diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e69de29
diff --git a/assets/textures/plants.json b/assets/textures/plants.json
index 9012e9d..8f8afc7 100644
--- a/assets/textures/plants.json
+++ b/assets/textures/plants.json
@@ -16,6 +16,7 @@
 		"sunflower_1":  {"frame": {"x": 16, "y": 0,  "w": 16, "h": 16}},
 		"sunflower_2":  {"frame": {"x": 32, "y": 0,  "w": 16, "h": 16}},
 		"sunflower_3":  {"frame": {"x": 48, "y": 0,  "w": 16, "h": 16}},
-		"sun":          {"frame": {"x": 16, "y": 48, "w": 16, "h": 16}}
+		"sun":          {"frame": {"x": 16, "y": 32, "w": 16, "h": 16}},
+		"heart":        {"frame": {"x": 32, "y": 32, "w": 16, "h": 16}}
 	}
 }
\ No newline at end of file
diff --git a/assets/textures/plants.png b/assets/textures/plants.png
index 3dccbf4..c8f6f86 100644
Binary files a/assets/textures/plants.png and b/assets/textures/plants.png differ
diff --git a/assets/textures/zombie.png b/assets/textures/zombie.png
index baf0a4f..95f3f3c 100644
Binary files a/assets/textures/zombie.png and b/assets/textures/zombie.png differ
diff --git a/css/fonts.css b/css/fonts.css
new file mode 100644
index 0000000..d9bd984
--- /dev/null
+++ b/css/fonts.css
@@ -0,0 +1,7 @@
+@font-face {
+  font-family: 'VT323';
+  font-style: normal;
+  font-weight: 400;
+  src: local('../assets/fonts/alterebro-pixel-font.ttf');
+  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
+}
\ No newline at end of file
diff --git a/index.html b/index.html
index 345116f..4840bfa 100644
--- a/index.html
+++ b/index.html
@@ -4,11 +4,16 @@
 	<title>Plants vs Campers</title>
 	<link href="css/styles.css" type="text/css" rel="stylesheet"/>
 	
+	<!-- Fonts -->
+	<link href='css/fonts.css' rel='stylesheet' type='text/css'>
+	
 	<!-- Load any external libraries -->
-	<script src="js/phaser.min.js"></script>
+	<script src="js/phaser/phaser.min.js"></script>
 	
 	<!-- Various misc bits of code -->
 	<script src="js/Props.js"></script>
+	<script src="js/cbd/GameObject.js"></script>
+	<script src="js/cbd/Component.js"></script>
 	<script src="js/Gui.js"></script>
 	<script src="js/Cursor.js"></script>
 	
@@ -17,7 +22,7 @@
 	<script src="js/Cloud.js"></script>
 	
 	<!-- Load in all the characters -->
-	<script src="js/plants/Plant.js"></script>
+	<script src="js/plants/Character.js"></script>
 	<script src="js/plants/Peashooter.js"></script>
 	<script src="js/plants/Sunflower.js"></script>
 	<script src="js/plants/Nut.js"></script>
diff --git a/js/Gui.js b/js/Gui.js
index 1415820..920727f 100644
--- a/js/Gui.js
+++ b/js/Gui.js
@@ -1,6 +1,43 @@
-function Gui() {
-    
-    
-    
-    
+function Gui(state) {
+	
+	this.heart = game.add.sprite(16, 16, 'plants');
+	this.heart.width = 64;
+	this.heart.height = 64;
+	this.heart.animations.add('full', ['heart'], 2, true, false);
+	this.heart.animations.add('med', ['heart'], 2, true, false);
+	this.heart.animations.add('low', ['heart'], 2, true, false);
+	this.heart.animations.play('full', 2, true);
+	
+	this.sun = game.add.sprite(80, 16, 'plants');
+	this.sun.width = 64;
+	this.sun.height = 64;
+	this.sun.animations.add('idle', ['sun'], 2, true, false);
+	this.sun.animations.play('idle', 2, true);
+	
+	var self = this; var i = 0;
+	['peashooter', 'sunflower', 'nut'].map(function(plant){
+		
+		var sprite = game.add.sprite(64 * i + 128, 16, 'plants');
+		
+		sprite.width = 64;
+		sprite.height = 64;
+		sprite.inputEnabled = true;
+		
+		sprite.animations.add('unselected', [plant + '_0'], 2, true, false);
+		sprite.animations.add('selected', [plant + '_1'], 2, true, false);
+		sprite.animations.play('unselected', 2, true);
+		
+		sprite.events.onInputDown.add(function(){
+			sprite.animations.play('selected', 2, true);
+		}, state);
+		
+		self[plant] = sprite;
+		i++;
+	});
+	
+	this.sunText = game.add.text(96, 128, '#FontFixBecauseExternalFontsDontWorkWellWithPhaser', {
+		'font': '40px Arial',
+		'fillStyle': 'black'
+	});
+	
 }
\ No newline at end of file
diff --git a/js/Sun.js b/js/Sun.js
index d9ca377..2a555d1 100644
--- a/js/Sun.js
+++ b/js/Sun.js
@@ -6,31 +6,29 @@ function Sun(manager, sprite_x, sprite_y) {
 	this.sprite.height = 64;
 	
 	this.props = new Props({
-	    speed: 50,
+	    speed: 80,
 	    cooldown: 1000
 	});
 	
 	this.collecting = false;
-	this.speed = 50;
-	this.spawnCountdown = 1;
+	
+	this.props.cooldown_timer = game.time.now;
 	
 	game.physics.arcade.enable(this.sprite);
 	this.sprite.body.acceleration = new Phaser.Point(0, 150);
 	this.sprite.body.velocity.y = -Math.random() * 50 - 50;
 	this.sprite.body.velocity.x = Math.random() * 30 - 10;
-	//this.sprite.body.velocity.x = this.props.speed;
 	
 	this.sprite.animations.add('idle', ['sun'], 2, true, false);
 	this.sprite.animations.play('idle', 2, true);
 }
 
 Sun.prototype.update = function() {
-    //If the sun is getting collected we don't need to check if
-    //the player is clicking on it
     var time_since = game.time.now - this.props.cooldown_timer;
     
+    //If the sun is getting collected we don't need to check if
+    //the player is clicking on it
     if(!this.collecting) {
-        
         //Stop moving the sun after about a second
         if(time_since >= this.props.cooldown) {
             this.sprite.body.velocity.x=0;
@@ -39,25 +37,28 @@ Sun.prototype.update = function() {
         }
         
         var mouseButton = game.input.activePointer.leftButton;
-        var mouse_x = game.input.mousePointer.x - this.manager.offsets.world_x; 
-        var mouse_y = game.input.mousePointer.y - this.manager.offsets.world_y;
+        var mouse_x = game.input.mousePointer.x; 
+        var mouse_y = game.input.mousePointer.y;
         
         //If the mouse button has been pressed in the last 50ms
         //We're gonna check if this sun got clicked on
         if(mouseButton.isDown && mouseButton.duration < 50) {
-            
-            if(this.sprite.x<mouse_x && this.sprite.x+this.sprite.width<mouse_x && this.sprite.y<mouse_y && this.sprite.y+this.sprite.height>mouse_y) {
+            if(this.sprite.x<mouse_x && this.sprite.x+this.sprite.width>mouse_x && this.sprite.y<mouse_y && this.sprite.y+this.sprite.height>mouse_y) {
                 this.collecting = true;
+                this.manager.money += 10;
+                this.manager.gui.sunText.text = this.manager.money.toString();
             }
         }
     }
     else {
+        this.props.speed += 5;
         var len = Math.sqrt(this.sprite.x*this.sprite.x+this.sprite.y*this.sprite.y);
-        this.sprite.body.velocity.x = this.speed*(-this.sprite.x) / len;
-        this.sprite.body.velocity.y = this.speed*(-this.sprite.y) / len;
-        if(len<150)
+        this.sprite.body.velocity.x = this.props.speed*(-this.sprite.x) / len + 100;
+        this.sprite.body.velocity.y = this.props.speed*(-this.sprite.y) / len + 100;
+        if(len<100)
             this.sprite.alpha -= 0.05;
-        if(len<50 && this.sprite.alpha<=0)
+        if(this.sprite.alpha<=0) {
             this.props.dead = true;
+        }
     }
 }
\ No newline at end of file
diff --git a/js/cbd/Component.js b/js/cbd/Component.js
index 7b9916d..fad0df8 100644
--- a/js/cbd/Component.js
+++ b/js/cbd/Component.js
@@ -1,3 +1,7 @@
 function Component (type) {
     this.type = type;
+}
+
+Component.prototype.update = function () {
+    
 }
\ No newline at end of file
diff --git a/js/cbd/GameObject.js b/js/cbd/GameObject.js
index ffc9bc7..10ba268 100644
--- a/js/cbd/GameObject.js
+++ b/js/cbd/GameObject.js
@@ -1,12 +1,21 @@
 function GameObject (name, tag, layer, row, column, components) {
+    
     this.name = name;
     this.tag = tag;
+    
+    this.props = new Props({
+		column: column,
+		row: row,
+		cooldown: 1000,
+		damage: 0,
+		speed: 100,
+		health: 2
+	});
     this.layer = layer;
-    this.row = row;
-    this.column = column;
     var attachedComponents = components;
 }
 
+
 GameObject.prototype.getColumnAndRow = function () {
     return [this.column, this.row];
 }
@@ -48,6 +57,33 @@ GameObject.prototype.compareLayer = function (layer) {
 
 GameObject.prototype.update = function () {
     for (var i = 0; i < this.attachedComponents[i]; i++) {
-        attachedComponents[i].update();
+        if (this.attachedComponents.update) {
+            this.attachedComponents[i].update();
+        }
     }
+}
+
+GameObject.prototype.render = function () {
+    for (var i = 0; i < this.attachedComponents[i]; i++) {
+        if (this.attachedComponents.render) {
+            this.attachedComponents[i].render();
+        }
+    }
+}
+
+function loadScript(url, callback)
+{
+    // Adding the script tag to the head as suggested before
+    var head = document.getElementsByTagName('head')[0];
+    var script = document.createElement('script');
+    script.type = 'text/javascript';
+    script.src = url;
+
+    // Then bind the event to the callback function.
+    // There are several events for cross browser compatibility.
+    script.onreadystatechange = callback;
+    script.onload = callback;
+
+    // Fire the loading
+    head.appendChild(script);
 }
\ No newline at end of file
diff --git a/js/main.js b/js/main.js
index 5e50997..9e319e3 100644
--- a/js/main.js
+++ b/js/main.js
@@ -18,7 +18,10 @@ function GameState() {
 		clouds: [],
 		suns: [],
 		spawn_timer: 0,
+		money: 100,
+		gui: null,
 		cursor: null,
+		gui: null,
 		setup: function(offsets) {
 			this.offsets = offsets;
 
@@ -56,6 +59,7 @@ function GameState() {
 				if(this.plants[i].props.row == row) {
 					if(closest == null || this.plants[i].sprite.x > closest.sprite.x) {
 						closest = this.plants[i];
+						//console.log(closest);
 					}
 				}
 			}
@@ -125,6 +129,23 @@ function GameState() {
 				(64 + this.offsets.margin_x) * column + this.offsets.world_x - this.offsets.spot_x,
 				(64 + this.offsets.margin_y) * row + this.offsets.world_y - this.offsets.spot_y
 			));
+		},
+		cleanup: function() {
+			
+			var objectArrays = ['plants', 'campers', 'peas', 'suns'];
+			
+			for(var i = 0; i < objectArrays.length; i++) {
+				
+				var objectArray = this[objectArrays[i]];
+				
+				var ii = 0; while(ii < objectArray.length) {
+					if(objectArray[ii].props.die) {
+						objectArray[ii].sprite.destroy();
+						objectArray.splice(ii, 1);
+					} ii++;
+				}
+			}
+			
 		}
 	};
 
@@ -156,100 +177,57 @@ GameState.prototype = {
 			spot_y: 0
 		});
 		
-		this.manager.addPlant(0, 0, 'basic');
-		this.manager.addPlant(0, 1, 'basic');
-		this.manager.addPlant(0, 2, 'basic');
-		this.manager.addPlant(0, 3, 'sunflower');
-		this.manager.addPlant(1, 3, 'nut');
-		this.manager.addPlant(0, 4, 'sunflower');
-		this.manager.addPlant(1, 4, 'nut');
-		this.manager.addSun(150,150);
+		for(var i = 0; i < this.manager.height; i++) {
+			this.manager.addPlant(0, i, 'basic');
+			this.manager.addPlant(1, i, 'sunflower');
+			this.manager.addPlant(2, i, 'nut');
+		}
 		
-		game.add.text(0, 0, 'Controls - Arrow keys to move cursor', {
-			'font': '24px Arial',
-			'fillStyle': 'black'
-		});
+		this.manager.gui = new Gui(this);
+		
+		var manager = this.manager;
+		window.setTimeout(function(){
+			manager.gui.sunText.text = manager.money.toString();
+		}, 100);
 	},
 	update: function() {
+		var manager = this.manager;
 		
 		// spawn a new camper every 2 seconds if theirs less than 10 in the game
-		var spawn_timer_difference = game.time.now - this.manager.spawn_timer;
-		
-		if(this.manager.campers.length < 1 && spawn_timer_difference >= 2000) {
-			var row = Math.floor(Math.random() * (this.manager.height - 1));
-			this.manager.addCamper(row, 'basic');
-			this.manager.spawn_timer = game.time.now;
+		var spawn_timer_difference = game.time.now - manager.spawn_timer;
+		if(manager.campers.length < 10 && spawn_timer_difference >= 2000) {
+			var row = Math.floor(Math.random() * (manager.height - 1));
+			manager.addCamper(row, 'basic');
+			manager.spawn_timer = game.time.now;
 		}
-		
-		// we use while loops below due to the fact that we're calling splice
-		// inside of them, using a while loop forces the length to be re-indexed
 
-		// update the plants
-		var i = 0; while(i < this.manager.plants.length) {
-		
-			this.manager.plants[i].update();
-			
-			i++;
-		}
+		manager.plants.map(function(plant){ plant.update(); });
+		manager.clouds.map(function(cloud){ cloud.update(); });
+		manager.suns.map(function(sun){ sun.update(); });
 
-		// update the campers
-		var i = 0; while(i < this.manager.campers.length) {
-			var camper = this.manager.campers[i];
-			
-			camper.update();
-			
-			if(camper.props.die) {
-				camper.sprite.destroy();
-				this.manager.campers.splice(i, 1);
-			}
-			
-			// this makes it so campers don't overlap
-			for(var c = 0; c < this.manager.campers.length; c++) {
-				game.physics.arcade.collide(camper.sprite, this.manager.campers[c].sprite);
-			}
-			
-			i++;
-		}
-		
-		// clean up any peas that have died
-		var i = 0; while(i < this.manager.peas.length) {
-			var pea = this.manager.peas[i];
-			
-			if(pea.props.die) {
-				pea.sprite.destroy();
-				this.manager.peas.splice(i, 1);
+		manager.campers.map(function(camper_a){
+			camper_a.update();
+			if(!camper_a.dying) {
+				manager.campers.map(function(camper_b){
+					if(!camper_b.dying) {
+						game.physics.arcade.collide(camper_a.sprite, camper_b.sprite);
+					}
+				});
 			}
-			
-			i++;
-		}
-		
+		});
 		
-		// check collisions between peas and campers
-		var i = 0; while(i < this.manager.peas.length) {
-			var pea = this.manager.peas[i];
-			
-			for(var c = 0; c < this.manager.campers.length; c++) {
-				var camper = this.manager.campers[c];
-				
+		manager.peas.map(function(pea){
+			manager.campers.map(function(camper){
 				if(game.physics.arcade.overlap(pea.sprite, camper.sprite)) {
 					pea.props.die = true;
 					camper.hit(pea.props.damage);
 				}
-			}
-			
-			i++;
-		}
-		
-		// Update the clouds
-		for (var i = 0; i < this.manager.clouds.length; i++) {
-			this.manager.clouds[i].update();
-		}
+			});
+		});
 		
-		for( var i=0; i<this.manager.suns.length; i++) {
-			this.manager.suns[i].update();
-		}
+		manager.cursor.update();
 		
-		this.manager.cursor.update();
+		manager.cleanup();
 	},
 	render: function() {
 		//for(var i = 0; i < this.manager.campers.length; i++) game.debug.body(this.manager.campers[i].sprite);
diff --git a/js/phaser.min.js b/js/phaser.min.js
deleted file mode 100644
index 3524cc9..0000000
--- a/js/phaser.min.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Phaser v2.4.2 - http://phaser.io - @photonstorm - (c) 2015 Photon Storm Ltd. */
-
-!function(a){if("object"==typeof exports)module.exports=a();else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.p2=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b){function c(){}var d=a("./Scalar");b.exports=c,c.lineInt=function(a,b,c){c=c||0;var e,f,g,h,i,j,k,l=[0,0];return e=a[1][1]-a[0][1],f=a[0][0]-a[1][0],g=e*a[0][0]+f*a[0][1],h=b[1][1]-b[0][1],i=b[0][0]-b[1][0],j=h*b[0][0]+i*b[0][1],k=e*i-h*f,d.eq(k,0,c)||(l[0]=(i*g-f*j)/k,l[1]=(e*j-h*g)/k),l},c.segmentsIntersect=function(a,b,c,d){var e=b[0]-a[0],f=b[1]-a[1],g=d[0]-c[0],h=d[1]-c[1];if(g*f-h*e==0)return!1;var i=(e*(c[1]-a[1])+f*(a[0]-c[0]))/(g*f-h*e),j=(g*(a[1]-c[1])+h*(c[0]-a[0]))/(h*e-g*f);return i>=0&&1>=i&&j>=0&&1>=j}},{"./Scalar":4}],2:[function(a,b){function c(){}b.exports=c,c.area=function(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1])},c.left=function(a,b,d){return c.area(a,b,d)>0},c.leftOn=function(a,b,d){return c.area(a,b,d)>=0},c.right=function(a,b,d){return c.area(a,b,d)<0},c.rightOn=function(a,b,d){return c.area(a,b,d)<=0};var d=[],e=[];c.collinear=function(a,b,f,g){if(g){var h=d,i=e;h[0]=b[0]-a[0],h[1]=b[1]-a[1],i[0]=f[0]-b[0],i[1]=f[1]-b[1];var j=h[0]*i[0]+h[1]*i[1],k=Math.sqrt(h[0]*h[0]+h[1]*h[1]),l=Math.sqrt(i[0]*i[0]+i[1]*i[1]),m=Math.acos(j/(k*l));return g>m}return 0==c.area(a,b,f)},c.sqdist=function(a,b){var c=b[0]-a[0],d=b[1]-a[1];return c*c+d*d}},{}],3:[function(a,b){function c(){this.vertices=[]}function d(a,b,c,d,e){e=e||0;var f=b[1]-a[1],h=a[0]-b[0],i=f*a[0]+h*a[1],j=d[1]-c[1],k=c[0]-d[0],l=j*c[0]+k*c[1],m=f*k-j*h;return g.eq(m,0,e)?[0,0]:[(k*i-h*l)/m,(f*l-j*i)/m]}var e=a("./Line"),f=a("./Point"),g=a("./Scalar");b.exports=c,c.prototype.at=function(a){var b=this.vertices,c=b.length;return b[0>a?a%c+c:a%c]},c.prototype.first=function(){return this.vertices[0]},c.prototype.last=function(){return this.vertices[this.vertices.length-1]},c.prototype.clear=function(){this.vertices.length=0},c.prototype.append=function(a,b,c){if("undefined"==typeof b)throw new Error("From is not given!");if("undefined"==typeof c)throw new Error("To is not given!");if(b>c-1)throw new Error("lol1");if(c>a.vertices.length)throw new Error("lol2");if(0>b)throw new Error("lol3");for(var d=b;c>d;d++)this.vertices.push(a.vertices[d])},c.prototype.makeCCW=function(){for(var a=0,b=this.vertices,c=1;c<this.vertices.length;++c)(b[c][1]<b[a][1]||b[c][1]==b[a][1]&&b[c][0]>b[a][0])&&(a=c);f.left(this.at(a-1),this.at(a),this.at(a+1))||this.reverse()},c.prototype.reverse=function(){for(var a=[],b=0,c=this.vertices.length;b!==c;b++)a.push(this.vertices.pop());this.vertices=a},c.prototype.isReflex=function(a){return f.right(this.at(a-1),this.at(a),this.at(a+1))};var h=[],i=[];c.prototype.canSee=function(a,b){var c,d,g=h,j=i;if(f.leftOn(this.at(a+1),this.at(a),this.at(b))&&f.rightOn(this.at(a-1),this.at(a),this.at(b)))return!1;d=f.sqdist(this.at(a),this.at(b));for(var k=0;k!==this.vertices.length;++k)if((k+1)%this.vertices.length!==a&&k!==a&&f.leftOn(this.at(a),this.at(b),this.at(k+1))&&f.rightOn(this.at(a),this.at(b),this.at(k))&&(g[0]=this.at(a),g[1]=this.at(b),j[0]=this.at(k),j[1]=this.at(k+1),c=e.lineInt(g,j),f.sqdist(this.at(a),c)<d))return!1;return!0},c.prototype.copy=function(a,b,d){var e=d||new c;if(e.clear(),b>a)for(var f=a;b>=f;f++)e.vertices.push(this.vertices[f]);else{for(var f=0;b>=f;f++)e.vertices.push(this.vertices[f]);for(var f=a;f<this.vertices.length;f++)e.vertices.push(this.vertices[f])}return e},c.prototype.getCutEdges=function(){for(var a=[],b=[],d=[],e=new c,f=Number.MAX_VALUE,g=0;g<this.vertices.length;++g)if(this.isReflex(g))for(var h=0;h<this.vertices.length;++h)if(this.canSee(g,h)){b=this.copy(g,h,e).getCutEdges(),d=this.copy(h,g,e).getCutEdges();for(var i=0;i<d.length;i++)b.push(d[i]);b.length<f&&(a=b,f=b.length,a.push([this.at(g),this.at(h)]))}return a},c.prototype.decomp=function(){var a=this.getCutEdges();return a.length>0?this.slice(a):[this]},c.prototype.slice=function(a){if(0==a.length)return[this];if(a instanceof Array&&a.length&&a[0]instanceof Array&&2==a[0].length&&a[0][0]instanceof Array){for(var b=[this],c=0;c<a.length;c++)for(var d=a[c],e=0;e<b.length;e++){var f=b[e],g=f.slice(d);if(g){b.splice(e,1),b.push(g[0],g[1]);break}}return b}var d=a,c=this.vertices.indexOf(d[0]),e=this.vertices.indexOf(d[1]);return-1!=c&&-1!=e?[this.copy(c,e),this.copy(e,c)]:!1},c.prototype.isSimple=function(){for(var a=this.vertices,b=0;b<a.length-1;b++)for(var c=0;b-1>c;c++)if(e.segmentsIntersect(a[b],a[b+1],a[c],a[c+1]))return!1;for(var b=1;b<a.length-2;b++)if(e.segmentsIntersect(a[0],a[a.length-1],a[b],a[b+1]))return!1;return!0},c.prototype.quickDecomp=function(a,b,e,g,h,i){h=h||100,i=i||0,g=g||25,a="undefined"!=typeof a?a:[],b=b||[],e=e||[];var j=[0,0],k=[0,0],l=[0,0],m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=new c,u=new c,v=this,w=this.vertices;if(w.length<3)return a;if(i++,i>h)return console.warn("quickDecomp: max level ("+h+") reached."),a;for(var x=0;x<this.vertices.length;++x)if(v.isReflex(x)){b.push(v.vertices[x]),m=n=Number.MAX_VALUE;for(var y=0;y<this.vertices.length;++y)f.left(v.at(x-1),v.at(x),v.at(y))&&f.rightOn(v.at(x-1),v.at(x),v.at(y-1))&&(l=d(v.at(x-1),v.at(x),v.at(y),v.at(y-1)),f.right(v.at(x+1),v.at(x),l)&&(o=f.sqdist(v.vertices[x],l),n>o&&(n=o,k=l,r=y))),f.left(v.at(x+1),v.at(x),v.at(y+1))&&f.rightOn(v.at(x+1),v.at(x),v.at(y))&&(l=d(v.at(x+1),v.at(x),v.at(y),v.at(y+1)),f.left(v.at(x-1),v.at(x),l)&&(o=f.sqdist(v.vertices[x],l),m>o&&(m=o,j=l,q=y)));if(r==(q+1)%this.vertices.length)l[0]=(k[0]+j[0])/2,l[1]=(k[1]+j[1])/2,e.push(l),q>x?(t.append(v,x,q+1),t.vertices.push(l),u.vertices.push(l),0!=r&&u.append(v,r,v.vertices.length),u.append(v,0,x+1)):(0!=x&&t.append(v,x,v.vertices.length),t.append(v,0,q+1),t.vertices.push(l),u.vertices.push(l),u.append(v,r,x+1));else{if(r>q&&(q+=this.vertices.length),p=Number.MAX_VALUE,r>q)return a;for(var y=r;q>=y;++y)f.leftOn(v.at(x-1),v.at(x),v.at(y))&&f.rightOn(v.at(x+1),v.at(x),v.at(y))&&(o=f.sqdist(v.at(x),v.at(y)),p>o&&(p=o,s=y%this.vertices.length));s>x?(t.append(v,x,s+1),0!=s&&u.append(v,s,w.length),u.append(v,0,x+1)):(0!=x&&t.append(v,x,w.length),t.append(v,0,s+1),u.append(v,s,x+1))}return t.vertices.length<u.vertices.length?(t.quickDecomp(a,b,e,g,h,i),u.quickDecomp(a,b,e,g,h,i)):(u.quickDecomp(a,b,e,g,h,i),t.quickDecomp(a,b,e,g,h,i)),a}return a.push(this),a},c.prototype.removeCollinearPoints=function(a){for(var b=0,c=this.vertices.length-1;this.vertices.length>3&&c>=0;--c)f.collinear(this.at(c-1),this.at(c),this.at(c+1),a)&&(this.vertices.splice(c%this.vertices.length,1),c--,b++);return b}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(a,b){function c(){}b.exports=c,c.eq=function(a,b,c){return c=c||0,Math.abs(a-b)<c}},{}],5:[function(a,b){b.exports={Polygon:a("./Polygon"),Point:a("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(a,b){b.exports={name:"p2",version:"0.7.0",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <schteppe@gmail.com> (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.0"}}},{}],7:[function(a,b){function c(a){this.lowerBound=d.create(),a&&a.lowerBound&&d.copy(this.lowerBound,a.lowerBound),this.upperBound=d.create(),a&&a.upperBound&&d.copy(this.upperBound,a.upperBound)}{var d=a("../math/vec2");a("../utils/Utils")}b.exports=c;var e=d.create();c.prototype.setFromPoints=function(a,b,c,f){var g=this.lowerBound,h=this.upperBound;"number"!=typeof c&&(c=0),0!==c?d.rotate(g,a[0],c):d.copy(g,a[0]),d.copy(h,g);for(var i=Math.cos(c),j=Math.sin(c),k=1;k<a.length;k++){var l=a[k];if(0!==c){var m=l[0],n=l[1];e[0]=i*m-j*n,e[1]=j*m+i*n,l=e}for(var o=0;2>o;o++)l[o]>h[o]&&(h[o]=l[o]),l[o]<g[o]&&(g[o]=l[o])}b&&(d.add(this.lowerBound,this.lowerBound,b),d.add(this.upperBound,this.upperBound,b)),f&&(this.lowerBound[0]-=f,this.lowerBound[1]-=f,this.upperBound[0]+=f,this.upperBound[1]+=f)},c.prototype.copy=function(a){d.copy(this.lowerBound,a.lowerBound),d.copy(this.upperBound,a.upperBound)},c.prototype.extend=function(a){for(var b=2;b--;){var c=a.lowerBound[b];this.lowerBound[b]>c&&(this.lowerBound[b]=c);var d=a.upperBound[b];this.upperBound[b]<d&&(this.upperBound[b]=d)}},c.prototype.overlaps=function(a){var b=this.lowerBound,c=this.upperBound,d=a.lowerBound,e=a.upperBound;return(d[0]<=c[0]&&c[0]<=e[0]||b[0]<=e[0]&&e[0]<=c[0])&&(d[1]<=c[1]&&c[1]<=e[1]||b[1]<=e[1]&&e[1]<=c[1])},c.prototype.containsPoint=function(a){var b=this.lowerBound,c=this.upperBound;return b[0]<=a[0]&&a[0]<=c[0]&&b[1]<=a[1]&&a[1]<=c[1]},c.prototype.overlapsRay=function(a){var b=1/a.direction[0],c=1/a.direction[1],d=(this.lowerBound[0]-a.from[0])*b,e=(this.upperBound[0]-a.from[0])*b,f=(this.lowerBound[1]-a.from[1])*c,g=(this.upperBound[1]-a.from[1])*c,h=Math.max(Math.max(Math.min(d,e),Math.min(f,g))),i=Math.min(Math.min(Math.max(d,e),Math.max(f,g)));return 0>i?-1:h>i?-1:h}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(a,b){function c(a){this.type=a,this.result=[],this.world=null,this.boundingVolumeType=c.AABB}var d=a("../math/vec2"),e=a("../objects/Body");b.exports=c,c.AABB=1,c.BOUNDING_CIRCLE=2,c.prototype.setWorld=function(a){this.world=a},c.prototype.getCollisionPairs=function(){};var f=d.create();c.boundingRadiusCheck=function(a,b){d.sub(f,a.position,b.position);var c=d.squaredLength(f),e=a.boundingRadius+b.boundingRadius;return e*e>=c},c.aabbCheck=function(a,b){return a.getAABB().overlaps(b.getAABB())},c.prototype.boundingVolumeCheck=function(a,b){var d;switch(this.boundingVolumeType){case c.BOUNDING_CIRCLE:d=c.boundingRadiusCheck(a,b);break;case c.AABB:d=c.aabbCheck(a,b);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return d},c.canCollide=function(a,b){var c=e.KINEMATIC,d=e.STATIC;return a.type===d&&b.type===d?!1:a.type===c&&b.type===d||a.type===d&&b.type===c?!1:a.type===c&&b.type===c?!1:a.sleepState===e.SLEEPING&&b.sleepState===e.SLEEPING?!1:a.sleepState===e.SLEEPING&&b.type===d||b.sleepState===e.SLEEPING&&a.type===d?!1:!0},c.NAIVE=1,c.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(a,b){function c(){d.call(this,d.NAIVE)}{var d=(a("../shapes/Circle"),a("../shapes/Plane"),a("../shapes/Shape"),a("../shapes/Particle"),a("../collision/Broadphase"));a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.getCollisionPairs=function(a){var b=a.bodies,c=this.result;c.length=0;for(var e=0,f=b.length;e!==f;e++)for(var g=b[e],h=0;e>h;h++){var i=b[h];d.canCollide(g,i)&&this.boundingVolumeCheck(g,i)&&c.push(g,i)}return c},c.prototype.aabbQuery=function(a,b,c){c=c||[];for(var d=a.bodies,e=0;e<d.length;e++){var f=d[e];f.aabbNeedsUpdate&&f.updateAABB(),f.aabb.overlaps(b)&&c.push(f)}return c}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(a,b){function c(){this.contactEquations=[],this.frictionEquations=[],this.enableFriction=!0,this.enabledEquations=!0,this.slipForce=10,this.frictionCoefficient=.3,this.surfaceVelocity=0,this.contactEquationPool=new j({size:32}),this.frictionEquationPool=new k({size:64}),this.restitution=0,this.stiffness=m.DEFAULT_STIFFNESS,this.relaxation=m.DEFAULT_RELAXATION,this.frictionStiffness=m.DEFAULT_STIFFNESS,this.frictionRelaxation=m.DEFAULT_RELAXATION,this.enableFrictionReduction=!0,this.collidingBodiesLastStep=new l,this.contactSkinSize=.01}function d(a,b){f.set(a.vertices[0],.5*-b.length,-b.radius),f.set(a.vertices[1],.5*b.length,-b.radius),f.set(a.vertices[2],.5*b.length,b.radius),f.set(a.vertices[3],.5*-b.length,b.radius)}function e(a,b,c,d){for(var e=S,i=T,j=U,k=V,l=a,m=b.vertices,n=null,o=0;o!==m.length+1;o++){var p=m[o%m.length],q=m[(o+1)%m.length];f.rotate(e,p,d),f.rotate(i,q,d),h(e,e,c),h(i,i,c),g(j,e,l),g(k,i,l);var r=f.crossLength(j,k);if(null===n&&(n=r),0>=r*n)return!1;n=r}return!0}var f=a("../math/vec2"),g=f.sub,h=f.add,i=f.dot,j=(a("../utils/Utils"),a("../utils/ContactEquationPool")),k=a("../utils/FrictionEquationPool"),l=a("../utils/TupleDictionary"),m=a("../equations/Equation"),n=(a("../equations/ContactEquation"),a("../equations/FrictionEquation"),a("../shapes/Circle")),o=a("../shapes/Convex"),p=a("../shapes/Shape"),q=(a("../objects/Body"),a("../shapes/Box"));b.exports=c;var r=f.fromValues(0,1),s=f.fromValues(0,0),t=f.fromValues(0,0),u=f.fromValues(0,0),v=f.fromValues(0,0),w=f.fromValues(0,0),x=f.fromValues(0,0),y=f.fromValues(0,0),z=f.fromValues(0,0),A=f.fromValues(0,0),B=f.fromValues(0,0),C=f.fromValues(0,0),D=f.fromValues(0,0),E=f.fromValues(0,0),F=f.fromValues(0,0),G=f.fromValues(0,0),H=f.fromValues(0,0),I=f.fromValues(0,0),J=f.fromValues(0,0),K=[],L=f.create(),M=f.create();c.prototype.bodiesOverlap=function(a,b){for(var c=L,d=M,e=0,f=a.shapes.length;e!==f;e++){var g=a.shapes[e];a.toWorldFrame(c,g.position);for(var h=0,i=b.shapes.length;h!==i;h++){var j=b.shapes[h];if(b.toWorldFrame(d,j.position),this[g.type|j.type](a,g,c,g.angle+a.angle,b,j,d,j.angle+b.angle,!0))return!0}}return!1},c.prototype.collidedLastStep=function(a,b){var c=0|a.id,d=0|b.id;return!!this.collidingBodiesLastStep.get(c,d)},c.prototype.reset=function(){this.collidingBodiesLastStep.reset();for(var a=this.contactEquations,b=a.length;b--;){var c=a[b],d=c.bodyA.id,e=c.bodyB.id;this.collidingBodiesLastStep.set(d,e,!0)}for(var f=this.contactEquations,g=this.frictionEquations,h=0;h<f.length;h++)this.contactEquationPool.release(f[h]);for(var h=0;h<g.length;h++)this.frictionEquationPool.release(g[h]);this.contactEquations.length=this.frictionEquations.length=0},c.prototype.createContactEquation=function(a,b,c,d){var e=this.contactEquationPool.get();return e.bodyA=a,e.bodyB=b,e.shapeA=c,e.shapeB=d,e.restitution=this.restitution,e.firstImpact=!this.collidedLastStep(a,b),e.stiffness=this.stiffness,e.relaxation=this.relaxation,e.needsUpdate=!0,e.enabled=this.enabledEquations,e.offset=this.contactSkinSize,e},c.prototype.createFrictionEquation=function(a,b,c,d){var e=this.frictionEquationPool.get();return e.bodyA=a,e.bodyB=b,e.shapeA=c,e.shapeB=d,e.setSlipForce(this.slipForce),e.frictionCoefficient=this.frictionCoefficient,e.relativeVelocity=this.surfaceVelocity,e.enabled=this.enabledEquations,e.needsUpdate=!0,e.stiffness=this.frictionStiffness,e.relaxation=this.frictionRelaxation,e.contactEquations.length=0,e},c.prototype.createFrictionFromContact=function(a){var b=this.createFrictionEquation(a.bodyA,a.bodyB,a.shapeA,a.shapeB);return f.copy(b.contactPointA,a.contactPointA),f.copy(b.contactPointB,a.contactPointB),f.rotate90cw(b.t,a.normalA),b.contactEquations.push(a),b},c.prototype.createFrictionFromAverage=function(a){{var b=this.contactEquations[this.contactEquations.length-1],c=this.createFrictionEquation(b.bodyA,b.bodyB,b.shapeA,b.shapeB),d=b.bodyA;b.bodyB}f.set(c.contactPointA,0,0),f.set(c.contactPointB,0,0),f.set(c.t,0,0);for(var e=0;e!==a;e++)b=this.contactEquations[this.contactEquations.length-1-e],b.bodyA===d?(f.add(c.t,c.t,b.normalA),f.add(c.contactPointA,c.contactPointA,b.contactPointA),f.add(c.contactPointB,c.contactPointB,b.contactPointB)):(f.sub(c.t,c.t,b.normalA),f.add(c.contactPointA,c.contactPointA,b.contactPointB),f.add(c.contactPointB,c.contactPointB,b.contactPointA)),c.contactEquations.push(b);var g=1/a;return f.scale(c.contactPointA,c.contactPointA,g),f.scale(c.contactPointB,c.contactPointB,g),f.normalize(c.t,c.t),f.rotate90cw(c.t,c.t),c},c.prototype[p.LINE|p.CONVEX]=c.prototype.convexLine=function(a,b,c,d,e,f,g,h,i){return i?!1:0},c.prototype[p.LINE|p.BOX]=c.prototype.lineBox=function(a,b,c,d,e,f,g,h,i){return i?!1:0};var N=new q({width:1,height:1}),O=f.create();c.prototype[p.CAPSULE|p.CONVEX]=c.prototype[p.CAPSULE|p.BOX]=c.prototype.convexCapsule=function(a,b,c,e,g,h,i,j,k){var l=O;f.set(l,h.length/2,0),f.rotate(l,l,j),f.add(l,l,i);var m=this.circleConvex(g,h,l,j,a,b,c,e,k,h.radius);f.set(l,-h.length/2,0),f.rotate(l,l,j),f.add(l,l,i);var n=this.circleConvex(g,h,l,j,a,b,c,e,k,h.radius);if(k&&(m||n))return!0;var o=N;d(o,h);var p=this.convexConvex(a,b,c,e,g,o,i,j,k);return p+m+n},c.prototype[p.CAPSULE|p.LINE]=c.prototype.lineCapsule=function(a,b,c,d,e,f,g,h,i){return i?!1:0};var P=f.create(),Q=f.create(),R=new q({width:1,height:1});c.prototype[p.CAPSULE|p.CAPSULE]=c.prototype.capsuleCapsule=function(a,b,c,e,g,h,i,j,k){for(var l,m=P,n=Q,o=0,p=0;2>p;p++){f.set(m,(0===p?-1:1)*b.length/2,0),f.rotate(m,m,e),f.add(m,m,c);for(var q=0;2>q;q++){f.set(n,(0===q?-1:1)*h.length/2,0),f.rotate(n,n,j),f.add(n,n,i),this.enableFrictionReduction&&(l=this.enableFriction,this.enableFriction=!1);var r=this.circleCircle(a,b,m,e,g,h,n,j,k,b.radius,h.radius);if(this.enableFrictionReduction&&(this.enableFriction=l),k&&r)return!0;o+=r}}this.enableFrictionReduction&&(l=this.enableFriction,this.enableFriction=!1);var s=R;d(s,b);var t=this.convexCapsule(a,s,c,e,g,h,i,j,k);if(this.enableFrictionReduction&&(this.enableFriction=l),k&&t)return!0;if(o+=t,this.enableFrictionReduction){var l=this.enableFriction;this.enableFriction=!1}d(s,h);var u=this.convexCapsule(g,s,i,j,a,b,c,e,k);return this.enableFrictionReduction&&(this.enableFriction=l),k&&u?!0:(o+=u,this.enableFrictionReduction&&o&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(o)),o)},c.prototype[p.LINE|p.LINE]=c.prototype.lineLine=function(a,b,c,d,e,f,g,h,i){return i?!1:0},c.prototype[p.PLANE|p.LINE]=c.prototype.planeLine=function(a,b,c,d,e,j,k,l,m){var n=s,o=t,p=u,q=v,B=w,C=x,D=y,E=z,F=A,G=K,H=0;f.set(n,-j.length/2,0),f.set(o,j.length/2,0),f.rotate(p,n,l),f.rotate(q,o,l),h(p,p,k),h(q,q,k),f.copy(n,p),f.copy(o,q),g(B,o,n),f.normalize(C,B),f.rotate90cw(F,C),f.rotate(E,r,d),G[0]=n,G[1]=o;for(var I=0;I<G.length;I++){var J=G[I];g(D,J,c);var L=i(D,E);if(0>L){if(m)return!0;var M=this.createContactEquation(a,e,b,j);H++,f.copy(M.normalA,E),f.normalize(M.normalA,M.normalA),f.scale(D,E,L),g(M.contactPointA,J,D),g(M.contactPointA,M.contactPointA,a.position),g(M.contactPointB,J,k),h(M.contactPointB,M.contactPointB,k),g(M.contactPointB,M.contactPointB,e.position),this.contactEquations.push(M),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}return m?!1:(this.enableFrictionReduction||H&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(H)),H)},c.prototype[p.PARTICLE|p.CAPSULE]=c.prototype.particleCapsule=function(a,b,c,d,e,f,g,h,i){return this.circleLine(a,b,c,d,e,f,g,h,i,f.radius,0)},c.prototype[p.CIRCLE|p.LINE]=c.prototype.circleLine=function(a,b,c,d,e,j,k,l,m,n,o){var n=n||0,o="undefined"!=typeof o?o:b.radius,p=s,q=t,r=u,G=v,H=w,I=x,J=y,L=z,M=A,N=B,O=C,P=D,Q=E,R=F,S=K;f.set(L,-j.length/2,0),f.set(M,j.length/2,0),f.rotate(N,L,l),f.rotate(O,M,l),h(N,N,k),h(O,O,k),f.copy(L,N),f.copy(M,O),g(I,M,L),f.normalize(J,I),f.rotate90cw(H,J),g(P,c,L);var T=i(P,H);g(G,L,k),g(Q,c,k);var U=o+n;if(Math.abs(T)<U){f.scale(p,H,T),g(r,c,p),f.scale(q,H,i(H,Q)),f.normalize(q,q),f.scale(q,q,n),h(r,r,q);var V=i(J,r),W=i(J,L),X=i(J,M);if(V>W&&X>V){if(m)return!0;var Y=this.createContactEquation(a,e,b,j);return f.scale(Y.normalA,p,-1),f.normalize(Y.normalA,Y.normalA),f.scale(Y.contactPointA,Y.normalA,o),h(Y.contactPointA,Y.contactPointA,c),g(Y.contactPointA,Y.contactPointA,a.position),g(Y.contactPointB,r,k),h(Y.contactPointB,Y.contactPointB,k),g(Y.contactPointB,Y.contactPointB,e.position),this.contactEquations.push(Y),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Y)),1}}S[0]=L,S[1]=M;for(var Z=0;Z<S.length;Z++){var $=S[Z];if(g(P,$,c),f.squaredLength(P)<Math.pow(U,2)){if(m)return!0;var Y=this.createContactEquation(a,e,b,j);return f.copy(Y.normalA,P),f.normalize(Y.normalA,Y.normalA),f.scale(Y.contactPointA,Y.normalA,o),h(Y.contactPointA,Y.contactPointA,c),g(Y.contactPointA,Y.contactPointA,a.position),g(Y.contactPointB,$,k),f.scale(R,Y.normalA,-n),h(Y.contactPointB,Y.contactPointB,R),h(Y.contactPointB,Y.contactPointB,k),g(Y.contactPointB,Y.contactPointB,e.position),this.contactEquations.push(Y),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Y)),1}}return 0},c.prototype[p.CIRCLE|p.CAPSULE]=c.prototype.circleCapsule=function(a,b,c,d,e,f,g,h,i){return this.circleLine(a,b,c,d,e,f,g,h,i,f.radius)},c.prototype[p.CIRCLE|p.CONVEX]=c.prototype[p.CIRCLE|p.BOX]=c.prototype.circleConvex=function(a,b,c,d,i,j,k,l,m,n){for(var n="number"==typeof n?n:b.radius,o=s,p=t,q=u,r=v,x=w,y=B,z=C,A=E,D=F,I=G,J=H,K=!1,L=Number.MAX_VALUE,M=j.vertices,N=0;N!==M.length+1;N++){var O=M[N%M.length],P=M[(N+1)%M.length];if(f.rotate(o,O,l),f.rotate(p,P,l),h(o,o,k),h(p,p,k),g(q,p,o),f.normalize(r,q),f.rotate90cw(x,r),f.scale(D,x,-b.radius),h(D,D,c),e(D,j,k,l)){f.sub(I,o,D);var Q=Math.abs(f.dot(I,x));L>Q&&(f.copy(J,D),L=Q,f.scale(A,x,Q),f.add(A,A,D),K=!0)}}if(K){if(m)return!0;var R=this.createContactEquation(a,i,b,j);return f.sub(R.normalA,J,c),f.normalize(R.normalA,R.normalA),f.scale(R.contactPointA,R.normalA,n),h(R.contactPointA,R.contactPointA,c),g(R.contactPointA,R.contactPointA,a.position),g(R.contactPointB,A,k),h(R.contactPointB,R.contactPointB,k),g(R.contactPointB,R.contactPointB,i.position),this.contactEquations.push(R),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(R)),1}if(n>0)for(var N=0;N<M.length;N++){var S=M[N];if(f.rotate(z,S,l),h(z,z,k),g(y,z,c),f.squaredLength(y)<Math.pow(n,2)){if(m)return!0;var R=this.createContactEquation(a,i,b,j);return f.copy(R.normalA,y),f.normalize(R.normalA,R.normalA),f.scale(R.contactPointA,R.normalA,n),h(R.contactPointA,R.contactPointA,c),g(R.contactPointA,R.contactPointA,a.position),g(R.contactPointB,z,k),h(R.contactPointB,R.contactPointB,k),g(R.contactPointB,R.contactPointB,i.position),this.contactEquations.push(R),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(R)),1}}return 0};var S=f.create(),T=f.create(),U=f.create(),V=f.create();c.prototype[p.PARTICLE|p.CONVEX]=c.prototype[p.PARTICLE|p.BOX]=c.prototype.particleConvex=function(a,b,c,d,j,k,l,m,n){var o=s,p=t,q=u,r=v,z=w,A=x,C=y,D=B,F=E,G=I,H=J,K=Number.MAX_VALUE,L=!1,M=k.vertices;if(!e(c,k,l,m))return 0;if(n)return!0;for(var N=0;N!==M.length+1;N++){var O=M[N%M.length],P=M[(N+1)%M.length];f.rotate(o,O,m),f.rotate(p,P,m),h(o,o,l),h(p,p,l),g(q,p,o),f.normalize(r,q),f.rotate90cw(z,r),g(D,c,o);{i(D,z)}g(A,o,l),g(C,c,l),f.sub(G,o,c);var Q=Math.abs(f.dot(G,z));K>Q&&(K=Q,f.scale(F,z,Q),f.add(F,F,c),f.copy(H,z),L=!0)}if(L){var R=this.createContactEquation(a,j,b,k);return f.scale(R.normalA,H,-1),f.normalize(R.normalA,R.normalA),f.set(R.contactPointA,0,0),h(R.contactPointA,R.contactPointA,c),g(R.contactPointA,R.contactPointA,a.position),g(R.contactPointB,F,l),h(R.contactPointB,R.contactPointB,l),g(R.contactPointB,R.contactPointB,j.position),this.contactEquations.push(R),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(R)),1}return 0},c.prototype[p.CIRCLE]=c.prototype.circleCircle=function(a,b,c,d,e,i,j,k,l,m,n){var o=s,m=m||b.radius,n=n||i.radius;g(o,c,j);var p=m+n;if(f.squaredLength(o)>Math.pow(p,2))return 0;if(l)return!0;var q=this.createContactEquation(a,e,b,i);return g(q.normalA,j,c),f.normalize(q.normalA,q.normalA),f.scale(q.contactPointA,q.normalA,m),f.scale(q.contactPointB,q.normalA,-n),h(q.contactPointA,q.contactPointA,c),g(q.contactPointA,q.contactPointA,a.position),h(q.contactPointB,q.contactPointB,j),g(q.contactPointB,q.contactPointB,e.position),this.contactEquations.push(q),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(q)),1},c.prototype[p.PLANE|p.CONVEX]=c.prototype[p.PLANE|p.BOX]=c.prototype.planeConvex=function(a,b,c,d,e,j,k,l,m){var n=s,o=t,p=u,q=0;f.rotate(o,r,d);for(var v=0;v!==j.vertices.length;v++){var w=j.vertices[v];if(f.rotate(n,w,l),h(n,n,k),g(p,n,c),i(p,o)<=0){if(m)return!0;q++;var x=this.createContactEquation(a,e,b,j);g(p,n,c),f.copy(x.normalA,o);var y=i(p,x.normalA);f.scale(p,x.normalA,y),g(x.contactPointB,n,e.position),g(x.contactPointA,n,p),g(x.contactPointA,x.contactPointA,a.position),this.contactEquations.push(x),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(x))}}return this.enableFrictionReduction&&this.enableFriction&&q&&this.frictionEquations.push(this.createFrictionFromAverage(q)),q},c.prototype[p.PARTICLE|p.PLANE]=c.prototype.particlePlane=function(a,b,c,d,e,h,j,k,l){var m=s,n=t;k=k||0,g(m,c,j),f.rotate(n,r,k);var o=i(m,n);if(o>0)return 0;if(l)return!0;var p=this.createContactEquation(e,a,h,b);return f.copy(p.normalA,n),f.scale(m,p.normalA,o),g(p.contactPointA,c,m),g(p.contactPointA,p.contactPointA,e.position),g(p.contactPointB,c,a.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1},c.prototype[p.CIRCLE|p.PARTICLE]=c.prototype.circleParticle=function(a,b,c,d,e,i,j,k,l){var m=s;if(g(m,j,c),f.squaredLength(m)>Math.pow(b.radius,2))return 0;if(l)return!0;var n=this.createContactEquation(a,e,b,i);return f.copy(n.normalA,m),f.normalize(n.normalA,n.normalA),f.scale(n.contactPointA,n.normalA,b.radius),h(n.contactPointA,n.contactPointA,c),g(n.contactPointA,n.contactPointA,a.position),g(n.contactPointB,j,e.position),this.contactEquations.push(n),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(n)),1};{var W=new n({radius:1}),X=f.create(),Y=f.create();f.create()}c.prototype[p.PLANE|p.CAPSULE]=c.prototype.planeCapsule=function(a,b,c,d,e,g,i,j,k){var l=X,m=Y,n=W;f.set(l,-g.length/2,0),f.rotate(l,l,j),h(l,l,i),f.set(m,g.length/2,0),f.rotate(m,m,j),h(m,m,i),n.radius=g.radius;var o;this.enableFrictionReduction&&(o=this.enableFriction,this.enableFriction=!1);var p=this.circlePlane(e,n,l,0,a,b,c,d,k),q=this.circlePlane(e,n,m,0,a,b,c,d,k);if(this.enableFrictionReduction&&(this.enableFriction=o),k)return p||q;var r=p+q;return this.enableFrictionReduction&&r&&this.frictionEquations.push(this.createFrictionFromAverage(r)),r},c.prototype[p.CIRCLE|p.PLANE]=c.prototype.circlePlane=function(a,b,c,d,e,j,k,l,m){var n=a,o=b,p=c,q=e,v=k,w=l;w=w||0;var x=s,y=t,z=u;g(x,p,v),f.rotate(y,r,w);var A=i(y,x);if(A>o.radius)return 0;if(m)return!0;var B=this.createContactEquation(q,n,j,b);return f.copy(B.normalA,y),f.scale(B.contactPointB,B.normalA,-o.radius),h(B.contactPointB,B.contactPointB,p),g(B.contactPointB,B.contactPointB,n.position),f.scale(z,B.normalA,A),g(B.contactPointA,x,z),h(B.contactPointA,B.contactPointA,v),g(B.contactPointA,B.contactPointA,q.position),this.contactEquations.push(B),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(B)),1},c.prototype[p.CONVEX]=c.prototype[p.CONVEX|p.BOX]=c.prototype[p.BOX]=c.prototype.convexConvex=function(a,b,d,e,j,k,l,m,n,o){var p=s,q=t,r=u,x=v,B=w,C=y,D=z,E=A,F=0,o="number"==typeof o?o:0,G=c.findSeparatingAxis(b,d,e,k,l,m,p);if(!G)return 0;g(D,l,d),i(p,D)>0&&f.scale(p,p,-1);var H=c.getClosestEdge(b,e,p,!0),I=c.getClosestEdge(k,m,p);if(-1===H||-1===I)return 0;for(var J=0;2>J;J++){var K=H,L=I,M=b,N=k,O=d,P=l,Q=e,R=m,S=a,T=j;if(0===J){var U;U=K,K=L,L=U,U=M,M=N,N=U,U=O,O=P,P=U,U=Q,Q=R,R=U,U=S,S=T,T=U}for(var V=L;L+2>V;V++){var W=N.vertices[(V+N.vertices.length)%N.vertices.length];f.rotate(q,W,R),h(q,q,P);for(var X=0,Y=K-1;K+2>Y;Y++){var Z=M.vertices[(Y+M.vertices.length)%M.vertices.length],$=M.vertices[(Y+1+M.vertices.length)%M.vertices.length];f.rotate(r,Z,Q),f.rotate(x,$,Q),h(r,r,O),h(x,x,O),g(B,x,r),f.rotate90cw(E,B),f.normalize(E,E),g(D,q,r);var _=i(E,D);(Y===K&&o>=_||Y!==K&&0>=_)&&X++}if(X>=3){if(n)return!0;var ab=this.createContactEquation(S,T,M,N);F++;var Z=M.vertices[K%M.vertices.length],$=M.vertices[(K+1)%M.vertices.length];f.rotate(r,Z,Q),f.rotate(x,$,Q),h(r,r,O),h(x,x,O),g(B,x,r),f.rotate90cw(ab.normalA,B),f.normalize(ab.normalA,ab.normalA),g(D,q,r);var _=i(ab.normalA,D);f.scale(C,ab.normalA,_),g(ab.contactPointA,q,O),g(ab.contactPointA,ab.contactPointA,C),h(ab.contactPointA,ab.contactPointA,O),g(ab.contactPointA,ab.contactPointA,S.position),g(ab.contactPointB,q,P),h(ab.contactPointB,ab.contactPointB,P),g(ab.contactPointB,ab.contactPointB,T.position),this.contactEquations.push(ab),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(ab))}}}return this.enableFrictionReduction&&this.enableFriction&&F&&this.frictionEquations.push(this.createFrictionFromAverage(F)),F};var Z=f.fromValues(0,0);c.projectConvexOntoAxis=function(a,b,c,d,e){var g,h,j=null,k=null,l=Z;f.rotate(l,d,-c);for(var m=0;m<a.vertices.length;m++)g=a.vertices[m],h=i(g,l),(null===j||h>j)&&(j=h),(null===k||k>h)&&(k=h);if(k>j){var n=k;k=j,j=n}var o=i(b,d);f.set(e,k+o,j+o)};var $=f.fromValues(0,0),_=f.fromValues(0,0),ab=f.fromValues(0,0),bb=f.fromValues(0,0),cb=f.fromValues(0,0),db=f.fromValues(0,0);c.findSeparatingAxis=function(a,b,d,e,h,i,j){var k=null,l=!1,m=!1,n=$,o=_,p=ab,r=bb,s=cb,t=db;if(a instanceof q&&e instanceof q)for(var u=0;2!==u;u++){var v=a,w=d;1===u&&(v=e,w=i);for(var x=0;2!==x;x++){0===x?f.set(r,0,1):1===x&&f.set(r,1,0),0!==w&&f.rotate(r,r,w),c.projectConvexOntoAxis(a,b,d,r,s),c.projectConvexOntoAxis(e,h,i,r,t);var y=s,z=t,A=!1;s[0]>t[0]&&(z=s,y=t,A=!0);var B=z[0]-y[1];l=0>=B,(null===k||B>k)&&(f.copy(j,r),k=B,m=l)}}else for(var u=0;2!==u;u++){var v=a,w=d;1===u&&(v=e,w=i);for(var x=0;x!==v.vertices.length;x++){f.rotate(o,v.vertices[x],w),f.rotate(p,v.vertices[(x+1)%v.vertices.length],w),g(n,p,o),f.rotate90cw(r,n),f.normalize(r,r),c.projectConvexOntoAxis(a,b,d,r,s),c.projectConvexOntoAxis(e,h,i,r,t);var y=s,z=t,A=!1;s[0]>t[0]&&(z=s,y=t,A=!0);var B=z[0]-y[1];l=0>=B,(null===k||B>k)&&(f.copy(j,r),k=B,m=l)}}return m};var eb=f.fromValues(0,0),fb=f.fromValues(0,0),gb=f.fromValues(0,0);c.getClosestEdge=function(a,b,c,d){var e=eb,h=fb,j=gb;f.rotate(e,c,-b),d&&f.scale(e,e,-1);for(var k=-1,l=a.vertices.length,m=-1,n=0;n!==l;n++){g(h,a.vertices[(n+1)%l],a.vertices[n%l]),f.rotate90cw(j,h),f.normalize(j,j);var o=i(j,e);(-1===k||o>m)&&(k=n%l,m=o)}return k};var hb=f.create(),ib=f.create(),jb=f.create(),kb=f.create(),lb=f.create(),mb=f.create(),nb=f.create();c.prototype[p.CIRCLE|p.HEIGHTFIELD]=c.prototype.circleHeightfield=function(a,b,c,d,e,i,j,k,l,m){var n=i.heights,m=m||b.radius,o=i.elementWidth,p=ib,q=hb,r=lb,s=nb,t=mb,u=jb,v=kb,w=Math.floor((c[0]-m-j[0])/o),x=Math.ceil((c[0]+m-j[0])/o);0>w&&(w=0),x>=n.length&&(x=n.length-1);for(var y=n[w],z=n[x],A=w;x>A;A++)n[A]<z&&(z=n[A]),n[A]>y&&(y=n[A]);if(c[1]-m>y)return l?!1:0;for(var B=!1,A=w;x>A;A++){f.set(u,A*o,n[A]),f.set(v,(A+1)*o,n[A+1]),f.add(u,u,j),f.add(v,v,j),f.sub(t,v,u),f.rotate(t,t,Math.PI/2),f.normalize(t,t),f.scale(q,t,-m),f.add(q,q,c),f.sub(p,q,u);var C=f.dot(p,t);if(q[0]>=u[0]&&q[0]<v[0]&&0>=C){if(l)return!0;B=!0,f.scale(p,t,-C),f.add(r,q,p),f.copy(s,t);var D=this.createContactEquation(e,a,i,b);f.copy(D.normalA,s),f.scale(D.contactPointB,D.normalA,-m),h(D.contactPointB,D.contactPointB,c),g(D.contactPointB,D.contactPointB,a.position),f.copy(D.contactPointA,r),f.sub(D.contactPointA,D.contactPointA,e.position),this.contactEquations.push(D),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(D))}}if(B=!1,m>0)for(var A=w;x>=A;A++)if(f.set(u,A*o,n[A]),f.add(u,u,j),f.sub(p,c,u),f.squaredLength(p)<Math.pow(m,2)){if(l)return!0;B=!0;var D=this.createContactEquation(e,a,i,b);
-f.copy(D.normalA,p),f.normalize(D.normalA,D.normalA),f.scale(D.contactPointB,D.normalA,-m),h(D.contactPointB,D.contactPointB,c),g(D.contactPointB,D.contactPointB,a.position),g(D.contactPointA,u,j),h(D.contactPointA,D.contactPointA,j),g(D.contactPointA,D.contactPointA,e.position),this.contactEquations.push(D),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(D))}return B?1:0};var ob=f.create(),pb=f.create(),qb=f.create(),rb=new o({vertices:[f.create(),f.create(),f.create(),f.create()]});c.prototype[p.BOX|p.HEIGHTFIELD]=c.prototype[p.CONVEX|p.HEIGHTFIELD]=c.prototype.convexHeightfield=function(a,b,c,d,e,g,h,i,j){var k=g.heights,l=g.elementWidth,m=ob,n=pb,o=qb,p=rb,q=Math.floor((a.aabb.lowerBound[0]-h[0])/l),r=Math.ceil((a.aabb.upperBound[0]-h[0])/l);0>q&&(q=0),r>=k.length&&(r=k.length-1);for(var s=k[q],t=k[r],u=q;r>u;u++)k[u]<t&&(t=k[u]),k[u]>s&&(s=k[u]);if(a.aabb.lowerBound[1]>s)return j?!1:0;for(var v=0,u=q;r>u;u++){f.set(m,u*l,k[u]),f.set(n,(u+1)*l,k[u+1]),f.add(m,m,h),f.add(n,n,h);var w=100;f.set(o,.5*(n[0]+m[0]),.5*(n[1]+m[1]-w)),f.sub(p.vertices[0],n,o),f.sub(p.vertices[1],m,o),f.copy(p.vertices[2],p.vertices[1]),f.copy(p.vertices[3],p.vertices[0]),p.vertices[2][1]-=w,p.vertices[3][1]-=w,v+=this.convexConvex(a,b,c,d,e,p,o,0,j)}return v}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(a,b){function c(a){a=a||{},this.from=a.from?e.fromValues(a.from[0],a.from[1]):e.create(),this.to=a.to?e.fromValues(a.to[0],a.to[1]):e.create(),this.checkCollisionResponse=void 0!==a.checkCollisionResponse?a.checkCollisionResponse:!0,this.skipBackfaces=!!a.skipBackfaces,this.collisionMask=void 0!==a.collisionMask?a.collisionMask:-1,this.collisionGroup=void 0!==a.collisionGroup?a.collisionGroup:-1,this.mode=void 0!==a.mode?a.mode:c.ANY,this.callback=a.callback||function(){},this.direction=e.create(),this.length=1,this.update()}function d(a,b,c){e.sub(g,c,a);var d=e.dot(g,b);return e.scale(h,b,d),e.add(h,h,a),e.squaredDistance(c,h)}b.exports=c;{var e=a("../math/vec2");a("../collision/RaycastResult"),a("../shapes/Shape"),a("../collision/AABB")}c.prototype.constructor=c,c.CLOSEST=1,c.ANY=2,c.ALL=4,c.prototype.update=function(){var a=this.direction;e.sub(a,this.to,this.from),this.length=e.length(a),e.normalize(a,a)},c.prototype.intersectBodies=function(a,b){for(var c=0,d=b.length;!a.shouldStop(this)&&d>c;c++){var e=b[c],f=e.getAABB();(f.overlapsRay(this)>=0||f.containsPoint(this.from))&&this.intersectBody(a,e)}};var f=e.create();c.prototype.intersectBody=function(a,b){var c=this.checkCollisionResponse;if(!c||b.collisionResponse)for(var d=f,g=0,h=b.shapes.length;h>g;g++){var i=b.shapes[g];if((!c||i.collisionResponse)&&0!==(this.collisionGroup&i.collisionMask)&&0!==(i.collisionGroup&this.collisionMask)){e.rotate(d,i.position,b.angle),e.add(d,d,b.position);var j=i.angle+b.angle;if(this.intersectShape(a,i,j,d,b),a.shouldStop(this))break}}},c.prototype.intersectShape=function(a,b,c,e,f){var g=this.from,h=d(g,this.direction,e);h>b.boundingRadius*b.boundingRadius||(this._currentBody=f,this._currentShape=b,b.raycast(a,this,e,c),this._currentBody=this._currentShape=null)},c.prototype.getAABB=function(a){var b=this.to,c=this.from;e.set(a.lowerBound,Math.min(b[0],c[0]),Math.min(b[1],c[1])),e.set(a.upperBound,Math.max(b[0],c[0]),Math.max(b[1],c[1]))};e.create();c.prototype.reportIntersection=function(a,b,d,f){var g=(this.from,this.to,this._currentShape),h=this._currentBody;if(!(this.skipBackfaces&&e.dot(d,this.direction)>0))switch(this.mode){case c.ALL:a.set(d,g,h,b,f),this.callback(a);break;case c.CLOSEST:(b<a.fraction||!a.hasHit())&&a.set(d,g,h,b,f);break;case c.ANY:a.set(d,g,h,b,f)}};var g=e.create(),h=e.create()},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(a,b){function c(){this.normal=d.create(),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1}var d=a("../math/vec2"),e=a("../collision/Ray");b.exports=c,c.prototype.reset=function(){d.set(this.normal,0,0),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1},c.prototype.getHitDistance=function(a){return d.distance(a.from,a.to)*this.fraction},c.prototype.hasHit=function(){return-1!==this.fraction},c.prototype.getHitPoint=function(a,b){d.lerp(a,b.from,b.to,this.fraction)},c.prototype.stop=function(){this.isStopped=!0},c.prototype.shouldStop=function(a){return this.isStopped||-1!==this.fraction&&a.mode===e.ANY},c.prototype.set=function(a,b,c,e,f){d.copy(this.normal,a),this.shape=b,this.body=c,this.fraction=e,this.faceIndex=f}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(a,b){function c(){e.call(this,e.SAP),this.axisList=[],this.axisIndex=0;var a=this;this._addBodyHandler=function(b){a.axisList.push(b.body)},this._removeBodyHandler=function(b){var c=a.axisList.indexOf(b.body);-1!==c&&a.axisList.splice(c,1)}}var d=a("../utils/Utils"),e=a("../collision/Broadphase");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.setWorld=function(a){this.axisList.length=0,d.appendArray(this.axisList,a.bodies),a.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler),a.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler),this.world=a},c.sortAxisList=function(a,b){b=0|b;for(var c=1,d=a.length;d>c;c++){for(var e=a[c],f=c-1;f>=0&&!(a[f].aabb.lowerBound[b]<=e.aabb.lowerBound[b]);f--)a[f+1]=a[f];a[f+1]=e}return a},c.prototype.sortList=function(){var a=this.axisList,b=this.axisIndex;c.sortAxisList(a,b)},c.prototype.getCollisionPairs=function(){var a=this.axisList,b=this.result,c=this.axisIndex;b.length=0;for(var d=a.length;d--;){var f=a[d];f.aabbNeedsUpdate&&f.updateAABB()}this.sortList();for(var g=0,h=0|a.length;g!==h;g++)for(var i=a[g],j=g+1;h>j;j++){var k=a[j],l=k.aabb.lowerBound[c]<=i.aabb.upperBound[c];if(!l)break;e.canCollide(i,k)&&this.boundingVolumeCheck(i,k)&&b.push(i,k)}return b},c.prototype.aabbQuery=function(a,b,c){c=c||[],this.sortList();var d=this.axisIndex,e="x";1===d&&(e="y"),2===d&&(e="z");for(var f=this.axisList,g=(b.lowerBound[e],b.upperBound[e],0);g<f.length;g++){var h=f[g];h.aabbNeedsUpdate&&h.updateAABB(),h.aabb.overlaps(b)&&c.push(h)}return c}},{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(a,b){function c(a,b,c,e){this.type=c,e=d.defaults(e,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=a,this.bodyB=b,this.collideConnected=e.collideConnected,e.wakeUpBodies&&(a&&a.wakeUp(),b&&b.wakeUp())}b.exports=c;var d=a("../utils/Utils");c.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},c.DISTANCE=1,c.GEAR=2,c.LOCK=3,c.PRISMATIC=4,c.REVOLUTE=5,c.prototype.setStiffness=function(a){for(var b=this.equations,c=0;c!==b.length;c++){var d=b[c];d.stiffness=a,d.needsUpdate=!0}},c.prototype.setRelaxation=function(a){for(var b=this.equations,c=0;c!==b.length;c++){var d=b[c];d.relaxation=a,d.needsUpdate=!0}}},{"../utils/Utils":57}],15:[function(a,b){function c(a,b,c){c=g.defaults(c,{localAnchorA:[0,0],localAnchorB:[0,0]}),d.call(this,a,b,d.DISTANCE,c),this.localAnchorA=f.fromValues(c.localAnchorA[0],c.localAnchorA[1]),this.localAnchorB=f.fromValues(c.localAnchorB[0],c.localAnchorB[1]);var h=this.localAnchorA,i=this.localAnchorB;if(this.distance=0,"number"==typeof c.distance)this.distance=c.distance;else{var j=f.create(),k=f.create(),l=f.create();f.rotate(j,h,a.angle),f.rotate(k,i,b.angle),f.add(l,b.position,k),f.sub(l,l,j),f.sub(l,l,a.position),this.distance=f.length(l)}var m;m="undefined"==typeof c.maxForce?Number.MAX_VALUE:c.maxForce;var n=new e(a,b,-m,m);this.equations=[n],this.maxForce=m;var l=f.create(),o=f.create(),p=f.create(),q=this;n.computeGq=function(){var a=this.bodyA,b=this.bodyB,c=a.position,d=b.position;return f.rotate(o,h,a.angle),f.rotate(p,i,b.angle),f.add(l,d,p),f.sub(l,l,o),f.sub(l,l,c),f.length(l)-q.distance},this.setMaxForce(m),this.upperLimitEnabled=!1,this.upperLimit=1,this.lowerLimitEnabled=!1,this.lowerLimit=0,this.position=0}var d=a("./Constraint"),e=a("../equations/Equation"),f=a("../math/vec2"),g=a("../utils/Utils");b.exports=c,c.prototype=new d,c.prototype.constructor=c;var h=f.create(),i=f.create(),j=f.create();c.prototype.update=function(){var a=this.equations[0],b=this.bodyA,c=this.bodyB,d=(this.distance,b.position),e=c.position,g=this.equations[0],k=a.G;f.rotate(i,this.localAnchorA,b.angle),f.rotate(j,this.localAnchorB,c.angle),f.add(h,e,j),f.sub(h,h,i),f.sub(h,h,d),this.position=f.length(h);var l=!1;if(this.upperLimitEnabled&&this.position>this.upperLimit&&(g.maxForce=0,g.minForce=-this.maxForce,this.distance=this.upperLimit,l=!0),this.lowerLimitEnabled&&this.position<this.lowerLimit&&(g.maxForce=this.maxForce,g.minForce=0,this.distance=this.lowerLimit,l=!0),(this.lowerLimitEnabled||this.upperLimitEnabled)&&!l)return void(g.enabled=!1);g.enabled=!0,f.normalize(h,h);var m=f.crossLength(i,h),n=f.crossLength(j,h);k[0]=-h[0],k[1]=-h[1],k[2]=-m,k[3]=h[0],k[4]=h[1],k[5]=n},c.prototype.setMaxForce=function(a){var b=this.equations[0];b.minForce=-a,b.maxForce=a},c.prototype.getMaxForce=function(){var a=this.equations[0];return a.maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.GEAR,c),this.ratio=void 0!==c.ratio?c.ratio:1,this.angle=void 0!==c.angle?c.angle:b.angle-this.ratio*a.angle,c.angle=this.angle,c.ratio=this.ratio,this.equations=[new e(a,b,c)],void 0!==c.maxTorque&&this.setMaxTorque(c.maxTorque)}{var d=a("./Constraint"),e=(a("../equations/Equation"),a("../equations/AngleLockEquation"));a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.update=function(){var a=this.equations[0];a.ratio!==this.ratio&&a.setRatio(this.ratio),a.angle=this.angle},c.prototype.setMaxTorque=function(a){this.equations[0].setMaxTorque(a)},c.prototype.getMaxTorque=function(){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.LOCK,c);var g="undefined"==typeof c.maxForce?Number.MAX_VALUE:c.maxForce,h=(c.localAngleB||0,new f(a,b,-g,g)),i=new f(a,b,-g,g),j=new f(a,b,-g,g),k=e.create(),l=e.create(),m=this;h.computeGq=function(){return e.rotate(k,m.localOffsetB,a.angle),e.sub(l,b.position,a.position),e.sub(l,l,k),l[0]},i.computeGq=function(){return e.rotate(k,m.localOffsetB,a.angle),e.sub(l,b.position,a.position),e.sub(l,l,k),l[1]};var n=e.create(),o=e.create();j.computeGq=function(){return e.rotate(n,m.localOffsetB,b.angle-m.localAngleB),e.scale(n,n,-1),e.sub(l,a.position,b.position),e.add(l,l,n),e.rotate(o,n,-Math.PI/2),e.normalize(o,o),e.dot(l,o)},this.localOffsetB=e.create(),c.localOffsetB?e.copy(this.localOffsetB,c.localOffsetB):(e.sub(this.localOffsetB,b.position,a.position),e.rotate(this.localOffsetB,this.localOffsetB,-a.angle)),this.localAngleB=0,this.localAngleB="number"==typeof c.localAngleB?c.localAngleB:b.angle-a.angle,this.equations.push(h,i,j),this.setMaxForce(g)}var d=a("./Constraint"),e=a("../math/vec2"),f=a("../equations/Equation");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.setMaxForce=function(a){for(var b=this.equations,c=0;c<this.equations.length;c++)b[c].maxForce=a,b[c].minForce=-a},c.prototype.getMaxForce=function(){return this.equations[0].maxForce};var g=e.create(),h=e.create(),i=e.create(),j=e.fromValues(1,0),k=e.fromValues(0,1);c.prototype.update=function(){var a=this.equations[0],b=this.equations[1],c=this.equations[2],d=this.bodyA,f=this.bodyB;e.rotate(g,this.localOffsetB,d.angle),e.rotate(h,this.localOffsetB,f.angle-this.localAngleB),e.scale(h,h,-1),e.rotate(i,h,Math.PI/2),e.normalize(i,i),a.G[0]=-1,a.G[1]=0,a.G[2]=-e.crossLength(g,j),a.G[3]=1,b.G[0]=0,b.G[1]=-1,b.G[2]=-e.crossLength(g,k),b.G[4]=1,c.G[0]=-i[0],c.G[1]=-i[1],c.G[3]=i[0],c.G[4]=i[1],c.G[5]=e.crossLength(h,i)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.PRISMATIC,c);var i=g.fromValues(0,0),j=g.fromValues(1,0),k=g.fromValues(0,0);c.localAnchorA&&g.copy(i,c.localAnchorA),c.localAxisA&&g.copy(j,c.localAxisA),c.localAnchorB&&g.copy(k,c.localAnchorB),this.localAnchorA=i,this.localAnchorB=k,this.localAxisA=j;var l=this.maxForce="undefined"!=typeof c.maxForce?c.maxForce:Number.MAX_VALUE,m=new f(a,b,-l,l),n=new g.create,o=new g.create,p=new g.create,q=new g.create;if(m.computeGq=function(){return g.dot(p,q)},m.updateJacobian=function(){var c=this.G,d=a.position,e=b.position;g.rotate(n,i,a.angle),g.rotate(o,k,b.angle),g.add(p,e,o),g.sub(p,p,d),g.sub(p,p,n),g.rotate(q,j,a.angle+Math.PI/2),c[0]=-q[0],c[1]=-q[1],c[2]=-g.crossLength(n,q)+g.crossLength(q,p),c[3]=q[0],c[4]=q[1],c[5]=g.crossLength(o,q)},this.equations.push(m),!c.disableRotationalLock){var r=new h(a,b,-l,l);this.equations.push(r)}this.position=0,this.velocity=0,this.lowerLimitEnabled="undefined"!=typeof c.lowerLimit?!0:!1,this.upperLimitEnabled="undefined"!=typeof c.upperLimit?!0:!1,this.lowerLimit="undefined"!=typeof c.lowerLimit?c.lowerLimit:0,this.upperLimit="undefined"!=typeof c.upperLimit?c.upperLimit:1,this.upperLimitEquation=new e(a,b),this.lowerLimitEquation=new e(a,b),this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0,this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=l,this.motorEquation=new f(a,b),this.motorEnabled=!1,this.motorSpeed=0;{var s=this,t=this.motorEquation;t.computeGW}t.computeGq=function(){return 0},t.computeGW=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=b.velocity,e=c.velocity,f=b.angularVelocity,g=c.angularVelocity;return this.gmult(a,d,f,e,g)+s.motorSpeed}}var d=a("./Constraint"),e=a("../equations/ContactEquation"),f=a("../equations/Equation"),g=a("../math/vec2"),h=a("../equations/RotationalLockEquation");b.exports=c,c.prototype=new d,c.prototype.constructor=c;var i=g.create(),j=g.create(),k=g.create(),l=g.create(),m=g.create(),n=g.create();c.prototype.update=function(){var a=this.equations,b=a[0],c=this.upperLimit,d=this.lowerLimit,e=this.upperLimitEquation,f=this.lowerLimitEquation,h=this.bodyA,o=this.bodyB,p=this.localAxisA,q=this.localAnchorA,r=this.localAnchorB;b.updateJacobian(),g.rotate(i,p,h.angle),g.rotate(l,q,h.angle),g.add(j,l,h.position),g.rotate(m,r,o.angle),g.add(k,m,o.position);var s=this.position=g.dot(k,i)-g.dot(j,i);if(this.motorEnabled){var t=this.motorEquation.G;t[0]=i[0],t[1]=i[1],t[2]=g.crossLength(i,m),t[3]=-i[0],t[4]=-i[1],t[5]=-g.crossLength(i,l)}if(this.upperLimitEnabled&&s>c)g.scale(e.normalA,i,-1),g.sub(e.contactPointA,j,h.position),g.sub(e.contactPointB,k,o.position),g.scale(n,i,c),g.add(e.contactPointA,e.contactPointA,n),-1===a.indexOf(e)&&a.push(e);else{var u=a.indexOf(e);-1!==u&&a.splice(u,1)}if(this.lowerLimitEnabled&&d>s)g.scale(f.normalA,i,1),g.sub(f.contactPointA,j,h.position),g.sub(f.contactPointB,k,o.position),g.scale(n,i,d),g.sub(f.contactPointB,f.contactPointB,n),-1===a.indexOf(f)&&a.push(f);else{var u=a.indexOf(f);-1!==u&&a.splice(u,1)}},c.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},c.prototype.disableMotor=function(){if(this.motorEnabled){var a=this.equations.indexOf(this.motorEquation);this.equations.splice(a,1),this.motorEnabled=!1}},c.prototype.setLimits=function(a,b){"number"==typeof a?(this.lowerLimit=a,this.lowerLimitEnabled=!0):(this.lowerLimit=a,this.lowerLimitEnabled=!1),"number"==typeof b?(this.upperLimit=b,this.upperLimitEnabled=!0):(this.upperLimit=b,this.upperLimitEnabled=!1)}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.REVOLUTE,c);var n=this.maxForce="undefined"!=typeof c.maxForce?c.maxForce:Number.MAX_VALUE;this.pivotA=h.create(),this.pivotB=h.create(),c.worldPivot?(h.sub(this.pivotA,c.worldPivot,a.position),h.sub(this.pivotB,c.worldPivot,b.position),h.rotate(this.pivotA,this.pivotA,-a.angle),h.rotate(this.pivotB,this.pivotB,-b.angle)):(h.copy(this.pivotA,c.localPivotA),h.copy(this.pivotB,c.localPivotB));var o=this.equations=[new e(a,b,-n,n),new e(a,b,-n,n)],p=o[0],q=o[1],r=this;p.computeGq=function(){return h.rotate(i,r.pivotA,a.angle),h.rotate(j,r.pivotB,b.angle),h.add(m,b.position,j),h.sub(m,m,a.position),h.sub(m,m,i),h.dot(m,k)},q.computeGq=function(){return h.rotate(i,r.pivotA,a.angle),h.rotate(j,r.pivotB,b.angle),h.add(m,b.position,j),h.sub(m,m,a.position),h.sub(m,m,i),h.dot(m,l)},q.minForce=p.minForce=-n,q.maxForce=p.maxForce=n,this.motorEquation=new f(a,b),this.motorEnabled=!1,this.angle=0,this.lowerLimitEnabled=!1,this.upperLimitEnabled=!1,this.lowerLimit=0,this.upperLimit=0,this.upperLimitEquation=new g(a,b),this.lowerLimitEquation=new g(a,b),this.upperLimitEquation.minForce=0,this.lowerLimitEquation.maxForce=0}var d=a("./Constraint"),e=a("../equations/Equation"),f=a("../equations/RotationalVelocityEquation"),g=a("../equations/RotationalLockEquation"),h=a("../math/vec2");b.exports=c;var i=h.create(),j=h.create(),k=h.fromValues(1,0),l=h.fromValues(0,1),m=h.create();c.prototype=new d,c.prototype.constructor=c,c.prototype.setLimits=function(a,b){"number"==typeof a?(this.lowerLimit=a,this.lowerLimitEnabled=!0):(this.lowerLimit=a,this.lowerLimitEnabled=!1),"number"==typeof b?(this.upperLimit=b,this.upperLimitEnabled=!0):(this.upperLimit=b,this.upperLimitEnabled=!1)},c.prototype.update=function(){var a=this.bodyA,b=this.bodyB,c=this.pivotA,d=this.pivotB,e=this.equations,f=(e[0],e[1],e[0]),g=e[1],m=this.upperLimit,n=this.lowerLimit,o=this.upperLimitEquation,p=this.lowerLimitEquation,q=this.angle=b.angle-a.angle;if(this.upperLimitEnabled&&q>m)o.angle=m,-1===e.indexOf(o)&&e.push(o);else{var r=e.indexOf(o);-1!==r&&e.splice(r,1)}if(this.lowerLimitEnabled&&n>q)p.angle=n,-1===e.indexOf(p)&&e.push(p);else{var r=e.indexOf(p);-1!==r&&e.splice(r,1)}h.rotate(i,c,a.angle),h.rotate(j,d,b.angle),f.G[0]=-1,f.G[1]=0,f.G[2]=-h.crossLength(i,k),f.G[3]=1,f.G[4]=0,f.G[5]=h.crossLength(j,k),g.G[0]=0,g.G[1]=-1,g.G[2]=-h.crossLength(i,l),g.G[3]=0,g.G[4]=1,g.G[5]=h.crossLength(j,l)},c.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},c.prototype.disableMotor=function(){if(this.motorEnabled){var a=this.equations.indexOf(this.motorEquation);this.equations.splice(a,1),this.motorEnabled=!1}},c.prototype.motorIsEnabled=function(){return!!this.motorEnabled},c.prototype.setMotorSpeed=function(a){if(this.motorEnabled){var b=this.equations.indexOf(this.motorEquation);this.equations[b].relativeVelocity=a}},c.prototype.getMotorSpeed=function(){return this.motorEnabled?this.motorEquation.relativeVelocity:!1}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=c.angle||0,this.ratio="number"==typeof c.ratio?c.ratio:1,this.setRatio(this.ratio)}{var d=a("./Equation");a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle},c.prototype.setRatio=function(a){var b=this.G;b[2]=a,b[5]=-1,this.ratio=a},c.prototype.setMaxTorque=function(a){this.maxForce=a,this.minForce=-a}},{"../math/vec2":30,"./Equation":22}],21:[function(a,b){function c(a,b){d.call(this,a,b,0,Number.MAX_VALUE),this.contactPointA=e.create(),this.penetrationVec=e.create(),this.contactPointB=e.create(),this.normalA=e.create(),this.restitution=0,this.firstImpact=!1,this.shapeA=null,this.shapeB=null}var d=a("./Equation"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeB=function(a,b,c){var d=this.bodyA,f=this.bodyB,g=this.contactPointA,h=this.contactPointB,i=d.position,j=f.position,k=this.penetrationVec,l=this.normalA,m=this.G,n=e.crossLength(g,l),o=e.crossLength(h,l);m[0]=-l[0],m[1]=-l[1],m[2]=-n,m[3]=l[0],m[4]=l[1],m[5]=o,e.add(k,j,h),e.sub(k,k,i),e.sub(k,k,g);var p,q;this.firstImpact&&0!==this.restitution?(q=0,p=1/b*(1+this.restitution)*this.computeGW()):(q=e.dot(l,k)+this.offset,p=this.computeGW());var r=this.computeGiMf(),s=-q*a-p*b-c*r;return s}},{"../math/vec2":30,"./Equation":22}],22:[function(a,b){function c(a,b,d,f){this.minForce="undefined"==typeof d?-Number.MAX_VALUE:d,this.maxForce="undefined"==typeof f?Number.MAX_VALUE:f,this.bodyA=a,this.bodyB=b,this.stiffness=c.DEFAULT_STIFFNESS,this.relaxation=c.DEFAULT_RELAXATION,this.G=new e.ARRAY_TYPE(6);for(var g=0;6>g;g++)this.G[g]=0;this.offset=0,this.a=0,this.b=0,this.epsilon=0,this.timeStep=1/60,this.needsUpdate=!0,this.multiplier=0,this.relativeVelocity=0,this.enabled=!0}b.exports=c;{var d=a("../math/vec2"),e=a("../utils/Utils");a("../objects/Body")}c.prototype.constructor=c,c.DEFAULT_STIFFNESS=1e6,c.DEFAULT_RELAXATION=4,c.prototype.update=function(){var a=this.stiffness,b=this.relaxation,c=this.timeStep;this.a=4/(c*(1+4*b)),this.b=4*b/(1+4*b),this.epsilon=4/(c*c*a*(1+4*b)),this.needsUpdate=!1},c.prototype.gmult=function(a,b,c,d,e){return a[0]*b[0]+a[1]*b[1]+a[2]*c+a[3]*d[0]+a[4]*d[1]+a[5]*e},c.prototype.computeB=function(a,b,c){var d=this.computeGW(),e=this.computeGq(),f=this.computeGiMf();return-e*a-d*b-f*c};var f=d.create(),g=d.create();c.prototype.computeGq=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=(b.position,c.position,b.angle),e=c.angle;return this.gmult(a,f,d,g,e)+this.offset},c.prototype.computeGW=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=b.velocity,e=c.velocity,f=b.angularVelocity,g=c.angularVelocity;return this.gmult(a,d,f,e,g)+this.relativeVelocity},c.prototype.computeGWlambda=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=b.vlambda,e=c.vlambda,f=b.wlambda,g=c.wlambda;return this.gmult(a,d,f,e,g)};var h=d.create(),i=d.create();c.prototype.computeGiMf=function(){var a=this.bodyA,b=this.bodyB,c=a.force,e=a.angularForce,f=b.force,g=b.angularForce,j=a.invMassSolve,k=b.invMassSolve,l=a.invInertiaSolve,m=b.invInertiaSolve,n=this.G;return d.scale(h,c,j),d.multiply(h,a.massMultiplier,h),d.scale(i,f,k),d.multiply(i,b.massMultiplier,i),this.gmult(n,h,e*l,i,g*m)},c.prototype.computeGiMGt=function(){var a=this.bodyA,b=this.bodyB,c=a.invMassSolve,d=b.invMassSolve,e=a.invInertiaSolve,f=b.invInertiaSolve,g=this.G;return g[0]*g[0]*c*a.massMultiplier[0]+g[1]*g[1]*c*a.massMultiplier[1]+g[2]*g[2]*e+g[3]*g[3]*d*b.massMultiplier[0]+g[4]*g[4]*d*b.massMultiplier[1]+g[5]*g[5]*f};{var j=d.create(),k=d.create(),l=d.create();d.create(),d.create(),d.create()}c.prototype.addToWlambda=function(a){var b=this.bodyA,c=this.bodyB,e=j,f=k,g=l,h=b.invMassSolve,i=c.invMassSolve,m=b.invInertiaSolve,n=c.invInertiaSolve,o=this.G;f[0]=o[0],f[1]=o[1],g[0]=o[3],g[1]=o[4],d.scale(e,f,h*a),d.multiply(e,e,b.massMultiplier),d.add(b.vlambda,b.vlambda,e),b.wlambda+=m*o[2]*a,d.scale(e,g,i*a),d.multiply(e,e,c.massMultiplier),d.add(c.vlambda,c.vlambda,e),c.wlambda+=n*o[5]*a},c.prototype.computeInvC=function(a){return 1/(this.computeGiMGt()+a)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(a,b){function c(a,b,c){e.call(this,a,b,-c,c),this.contactPointA=d.create(),this.contactPointB=d.create(),this.t=d.create(),this.contactEquations=[],this.shapeA=null,this.shapeB=null,this.frictionCoefficient=.3}{var d=a("../math/vec2"),e=a("./Equation");a("../utils/Utils")}b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.setSlipForce=function(a){this.maxForce=a,this.minForce=-a},c.prototype.getSlipForce=function(){return this.maxForce},c.prototype.computeB=function(a,b,c){var e=(this.bodyA,this.bodyB,this.contactPointA),f=this.contactPointB,g=this.t,h=this.G;h[0]=-g[0],h[1]=-g[1],h[2]=-d.crossLength(e,g),h[3]=g[0],h[4]=g[1],h[5]=d.crossLength(f,g);var i=this.computeGW(),j=this.computeGiMf(),k=-i*b-c*j;return k}},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=c.angle||0;var e=this.G;e[2]=1,e[5]=-1}var d=a("./Equation"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c;var f=e.create(),g=e.create(),h=e.fromValues(1,0),i=e.fromValues(0,1);c.prototype.computeGq=function(){return e.rotate(f,h,this.bodyA.angle+this.angle),e.rotate(g,i,this.bodyB.angle),e.dot(f,g)}},{"../math/vec2":30,"./Equation":22}],25:[function(a,b){function c(a,b){d.call(this,a,b,-Number.MAX_VALUE,Number.MAX_VALUE),this.relativeVelocity=1,this.ratio=1}{var d=a("./Equation");a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeB=function(a,b,c){var d=this.G;d[2]=-1,d[5]=this.ratio;var e=this.computeGiMf(),f=this.computeGW(),g=-f*b-c*e;return g}},{"../math/vec2":30,"./Equation":22}],26:[function(a,b){var c=function(){};b.exports=c,c.prototype={constructor:c,on:function(a,b,c){b.context=c||this,void 0===this._listeners&&(this._listeners={});var d=this._listeners;return void 0===d[a]&&(d[a]=[]),-1===d[a].indexOf(b)&&d[a].push(b),this},has:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;if(b){if(void 0!==c[a]&&-1!==c[a].indexOf(b))return!0}else if(void 0!==c[a])return!0;return!1},off:function(a,b){if(void 0===this._listeners)return this;var c=this._listeners,d=c[a].indexOf(b);return-1!==d&&c[a].splice(d,1),this},emit:function(a){if(void 0===this._listeners)return this;var b=this._listeners,c=b[a.type];if(void 0!==c){a.target=this;for(var d=0,e=c.length;e>d;d++){var f=c[d];f.call(f.context,a)}}return this}}},{}],27:[function(a,b){function c(a,b,f){if(f=f||{},!(a instanceof d&&b instanceof d))throw new Error("First two arguments must be Material instances.");this.id=c.idCounter++,this.materialA=a,this.materialB=b,this.friction="undefined"!=typeof f.friction?Number(f.friction):.3,this.restitution="undefined"!=typeof f.restitution?Number(f.restitution):0,this.stiffness="undefined"!=typeof f.stiffness?Number(f.stiffness):e.DEFAULT_STIFFNESS,this.relaxation="undefined"!=typeof f.relaxation?Number(f.relaxation):e.DEFAULT_RELAXATION,this.frictionStiffness="undefined"!=typeof f.frictionStiffness?Number(f.frictionStiffness):e.DEFAULT_STIFFNESS,this.frictionRelaxation="undefined"!=typeof f.frictionRelaxation?Number(f.frictionRelaxation):e.DEFAULT_RELAXATION,this.surfaceVelocity="undefined"!=typeof f.surfaceVelocity?Number(f.surfaceVelocity):0,this.contactSkinSize=.005}var d=a("./Material"),e=a("../equations/Equation");b.exports=c,c.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(a,b){function c(a){this.id=a||c.idCounter++}b.exports=c,c.idCounter=0},{}],29:[function(a,b){var c={};c.GetArea=function(a){if(a.length<6)return 0;for(var b=a.length-2,c=0,d=0;b>d;d+=2)c+=(a[d+2]-a[d])*(a[d+1]+a[d+3]);return c+=(a[0]-a[b])*(a[b+1]+a[1]),.5*-c},c.Triangulate=function(a){var b=a.length>>1;if(3>b)return[];for(var d=[],e=[],f=0;b>f;f++)e.push(f);for(var f=0,g=b;g>3;){var h=e[(f+0)%g],i=e[(f+1)%g],j=e[(f+2)%g],k=a[2*h],l=a[2*h+1],m=a[2*i],n=a[2*i+1],o=a[2*j],p=a[2*j+1],q=!1;if(c._convex(k,l,m,n,o,p)){q=!0;for(var r=0;g>r;r++){var s=e[r];if(s!=h&&s!=i&&s!=j&&c._PointInTriangle(a[2*s],a[2*s+1],k,l,m,n,o,p)){q=!1;break}}}if(q)d.push(h,i,j),e.splice((f+1)%g,1),g--,f=0;else if(f++>3*g)break}return d.push(e[0],e[1],e[2]),d},c._PointInTriangle=function(a,b,c,d,e,f,g,h){var i=g-c,j=h-d,k=e-c,l=f-d,m=a-c,n=b-d,o=i*i+j*j,p=i*k+j*l,q=i*m+j*n,r=k*k+l*l,s=k*m+l*n,t=1/(o*r-p*p),u=(r*q-p*s)*t,v=(o*s-p*q)*t;return u>=0&&v>=0&&1>u+v},c._convex=function(a,b,c,d,e,f){return(b-d)*(e-c)+(c-a)*(f-d)>=0},b.exports=c},{}],30:[function(a,b){var c=b.exports={},d=a("../utils/Utils");c.crossLength=function(a,b){return a[0]*b[1]-a[1]*b[0]},c.crossVZ=function(a,b,d){return c.rotate(a,b,-Math.PI/2),c.scale(a,a,d),a},c.crossZV=function(a,b,d){return c.rotate(a,d,Math.PI/2),c.scale(a,a,b),a},c.rotate=function(a,b,c){if(0!==c){var d=Math.cos(c),e=Math.sin(c),f=b[0],g=b[1];a[0]=d*f-e*g,a[1]=e*f+d*g}else a[0]=b[0],a[1]=b[1]},c.rotate90cw=function(a,b){var c=b[0],d=b[1];a[0]=d,a[1]=-c},c.toLocalFrame=function(a,b,d,e){c.copy(a,b),c.sub(a,a,d),c.rotate(a,a,-e)},c.toGlobalFrame=function(a,b,d,e){c.copy(a,b),c.rotate(a,a,e),c.add(a,a,d)},c.vectorToLocalFrame=function(a,b,d){c.rotate(a,b,-d)},c.vectorToGlobalFrame=function(a,b,d){c.rotate(a,b,d)},c.centroid=function(a,b,d,e){return c.add(a,b,d),c.add(a,a,e),c.scale(a,a,1/3),a},c.create=function(){var a=new d.ARRAY_TYPE(2);return a[0]=0,a[1]=0,a},c.clone=function(a){var b=new d.ARRAY_TYPE(2);return b[0]=a[0],b[1]=a[1],b},c.fromValues=function(a,b){var c=new d.ARRAY_TYPE(2);return c[0]=a,c[1]=b,c},c.copy=function(a,b){return a[0]=b[0],a[1]=b[1],a},c.set=function(a,b,c){return a[0]=b,a[1]=c,a},c.add=function(a,b,c){return a[0]=b[0]+c[0],a[1]=b[1]+c[1],a},c.subtract=function(a,b,c){return a[0]=b[0]-c[0],a[1]=b[1]-c[1],a},c.sub=c.subtract,c.multiply=function(a,b,c){return a[0]=b[0]*c[0],a[1]=b[1]*c[1],a},c.mul=c.multiply,c.divide=function(a,b,c){return a[0]=b[0]/c[0],a[1]=b[1]/c[1],a},c.div=c.divide,c.scale=function(a,b,c){return a[0]=b[0]*c,a[1]=b[1]*c,a},c.distance=function(a,b){var c=b[0]-a[0],d=b[1]-a[1];return Math.sqrt(c*c+d*d)},c.dist=c.distance,c.squaredDistance=function(a,b){var c=b[0]-a[0],d=b[1]-a[1];return c*c+d*d},c.sqrDist=c.squaredDistance,c.length=function(a){var b=a[0],c=a[1];return Math.sqrt(b*b+c*c)},c.len=c.length,c.squaredLength=function(a){var b=a[0],c=a[1];return b*b+c*c},c.sqrLen=c.squaredLength,c.negate=function(a,b){return a[0]=-b[0],a[1]=-b[1],a},c.normalize=function(a,b){var c=b[0],d=b[1],e=c*c+d*d;return e>0&&(e=1/Math.sqrt(e),a[0]=b[0]*e,a[1]=b[1]*e),a},c.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]},c.str=function(a){return"vec2("+a[0]+", "+a[1]+")"},c.lerp=function(a,b,c,d){var e=b[0],f=b[1];return a[0]=e+d*(c[0]-e),a[1]=f+d*(c[1]-f),a},c.reflect=function(a,b,c){var d=b[0]*c[0]+b[1]*c[1];a[0]=b[0]-2*c[0]*d,a[1]=b[1]-2*c[1]*d},c.getLineSegmentsIntersection=function(a,b,d,e,f){var g=c.getLineSegmentsIntersectionFraction(b,d,e,f);return 0>g?!1:(a[0]=b[0]+g*(d[0]-b[0]),a[1]=b[1]+g*(d[1]-b[1]),!0)},c.getLineSegmentsIntersectionFraction=function(a,b,c,d){var e,f,g=b[0]-a[0],h=b[1]-a[1],i=d[0]-c[0],j=d[1]-c[1];return e=(-h*(a[0]-c[0])+g*(a[1]-c[1]))/(-i*h+g*j),f=(i*(a[1]-c[1])-j*(a[0]-c[0]))/(-i*h+g*j),e>=0&&1>=e&&f>=0&&1>=f?f:-1}},{"../utils/Utils":57}],31:[function(a,b){function c(a){a=a||{},j.call(this),this.id=a.id||++c._idCounter,this.world=null,this.shapes=[],this.mass=a.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!a.fixedRotation,this.fixedX=!!a.fixedX,this.fixedY=!!a.fixedY,this.massMultiplier=d.create(),this.position=d.fromValues(0,0),a.position&&d.copy(this.position,a.position),this.interpolatedPosition=d.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=d.fromValues(0,0),this.previousAngle=0,this.velocity=d.fromValues(0,0),a.velocity&&d.copy(this.velocity,a.velocity),this.vlambda=d.fromValues(0,0),this.wlambda=0,this.angle=a.angle||0,this.angularVelocity=a.angularVelocity||0,this.force=d.create(),a.force&&d.copy(this.force,a.force),this.angularForce=a.angularForce||0,this.damping="number"==typeof a.damping?a.damping:.1,this.angularDamping="number"==typeof a.angularDamping?a.angularDamping:.1,this.type=c.STATIC,this.type="undefined"!=typeof a.type?a.type:a.mass?c.DYNAMIC:c.STATIC,this.boundingRadius=0,this.aabb=new i,this.aabbNeedsUpdate=!0,this.allowSleep=void 0!==a.allowSleep?a.allowSleep:!0,this.wantsToSleep=!1,this.sleepState=c.AWAKE,this.sleepSpeedLimit=void 0!==a.sleepSpeedLimit?a.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==a.sleepTimeLimit?a.sleepTimeLimit:1,this.gravityScale=void 0!==a.gravityScale?a.gravityScale:1,this.collisionResponse=void 0!==a.collisionResponse?a.collisionResponse:!0,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==a.ccdSpeedThreshold?a.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==a.ccdIterations?a.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()
-}var d=a("../math/vec2"),e=a("poly-decomp"),f=a("../shapes/Convex"),g=a("../collision/RaycastResult"),h=a("../collision/Ray"),i=a("../collision/AABB"),j=a("../events/EventEmitter");b.exports=c,c.prototype=new j,c.prototype.constructor=c,c._idCounter=0,c.prototype.updateSolveMassProperties=function(){this.sleepState===c.SLEEPING||this.type===c.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},c.prototype.setDensity=function(a){var b=this.getArea();this.mass=b*a,this.updateMassProperties()},c.prototype.getArea=function(){for(var a=0,b=0;b<this.shapes.length;b++)a+=this.shapes[b].area;return a},c.prototype.getAABB=function(){return this.aabbNeedsUpdate&&this.updateAABB(),this.aabb};var k=new i,l=d.create();c.prototype.updateAABB=function(){for(var a=this.shapes,b=a.length,c=l,e=this.angle,f=0;f!==b;f++){var g=a[f],h=g.angle+e;d.rotate(c,g.position,e),d.add(c,c,this.position),g.computeAABB(k,c,h),0===f?this.aabb.copy(k):this.aabb.extend(k)}this.aabbNeedsUpdate=!1},c.prototype.updateBoundingRadius=function(){for(var a=this.shapes,b=a.length,c=0,e=0;e!==b;e++){var f=a[e],g=d.length(f.position),h=f.boundingRadius;g+h>c&&(c=g+h)}this.boundingRadius=c},c.prototype.addShape=function(a,b,c){if(a.body)throw new Error("A shape can only be added to one body.");a.body=this,b?d.copy(a.position,b):d.set(a.position,0,0),a.angle=c||0,this.shapes.push(a),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},c.prototype.removeShape=function(a){var b=this.shapes.indexOf(a);return-1!==b?(this.shapes.splice(b,1),this.aabbNeedsUpdate=!0,a.body=null,!0):!1},c.prototype.updateMassProperties=function(){if(this.type===c.STATIC||this.type===c.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var a=this.shapes,b=a.length,e=this.mass/b,f=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var g=0;b>g;g++){var h=a[g],i=d.squaredLength(h.position),j=h.computeMomentOfInertia(e);f+=j+e*i}this.inertia=f,this.invInertia=f>0?1/f:0}this.invMass=1/this.mass,d.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};d.create();c.prototype.applyForce=function(a,b){if(d.add(this.force,this.force,a),b){var c=d.crossLength(b,a);this.angularForce+=c}};var m=d.create(),n=d.create(),o=d.create();c.prototype.applyForceLocal=function(a,b){b=b||o;var c=m,d=n;this.vectorToWorldFrame(c,a),this.vectorToWorldFrame(d,b),this.applyForce(c,d)};var p=d.create();c.prototype.applyImpulse=function(a,b){if(this.type===c.DYNAMIC){var e=p;if(d.scale(e,a,this.invMass),d.multiply(e,this.massMultiplier,e),d.add(this.velocity,e,this.velocity),b){var f=d.crossLength(b,a);f*=this.invInertia,this.angularVelocity+=f}}};var q=d.create(),r=d.create(),s=d.create();c.prototype.applyImpulseLocal=function(a,b){b=b||s;var c=q,d=r;this.vectorToWorldFrame(c,a),this.vectorToWorldFrame(d,b),this.applyImpulse(c,d)},c.prototype.toLocalFrame=function(a,b){d.toLocalFrame(a,b,this.position,this.angle)},c.prototype.toWorldFrame=function(a,b){d.toGlobalFrame(a,b,this.position,this.angle)},c.prototype.vectorToLocalFrame=function(a,b){d.vectorToLocalFrame(a,b,this.angle)},c.prototype.vectorToWorldFrame=function(a,b){d.vectorToGlobalFrame(a,b,this.angle)},c.prototype.fromPolygon=function(a,b){b=b||{};for(var c=this.shapes.length;c>=0;--c)this.removeShape(this.shapes[c]);var g=new e.Polygon;if(g.vertices=a,g.makeCCW(),"number"==typeof b.removeCollinearPoints&&g.removeCollinearPoints(b.removeCollinearPoints),"undefined"==typeof b.skipSimpleCheck&&!g.isSimple())return!1;this.concavePath=g.vertices.slice(0);for(var c=0;c<this.concavePath.length;c++){var h=[0,0];d.copy(h,this.concavePath[c]),this.concavePath[c]=h}var i;i=b.optimalDecomp?g.decomp():g.quickDecomp();for(var j=d.create(),c=0;c!==i.length;c++){for(var k=new f({vertices:i[c].vertices}),l=0;l!==k.vertices.length;l++){var h=k.vertices[l];d.sub(h,h,k.centerOfMass)}d.scale(j,k.centerOfMass,1),k.updateTriangles(),k.updateCenterOfMass(),k.updateBoundingRadius(),this.addShape(k,j)}return this.adjustCenterOfMass(),this.aabbNeedsUpdate=!0,!0};var t=(d.fromValues(0,0),d.fromValues(0,0)),u=d.fromValues(0,0),v=d.fromValues(0,0);c.prototype.adjustCenterOfMass=function(){var a=t,b=u,c=v,e=0;d.set(b,0,0);for(var f=0;f!==this.shapes.length;f++){var g=this.shapes[f];d.scale(a,g.position,g.area),d.add(b,b,a),e+=g.area}d.scale(c,b,1/e);for(var f=0;f!==this.shapes.length;f++){var g=this.shapes[f];d.sub(g.position,g.position,c)}d.add(this.position,this.position,c);for(var f=0;this.concavePath&&f<this.concavePath.length;f++)d.sub(this.concavePath[f],this.concavePath[f],c);this.updateMassProperties(),this.updateBoundingRadius()},c.prototype.setZeroForce=function(){d.set(this.force,0,0),this.angularForce=0},c.prototype.resetConstraintVelocity=function(){var a=this,b=a.vlambda;d.set(b,0,0),a.wlambda=0},c.prototype.addConstraintVelocity=function(){var a=this,b=a.velocity;d.add(b,b,a.vlambda),a.angularVelocity+=a.wlambda},c.prototype.applyDamping=function(a){if(this.type===c.DYNAMIC){var b=this.velocity;d.scale(b,b,Math.pow(1-this.damping,a)),this.angularVelocity*=Math.pow(1-this.angularDamping,a)}},c.prototype.wakeUp=function(){var a=this.sleepState;this.sleepState=c.AWAKE,this.idleTime=0,a!==c.AWAKE&&this.emit(c.wakeUpEvent)},c.prototype.sleep=function(){this.sleepState=c.SLEEPING,this.angularVelocity=0,this.angularForce=0,d.set(this.velocity,0,0),d.set(this.force,0,0),this.emit(c.sleepEvent)},c.prototype.sleepTick=function(a,b,e){if(this.allowSleep&&this.type!==c.SLEEPING){this.wantsToSleep=!1;var f=(this.sleepState,d.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2)),g=Math.pow(this.sleepSpeedLimit,2);f>=g?(this.idleTime=0,this.sleepState=c.AWAKE):(this.idleTime+=e,this.sleepState=c.SLEEPY),this.idleTime>this.sleepTimeLimit&&(b?this.wantsToSleep=!0:this.sleep())}},c.prototype.overlaps=function(a){return this.world.overlapKeeper.bodiesAreOverlapping(this,a)};var w=d.create(),x=d.create();c.prototype.integrate=function(a){var b=this.invMass,c=this.force,e=this.position,f=this.velocity;d.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*a),d.scale(w,c,a*b),d.multiply(w,this.massMultiplier,w),d.add(f,w,f),this.integrateToTimeOfImpact(a)||(d.scale(x,f,a),d.add(e,e,x),this.fixedRotation||(this.angle+=this.angularVelocity*a)),this.aabbNeedsUpdate=!0};var y=new g,z=new h({mode:h.ALL}),A=d.create(),B=d.create(),C=d.create(),D=d.create();c.prototype.integrateToTimeOfImpact=function(a){if(this.ccdSpeedThreshold<0||d.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2))return!1;d.normalize(A,this.velocity),d.scale(B,this.velocity,a),d.add(B,B,this.position),d.sub(C,B,this.position);var b,c=this.angularVelocity*a,e=d.length(C),f=1,g=this;if(y.reset(),z.callback=function(a){a.body!==g&&(b=a.body,a.getHitPoint(B,z),d.sub(C,B,g.position),f=d.length(C)/e,a.stop())},d.copy(z.from,this.position),d.copy(z.to,B),z.update(),this.world.raycast(y,z),!b)return!1;var h=this.angle;d.copy(D,this.position);for(var i=0,j=0,k=0,l=f;l>=j&&i<this.ccdIterations;){i++,k=(l-j)/2,d.scale(x,C,f),d.add(this.position,D,x),this.angle=h+c*f,this.updateAABB();var m=this.aabb.overlaps(b.aabb)&&this.world.narrowphase.bodiesOverlap(this,b);m?j=k:l=k}return f=k,d.copy(this.position,D),this.angle=h,d.scale(x,C,f),d.add(this.position,this.position,x),this.fixedRotation||(this.angle+=c*f),!0},c.prototype.getVelocityAtPoint=function(a,b){return d.crossVZ(a,b,this.angularVelocity),d.subtract(a,this.velocity,a),a},c.sleepyEvent={type:"sleepy"},c.sleepEvent={type:"sleep"},c.wakeUpEvent={type:"wakeup"},c.DYNAMIC=1,c.STATIC=2,c.KINEMATIC=4,c.AWAKE=0,c.SLEEPY=1,c.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(a,b){function c(a,b,c){c=c||{},e.call(this,a,b,c),this.localAnchorA=d.fromValues(0,0),this.localAnchorB=d.fromValues(0,0),c.localAnchorA&&d.copy(this.localAnchorA,c.localAnchorA),c.localAnchorB&&d.copy(this.localAnchorB,c.localAnchorB),c.worldAnchorA&&this.setWorldAnchorA(c.worldAnchorA),c.worldAnchorB&&this.setWorldAnchorB(c.worldAnchorB);var f=d.create(),g=d.create();this.getWorldAnchorA(f),this.getWorldAnchorB(g);var h=d.distance(f,g);this.restLength="number"==typeof c.restLength?c.restLength:h}{var d=a("../math/vec2"),e=a("./Spring");a("../utils/Utils")}b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.setWorldAnchorA=function(a){this.bodyA.toLocalFrame(this.localAnchorA,a)},c.prototype.setWorldAnchorB=function(a){this.bodyB.toLocalFrame(this.localAnchorB,a)},c.prototype.getWorldAnchorA=function(a){this.bodyA.toWorldFrame(a,this.localAnchorA)},c.prototype.getWorldAnchorB=function(a){this.bodyB.toWorldFrame(a,this.localAnchorB)};var f=d.create(),g=d.create(),h=d.create(),i=d.create(),j=d.create(),k=d.create(),l=d.create(),m=d.create(),n=d.create();c.prototype.applyForce=function(){var a=this.stiffness,b=this.damping,c=this.restLength,e=this.bodyA,o=this.bodyB,p=f,q=g,r=h,s=i,t=n,u=j,v=k,w=l,x=m;this.getWorldAnchorA(u),this.getWorldAnchorB(v),d.sub(w,u,e.position),d.sub(x,v,o.position),d.sub(p,v,u);var y=d.len(p);d.normalize(q,p),d.sub(r,o.velocity,e.velocity),d.crossZV(t,o.angularVelocity,x),d.add(r,r,t),d.crossZV(t,e.angularVelocity,w),d.sub(r,r,t),d.scale(s,q,-a*(y-c)-b*d.dot(r,q)),d.sub(e.force,e.force,s),d.add(o.force,o.force,s);var z=d.crossLength(w,s),A=d.crossLength(x,s);e.angularForce-=z,o.angularForce+=A}},{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,c),this.restAngle="number"==typeof c.restAngle?c.restAngle:b.angle-a.angle}var d=(a("../math/vec2"),a("./Spring"));b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.applyForce=function(){var a=this.stiffness,b=this.damping,c=this.restAngle,d=this.bodyA,e=this.bodyB,f=e.angle-d.angle,g=e.angularVelocity-d.angularVelocity,h=-a*(f-c)-b*g*0;d.angularForce-=h,e.angularForce+=h}},{"../math/vec2":30,"./Spring":34}],34:[function(a,b){function c(a,b,c){c=d.defaults(c,{stiffness:100,damping:1}),this.stiffness=c.stiffness,this.damping=c.damping,this.bodyA=a,this.bodyB=b}var d=(a("../math/vec2"),a("../utils/Utils"));b.exports=c,c.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":57}],35:[function(a,b){function c(a,b){b=b||{},this.chassisBody=a,this.wheels=[],this.groundBody=new h({mass:0}),this.world=null;var c=this;this.preStepCallback=function(){c.update()}}function d(a,b){b=b||{},this.vehicle=a,this.forwardEquation=new g(a.chassisBody,a.groundBody),this.sideEquation=new g(a.chassisBody,a.groundBody),this.steerValue=0,this.engineForce=0,this.setSideFriction(void 0!==b.sideFriction?b.sideFriction:5),this.localForwardVector=e.fromValues(0,1),b.localForwardVector&&e.copy(this.localForwardVector,b.localForwardVector),this.localPosition=e.fromValues(0,0),b.localPosition&&e.copy(this.localPosition,b.localPosition),f.apply(this,a.chassisBody,a.groundBody),this.equations.push(this.forwardEquation,this.sideEquation),this.setBrakeForce(0)}var e=a("../math/vec2"),f=(a("../utils/Utils"),a("../constraints/Constraint")),g=a("../equations/FrictionEquation"),h=a("../objects/Body");b.exports=c,c.prototype.addToWorld=function(a){this.world=a,a.addBody(this.groundBody),a.on("preStep",this.preStepCallback);for(var b=0;b<this.wheels.length;b++){var c=this.wheels[b];a.addConstraint(c)}},c.prototype.removeFromWorld=function(){var a=this.world;a.removeBody(this.groundBody),a.off("preStep",this.preStepCallback);for(var b=0;b<this.wheels.length;b++){var c=this.wheels[b];a.removeConstraint(c)}this.world=null},c.prototype.addWheel=function(a){var b=new d(this,a);return this.wheels.push(b),b},c.prototype.update=function(){for(var a=0;a<this.wheels.length;a++)this.wheels[a].update()},d.prototype=new f,d.prototype.setBrakeForce=function(a){this.forwardEquation.setSlipForce(a)},d.prototype.setSideFriction=function(a){this.sideEquation.setSlipForce(a)};var i=e.create(),j=e.create();d.prototype.getSpeed=function(){return this.vehicle.chassisBody.vectorToWorldFrame(j,this.localForwardVector),this.vehicle.chassisBody.getVelocityAtPoint(i,j),e.dot(i,j)};var k=e.create();d.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector),e.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2),this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t),e.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue),e.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue),this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition),e.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB),this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition),e.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA),e.normalize(k,this.forwardEquation.t),e.scale(k,k,this.engineForce),this.vehicle.chassisBody.applyForce(k,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(a,b){var c=b.exports={AABB:a("./collision/AABB"),AngleLockEquation:a("./equations/AngleLockEquation"),Body:a("./objects/Body"),Broadphase:a("./collision/Broadphase"),Capsule:a("./shapes/Capsule"),Circle:a("./shapes/Circle"),Constraint:a("./constraints/Constraint"),ContactEquation:a("./equations/ContactEquation"),ContactEquationPool:a("./utils/ContactEquationPool"),ContactMaterial:a("./material/ContactMaterial"),Convex:a("./shapes/Convex"),DistanceConstraint:a("./constraints/DistanceConstraint"),Equation:a("./equations/Equation"),EventEmitter:a("./events/EventEmitter"),FrictionEquation:a("./equations/FrictionEquation"),FrictionEquationPool:a("./utils/FrictionEquationPool"),GearConstraint:a("./constraints/GearConstraint"),GSSolver:a("./solver/GSSolver"),Heightfield:a("./shapes/Heightfield"),Line:a("./shapes/Line"),LockConstraint:a("./constraints/LockConstraint"),Material:a("./material/Material"),Narrowphase:a("./collision/Narrowphase"),NaiveBroadphase:a("./collision/NaiveBroadphase"),Particle:a("./shapes/Particle"),Plane:a("./shapes/Plane"),Pool:a("./utils/Pool"),RevoluteConstraint:a("./constraints/RevoluteConstraint"),PrismaticConstraint:a("./constraints/PrismaticConstraint"),Ray:a("./collision/Ray"),RaycastResult:a("./collision/RaycastResult"),Box:a("./shapes/Box"),RotationalVelocityEquation:a("./equations/RotationalVelocityEquation"),SAPBroadphase:a("./collision/SAPBroadphase"),Shape:a("./shapes/Shape"),Solver:a("./solver/Solver"),Spring:a("./objects/Spring"),TopDownVehicle:a("./objects/TopDownVehicle"),LinearSpring:a("./objects/LinearSpring"),RotationalSpring:a("./objects/RotationalSpring"),Utils:a("./utils/Utils"),World:a("./world/World"),vec2:a("./math/vec2"),version:a("../package.json").version};Object.defineProperty(c,"Rectangle",{get:function(){return console.warn("The Rectangle class has been renamed to Box."),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":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(a,b){function c(a){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(a={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, ... })")),a=a||{};var b=this.width=a.width||1,c=this.height=a.height||1,g=[d.fromValues(-b/2,-c/2),d.fromValues(b/2,-c/2),d.fromValues(b/2,c/2),d.fromValues(-b/2,c/2)],h=[d.fromValues(1,0),d.fromValues(0,1)];a.vertices=g,a.axes=h,a.type=e.BOX,f.call(this,a)}var d=a("../math/vec2"),e=a("./Shape"),f=a("./Convex");b.exports=c,c.prototype=new f,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){var b=this.width,c=this.height;return a*(c*c+b*b)/12},c.prototype.updateBoundingRadius=function(){var a=this.width,b=this.height;this.boundingRadius=Math.sqrt(a*a+b*b)/2};d.create(),d.create(),d.create(),d.create();c.prototype.computeAABB=function(a,b,c){a.setFromPoints(this.vertices,b,c,0)},c.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(a,b){function c(a){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(a={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 })")),a=a||{},this.length=a.length||1,this.radius=a.radius||1,a.type=d.CAPSULE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){var b=this.radius,c=this.length+b,d=2*b;return a*(d*d+c*c)/12},c.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2},c.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+2*this.radius*this.length};var f=e.create();c.prototype.computeAABB=function(a,b,c){var d=this.radius;e.set(f,this.length/2,0),0!==c&&e.rotate(f,f,c),e.set(a.upperBound,Math.max(f[0]+d,-f[0]+d),Math.max(f[1]+d,-f[1]+d)),e.set(a.lowerBound,Math.min(f[0]-d,-f[0]-d),Math.min(f[1]-d,-f[1]-d)),e.add(a.lowerBound,a.lowerBound,b),e.add(a.upperBound,a.upperBound,b)};var g=e.create(),h=e.create(),i=e.create(),j=e.create(),k=e.fromValues(0,1);c.prototype.raycast=function(a,b,c,d){for(var f=b.from,l=b.to,m=(b.direction,g),n=h,o=i,p=j,q=this.length/2,r=0;2>r;r++){var s=this.radius*(2*r-1);e.set(o,-q,s),e.set(p,q,s),e.toGlobalFrame(o,o,c,d),e.toGlobalFrame(p,p,c,d);var t=e.getLineSegmentsIntersectionFraction(f,l,o,p);if(t>=0&&(e.rotate(n,k,d),e.scale(n,n,2*r-1),b.reportIntersection(a,t,n,-1),a.shouldStop(b)))return}for(var u=Math.pow(this.radius,2)+Math.pow(q,2),r=0;2>r;r++){e.set(o,q*(2*r-1),0),e.toGlobalFrame(o,o,c,d);var v=Math.pow(l[0]-f[0],2)+Math.pow(l[1]-f[1],2),w=2*((l[0]-f[0])*(f[0]-o[0])+(l[1]-f[1])*(f[1]-o[1])),x=Math.pow(f[0]-o[0],2)+Math.pow(f[1]-o[1],2)-Math.pow(this.radius,2),t=Math.pow(w,2)-4*v*x;if(!(0>t))if(0===t){if(e.lerp(m,f,l,t),e.squaredDistance(m,c)>u&&(e.sub(n,m,o),e.normalize(n,n),b.reportIntersection(a,t,n,-1),a.shouldStop(b)))return}else{var y=Math.sqrt(t),z=1/(2*v),A=(-w-y)*z,B=(-w+y)*z;if(A>=0&&1>=A&&(e.lerp(m,f,l,A),e.squaredDistance(m,c)>u&&(e.sub(n,m,o),e.normalize(n,n),b.reportIntersection(a,A,n,-1),a.shouldStop(b))))return;if(B>=0&&1>=B&&(e.lerp(m,f,l,B),e.squaredDistance(m,c)>u&&(e.sub(n,m,o),e.normalize(n,n),b.reportIntersection(a,B,n,-1),a.shouldStop(b))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(a,b){function c(a){"number"==typeof arguments[0]&&(a={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),a=a||{},this.radius=a.radius||1,a.type=d.CIRCLE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){var b=this.radius;return a*b*b/2},c.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},c.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},c.prototype.computeAABB=function(a,b){var c=this.radius;e.set(a.upperBound,c,c),e.set(a.lowerBound,-c,-c),b&&(e.add(a.lowerBound,a.lowerBound,b),e.add(a.upperBound,a.upperBound,b))};var f=e.create(),g=e.create();c.prototype.raycast=function(a,b,c){var d=b.from,h=b.to,i=this.radius,j=Math.pow(h[0]-d[0],2)+Math.pow(h[1]-d[1],2),k=2*((h[0]-d[0])*(d[0]-c[0])+(h[1]-d[1])*(d[1]-c[1])),l=Math.pow(d[0]-c[0],2)+Math.pow(d[1]-c[1],2)-Math.pow(i,2),m=Math.pow(k,2)-4*j*l,n=f,o=g;if(!(0>m))if(0===m)e.lerp(n,d,h,m),e.sub(o,n,c),e.normalize(o,o),b.reportIntersection(a,m,o,-1);else{var p=Math.sqrt(m),q=1/(2*j),r=(-k-p)*q,s=(-k+p)*q;if(r>=0&&1>=r&&(e.lerp(n,d,h,r),e.sub(o,n,c),e.normalize(o,o),b.reportIntersection(a,r,o,-1),a.shouldStop(b)))return;s>=0&&1>=s&&(e.lerp(n,d,h,s),e.sub(o,n,c),e.normalize(o,o),b.reportIntersection(a,s,o,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(a,b){function c(a){Array.isArray(arguments[0])&&(a={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),a=a||{},this.vertices=[];for(var b=void 0!==a.vertices?a.vertices:[],c=0;c<b.length;c++){var f=e.create();e.copy(f,b[c]),this.vertices.push(f)}if(this.axes=[],a.axes)for(var c=0;c<a.axes.length;c++){var g=e.create();e.copy(g,a.axes[c]),this.axes.push(g)}else for(var c=0;c<this.vertices.length;c++){var h=this.vertices[c],i=this.vertices[(c+1)%this.vertices.length],j=e.create();e.sub(j,i,h),e.rotate90cw(j,j),e.normalize(j,j),this.axes.push(j)}if(this.centerOfMass=e.fromValues(0,0),this.triangles=[],this.vertices.length&&(this.updateTriangles(),this.updateCenterOfMass()),this.boundingRadius=0,a.type=d.CONVEX,d.call(this,a),this.updateBoundingRadius(),this.updateArea(),this.area<0)throw new Error("Convex vertices must be given in conter-clockwise winding.")}{var d=a("./Shape"),e=a("../math/vec2"),f=a("../math/polyk");a("poly-decomp")}b.exports=c,c.prototype=new d,c.prototype.constructor=c;var g=e.create(),h=e.create();c.prototype.projectOntoLocalAxis=function(a,b){for(var c,d,f=null,h=null,a=g,i=0;i<this.vertices.length;i++)c=this.vertices[i],d=e.dot(c,a),(null===f||d>f)&&(f=d),(null===h||h>d)&&(h=d);if(h>f){var j=h;h=f,f=j}e.set(b,h,f)},c.prototype.projectOntoWorldAxis=function(a,b,c,d){var f=h;this.projectOntoLocalAxis(a,d),0!==c?e.rotate(f,a,c):f=a;var g=e.dot(b,f);e.set(d,d[0]+g,d[1]+g)},c.prototype.updateTriangles=function(){this.triangles.length=0;for(var a=[],b=0;b<this.vertices.length;b++){var c=this.vertices[b];a.push(c[0],c[1])}for(var d=f.Triangulate(a),b=0;b<d.length;b+=3){var e=d[b],g=d[b+1],h=d[b+2];this.triangles.push([e,g,h])}};{var i=e.create(),j=e.create(),k=e.create(),l=e.create(),m=e.create();e.create(),e.create(),e.create(),e.create()}c.prototype.updateCenterOfMass=function(){var a=this.triangles,b=this.vertices,d=this.centerOfMass,f=i,g=k,h=l,n=m,o=j;e.set(d,0,0);for(var p=0,q=0;q!==a.length;q++){var r=a[q],g=b[r[0]],h=b[r[1]],n=b[r[2]];e.centroid(f,g,h,n);var s=c.triangleArea(g,h,n);p+=s,e.scale(o,f,s),e.add(d,d,o)}e.scale(d,d,1/p)},c.prototype.computeMomentOfInertia=function(a){for(var b=0,c=0,d=this.vertices.length,f=d-1,g=0;d>g;f=g,g++){var h=this.vertices[f],i=this.vertices[g],j=Math.abs(e.crossLength(h,i)),k=e.dot(i,i)+e.dot(i,h)+e.dot(h,h);b+=j*k,c+=j}return a/6*(b/c)},c.prototype.updateBoundingRadius=function(){for(var a=this.vertices,b=0,c=0;c!==a.length;c++){var d=e.squaredLength(a[c]);d>b&&(b=d)}this.boundingRadius=Math.sqrt(b)},c.triangleArea=function(a,b,c){return.5*((b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]))},c.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var a=this.triangles,b=this.vertices,d=0;d!==a.length;d++){var e=a[d],f=b[e[0]],g=b[e[1]],h=b[e[2]],i=c.triangleArea(f,g,h);this.area+=i}},c.prototype.computeAABB=function(a,b,c){a.setFromPoints(this.vertices,b,c,0)};var n=e.create(),o=e.create(),p=e.create();c.prototype.raycast=function(a,b,c,d){var f=n,g=o,h=p,i=this.vertices;e.toLocalFrame(f,b.from,c,d),e.toLocalFrame(g,b.to,c,d);for(var j=i.length,k=0;j>k&&!a.shouldStop(b);k++){var l=i[k],m=i[(k+1)%j],q=e.getLineSegmentsIntersectionFraction(f,g,l,m);q>=0&&(e.sub(h,m,l),e.rotate(h,h,-Math.PI/2+d),e.normalize(h,h),b.reportIntersection(a,q,h,k))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(a,b){function c(a){if(Array.isArray(arguments[0])){if(a={heights:arguments[0]},"object"==typeof arguments[1])for(var b in arguments[1])a[b]=arguments[1][b];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}a=a||{},this.heights=a.heights?a.heights.slice(0):[],this.maxValue=a.maxValue||null,this.minValue=a.minValue||null,this.elementWidth=a.elementWidth||.1,(void 0===a.maxValue||void 0===a.minValue)&&this.updateMaxMinValues(),a.type=d.HEIGHTFIELD,d.call(this,a)}{var d=a("./Shape"),e=a("../math/vec2");a("../utils/Utils")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.updateMaxMinValues=function(){for(var a=this.heights,b=a[0],c=a[0],d=0;d!==a.length;d++){var e=a[d];e>b&&(b=e),c>e&&(c=e)}this.maxValue=b,this.minValue=c},c.prototype.computeMomentOfInertia=function(){return Number.MAX_VALUE},c.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},c.prototype.updateArea=function(){for(var a=this.heights,b=0,c=0;c<a.length-1;c++)b+=(a[c]+a[c+1])/2*this.elementWidth;this.area=b};var f=[e.create(),e.create(),e.create(),e.create()];c.prototype.computeAABB=function(a,b,c){e.set(f[0],0,this.maxValue),e.set(f[1],this.elementWidth*this.heights.length,this.maxValue),e.set(f[2],this.elementWidth*this.heights.length,this.minValue),e.set(f[3],0,this.minValue),a.setFromPoints(f,b,c)},c.prototype.getLineSegment=function(a,b,c){var d=this.heights,f=this.elementWidth;e.set(a,c*f,d[c]),e.set(b,(c+1)*f,d[c+1])},c.prototype.getSegmentIndex=function(a){return Math.floor(a[0]/this.elementWidth)},c.prototype.getClampedSegmentIndex=function(a){var b=this.getSegmentIndex(a);return b=Math.min(this.heights.length,Math.max(b,0))};{var g=(e.create(),e.create()),h=e.create(),i=e.create(),j=e.create(),k=e.create();e.fromValues(0,1)}c.prototype.raycast=function(a,b,c,d){var f=b.from,l=b.to,m=(b.direction,g),n=h,o=i,p=j,q=k;e.toLocalFrame(p,f,c,d),e.toLocalFrame(q,l,c,d);var r=this.getClampedSegmentIndex(p),s=this.getClampedSegmentIndex(q);if(r>s){var t=r;r=s,s=t}for(var u=0;u<this.heights.length-1;u++){this.getLineSegment(n,o,u);var v=e.getLineSegmentsIntersectionFraction(p,q,n,o);if(v>=0&&(e.sub(m,o,n),e.rotate(m,m,d+Math.PI/2),e.normalize(m,m),b.reportIntersection(a,v,m,-1),a.shouldStop(b)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(a,b){function c(a){"number"==typeof arguments[0]&&(a={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),a=a||{},this.length=a.length||1,a.type=d.LINE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){return a*Math.pow(this.length,2)/12},c.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var f=[e.create(),e.create()];c.prototype.computeAABB=function(a,b,c){var d=this.length/2;e.set(f[0],-d,0),e.set(f[1],d,0),a.setFromPoints(f,b,c,0)};var g=(e.create(),e.create()),h=e.create(),i=e.create(),j=e.fromValues(0,1);c.prototype.raycast=function(a,b,c,d){var f=b.from,k=b.to,l=h,m=i,n=this.length/2;e.set(l,-n,0),e.set(m,n,0),e.toGlobalFrame(l,l,c,d),e.toGlobalFrame(m,m,c,d);var o=e.getLineSegmentsIntersectionFraction(l,m,f,k);if(o>=0){var p=g;e.rotate(p,j,d),b.reportIntersection(a,o,p,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(a,b){function c(a){a=a||{},a.type=d.PARTICLE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(){return 0},c.prototype.updateBoundingRadius=function(){this.boundingRadius=0},c.prototype.computeAABB=function(a,b){e.copy(a.lowerBound,b),e.copy(a.upperBound,b)}},{"../math/vec2":30,"./Shape":45}],44:[function(a,b){function c(a){a=a||{},a.type=d.PLANE,d.call(this,a)}{var d=a("./Shape"),e=a("../math/vec2");a("../utils/Utils")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(){return 0},c.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},c.prototype.computeAABB=function(a,b,c){var d=c%(2*Math.PI),f=e.set,g=Number.MAX_VALUE,h=a.lowerBound,i=a.upperBound;0===d?(f(h,-g,-g),f(i,g,0)):d===Math.PI/2?(f(h,0,-g),f(i,g,g)):d===Math.PI?(f(h,-g,0),f(i,g,g)):d===3*Math.PI/2?(f(h,-g,-g),f(i,0,g)):(f(h,-g,-g),f(i,g,g)),e.add(h,h,b),e.add(i,i,b)},c.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var f=e.create(),g=(e.create(),e.create(),e.create()),h=e.create();c.prototype.raycast=function(a,b,c,d){var i=b.from,j=b.to,k=b.direction,l=f,m=g,n=h;e.set(m,0,1),e.rotate(m,m,d),e.sub(n,i,c);var o=e.dot(n,m);e.sub(n,j,c);var p=e.dot(n,m);if(!(o*p>0||e.squaredDistance(i,j)<o*o)){var q=e.dot(m,k);e.sub(l,i,c);var r=-e.dot(m,l)/q/b.length;b.reportIntersection(a,r,m,-1)}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(a,b){function c(a){a=a||{},this.body=null,this.position=d.fromValues(0,0),a.position&&d.copy(this.position,a.position),this.angle=a.angle||0,this.type=a.type||0,this.id=c.idCounter++,this.boundingRadius=0,this.collisionGroup=void 0!==a.collisionGroup?a.collisionGroup:1,this.collisionResponse=void 0!==a.collisionResponse?a.collisionResponse:!0,this.collisionMask=void 0!==a.collisionMask?a.collisionMask:1,this.material=a.material||null,this.area=0,this.sensor=void 0!==a.sensor?a.sensor:!1,this.type&&this.updateBoundingRadius(),this.updateArea()}b.exports=c;var d=a("../math/vec2");c.idCounter=0,c.CIRCLE=1,c.PARTICLE=2,c.PLANE=4,c.CONVEX=8,c.LINE=16,c.BOX=32,Object.defineProperty(c,"RECTANGLE",{get:function(){return console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead."),c.BOX}}),c.CAPSULE=64,c.HEIGHTFIELD=128,c.prototype.computeMomentOfInertia=function(){},c.prototype.updateBoundingRadius=function(){},c.prototype.updateArea=function(){},c.prototype.computeAABB=function(){},c.prototype.raycast=function(){}},{"../math/vec2":30}],46:[function(a,b){function c(a){f.call(this,a,f.GS),a=a||{},this.iterations=a.iterations||10,this.tolerance=a.tolerance||1e-7,this.arrayStep=30,this.lambda=new g.ARRAY_TYPE(this.arrayStep),this.Bs=new g.ARRAY_TYPE(this.arrayStep),this.invCs=new g.ARRAY_TYPE(this.arrayStep),this.useZeroRHS=!1,this.frictionIterations=0,this.usedIterations=0}function d(a){for(var b=a.length;b--;)a[b]=0}var e=a("../math/vec2"),f=a("./Solver"),g=a("../utils/Utils"),h=a("../equations/FrictionEquation");b.exports=c,c.prototype=new f,c.prototype.constructor=c,c.prototype.solve=function(a,b){this.sortEquations();var f=0,i=this.iterations,j=this.frictionIterations,k=this.equations,l=k.length,m=Math.pow(this.tolerance*l,2),n=b.bodies,o=b.bodies.length,p=(e.add,e.set,this.useZeroRHS),q=this.lambda;if(this.usedIterations=0,l)for(var r=0;r!==o;r++){var s=n[r];s.updateSolveMassProperties()}q.length<l&&(q=this.lambda=new g.ARRAY_TYPE(l+this.arrayStep),this.Bs=new g.ARRAY_TYPE(l+this.arrayStep),this.invCs=new g.ARRAY_TYPE(l+this.arrayStep)),d(q);
-for(var t=this.invCs,u=this.Bs,q=this.lambda,r=0;r!==k.length;r++){var v=k[r];(v.timeStep!==a||v.needsUpdate)&&(v.timeStep=a,v.update()),u[r]=v.computeB(v.a,v.b,a),t[r]=v.computeInvC(v.epsilon)}var v,w,r,x;if(0!==l){for(r=0;r!==o;r++){var s=n[r];s.resetConstraintVelocity()}if(j){for(f=0;f!==j;f++){for(w=0,x=0;x!==l;x++){v=k[x];var y=c.iterateEquation(x,v,v.epsilon,u,t,q,p,a,f);w+=Math.abs(y)}if(this.usedIterations++,m>=w*w)break}for(c.updateMultipliers(k,q,1/a),x=0;x!==l;x++){var z=k[x];if(z instanceof h){for(var A=0,B=0;B!==z.contactEquations.length;B++)A+=z.contactEquations[B].multiplier;A*=z.frictionCoefficient/z.contactEquations.length,z.maxForce=A,z.minForce=-A}}}for(f=0;f!==i;f++){for(w=0,x=0;x!==l;x++){v=k[x];var y=c.iterateEquation(x,v,v.epsilon,u,t,q,p,a,f);w+=Math.abs(y)}if(this.usedIterations++,m>=w*w)break}for(r=0;r!==o;r++)n[r].addConstraintVelocity();c.updateMultipliers(k,q,1/a)}},c.updateMultipliers=function(a,b,c){for(var d=a.length;d--;)a[d].multiplier=b[d]*c},c.iterateEquation=function(a,b,c,d,e,f,g,h){var i=d[a],j=e[a],k=f[a],l=b.computeGWlambda(),m=b.maxForce,n=b.minForce;g&&(i=0);var o=j*(i-l-c*k),p=k+o;return n*h>p?o=n*h-k:p>m*h&&(o=m*h-k),f[a]+=o,b.addToWlambda(o),o}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(a,b){function c(a,b){a=a||{},d.call(this),this.type=b,this.equations=[],this.equationSortFunction=a.equationSortFunction||!1}var d=(a("../utils/Utils"),a("../events/EventEmitter"));b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.solve=function(){throw new Error("Solver.solve should be implemented by subclasses!")};var e={bodies:[]};c.prototype.solveIsland=function(a,b){this.removeAllEquations(),b.equations.length&&(this.addEquations(b.equations),e.bodies.length=0,b.getBodies(e.bodies),e.bodies.length&&this.solve(a,e))},c.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},c.prototype.addEquation=function(a){a.enabled&&this.equations.push(a)},c.prototype.addEquations=function(a){for(var b=0,c=a.length;b!==c;b++){var d=a[b];d.enabled&&this.equations.push(d)}},c.prototype.removeEquation=function(a){var b=this.equations.indexOf(a);-1!==b&&this.equations.splice(b,1)},c.prototype.removeAllEquations=function(){this.equations.length=0},c.GS=1,c.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../equations/ContactEquation"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.bodyA=a.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../equations/FrictionEquation"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.bodyA=a.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../world/IslandNode"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../world/Island"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(a,b){function c(){this.overlappingShapesLastState=new d,this.overlappingShapesCurrentState=new d,this.recordPool=new e({size:16}),this.tmpDict=new d,this.tmpArray1=[]}{var d=a("./TupleDictionary"),e=(a("./OverlapKeeperRecord"),a("./OverlapKeeperRecordPool"));a("./Utils")}b.exports=c,c.prototype.tick=function(){for(var a=this.overlappingShapesLastState,b=this.overlappingShapesCurrentState,c=a.keys.length;c--;){{var d=a.keys[c],e=a.getByKey(d);b.getByKey(d)}e&&this.recordPool.release(e)}a.reset(),a.copy(b),b.reset()},c.prototype.setOverlapping=function(a,b,c,d){var e=(this.overlappingShapesLastState,this.overlappingShapesCurrentState);if(!e.get(b.id,d.id)){var f=this.recordPool.get();f.set(a,b,c,d),e.set(b.id,d.id,f)}},c.prototype.getNewOverlaps=function(a){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,a)},c.prototype.getEndOverlaps=function(a){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,a)},c.prototype.bodiesAreOverlapping=function(a,b){for(var c=this.overlappingShapesCurrentState,d=c.keys.length;d--;){var e=c.keys[d],f=c.data[e];if(f.bodyA===a&&f.bodyB===b||f.bodyA===b&&f.bodyB===a)return!0}return!1},c.prototype.getDiff=function(a,b,c){var c=c||[],d=a,e=b;c.length=0;for(var f=e.keys.length;f--;){var g=e.keys[f],h=e.data[g];if(!h)throw new Error("Key "+g+" had no data!");var i=d.data[g];i||c.push(h)}return c},c.prototype.isNewOverlap=function(a,b){var c=0|a.id,d=0|b.id,e=this.overlappingShapesLastState,f=this.overlappingShapesCurrentState;return!e.get(c,d)&&!!f.get(c,d)},c.prototype.getNewBodyOverlaps=function(a){this.tmpArray1.length=0;var b=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(b,a)},c.prototype.getEndBodyOverlaps=function(a){this.tmpArray1.length=0;var b=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(b,a)},c.prototype.getBodyDiff=function(a,b){b=b||[];for(var c=this.tmpDict,d=a.length;d--;){var e=a[d];c.set(0|e.bodyA.id,0|e.bodyB.id,e)}for(d=c.keys.length;d--;){var e=c.getByKey(c.keys[d]);e&&b.push(e.bodyA,e.bodyB)}return c.reset(),b}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(a,b){function c(a,b,c,d){this.shapeA=b,this.shapeB=d,this.bodyA=a,this.bodyB=c}b.exports=c,c.prototype.set=function(a,b,d,e){c.call(this,a,b,d,e)}},{}],54:[function(a,b){function c(){e.apply(this,arguments)}var d=a("./OverlapKeeperRecord"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.bodyA=a.bodyB=a.shapeA=a.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(a,b){function c(a){a=a||{},this.objects=[],void 0!==a.size&&this.resize(a.size)}b.exports=c,c.prototype.resize=function(a){for(var b=this.objects;b.length>a;)b.pop();for(;b.length<a;)b.push(this.create());return this},c.prototype.get=function(){var a=this.objects;return a.length?a.pop():this.create()},c.prototype.release=function(a){return this.destroy(a),this.objects.push(a),this}},{}],56:[function(a,b){function c(){this.data={},this.keys=[]}var d=a("./Utils");b.exports=c,c.prototype.getKey=function(a,b){return a=0|a,b=0|b,(0|a)===(0|b)?-1:0|((0|a)>(0|b)?a<<16|65535&b:b<<16|65535&a)},c.prototype.getByKey=function(a){return a=0|a,this.data[a]},c.prototype.get=function(a,b){return this.data[this.getKey(a,b)]},c.prototype.set=function(a,b,c){if(!c)throw new Error("No data!");var d=this.getKey(a,b);return this.data[d]||this.keys.push(d),this.data[d]=c,d},c.prototype.reset=function(){for(var a=this.data,b=this.keys,c=b.length;c--;)delete a[b[c]];b.length=0},c.prototype.copy=function(a){this.reset(),d.appendArray(this.keys,a.keys);for(var b=a.keys.length;b--;){var c=a.keys[b];this.data[c]=a.data[c]}}},{"./Utils":57}],57:[function(a,b){function c(){}b.exports=c,c.appendArray=function(a,b){if(b.length<15e4)a.push.apply(a,b);else for(var c=0,d=b.length;c!==d;++c)a.push(b[c])},c.splice=function(a,b,c){c=c||1;for(var d=b,e=a.length-c;e>d;d++)a[d]=a[d+c];a.length=e},c.ARRAY_TYPE="undefined"!=typeof P2_ARRAY_TYPE?P2_ARRAY_TYPE:"undefined"!=typeof Float32Array?Float32Array:Array,c.extend=function(a,b){for(var c in b)a[c]=b[c]},c.defaults=function(a,b){a=a||{};for(var c in b)c in a||(a[c]=b[c]);return a}},{}],58:[function(a,b){function c(){this.equations=[],this.bodies=[]}var d=a("../objects/Body");b.exports=c,c.prototype.reset=function(){this.equations.length=this.bodies.length=0};var e=[];c.prototype.getBodies=function(a){var b=a||[],c=this.equations;e.length=0;for(var d=0;d!==c.length;d++){var f=c[d];-1===e.indexOf(f.bodyA.id)&&(b.push(f.bodyA),e.push(f.bodyA.id)),-1===e.indexOf(f.bodyB.id)&&(b.push(f.bodyB),e.push(f.bodyB.id))}return b},c.prototype.wantsToSleep=function(){for(var a=0;a<this.bodies.length;a++){var b=this.bodies[a];if(b.type===d.DYNAMIC&&!b.wantsToSleep)return!1}return!0},c.prototype.sleep=function(){for(var a=0;a<this.bodies.length;a++){var b=this.bodies[a];b.sleep()}return!0}},{"../objects/Body":31}],59:[function(a,b){function c(){this.nodePool=new d({size:16}),this.islandPool=new e({size:8}),this.equations=[],this.islands=[],this.nodes=[],this.queue=[]}var d=(a("../math/vec2"),a("./Island"),a("./IslandNode"),a("./../utils/IslandNodePool")),e=a("./../utils/IslandPool"),f=a("../objects/Body");b.exports=c,c.getUnvisitedNode=function(a){for(var b=a.length,c=0;c!==b;c++){var d=a[c];if(!d.visited&&d.body.type===f.DYNAMIC)return d}return!1},c.prototype.visit=function(a,b,c){b.push(a.body);for(var d=a.equations.length,e=0;e!==d;e++){var f=a.equations[e];-1===c.indexOf(f)&&c.push(f)}},c.prototype.bfs=function(a,b,d){var e=this.queue;for(e.length=0,e.push(a),a.visited=!0,this.visit(a,b,d);e.length;)for(var g,h=e.pop();g=c.getUnvisitedNode(h.neighbors);)g.visited=!0,this.visit(g,b,d),g.body.type===f.DYNAMIC&&e.push(g)},c.prototype.split=function(a){for(var b=a.bodies,d=this.nodes,e=this.equations;d.length;)this.nodePool.release(d.pop());for(var f=0;f!==b.length;f++){var g=this.nodePool.get();g.body=b[f],d.push(g)}for(var h=0;h!==e.length;h++){var i=e[h],f=b.indexOf(i.bodyA),j=b.indexOf(i.bodyB),k=d[f],l=d[j];k.neighbors.push(l),l.neighbors.push(k),k.equations.push(i),l.equations.push(i)}for(var m=this.islands,f=0;f<m.length;f++)this.islandPool.release(m[f]);m.length=0;for(var n;n=c.getUnvisitedNode(d);){var o=this.islandPool.get();this.bfs(n,o.bodies,o.equations),m.push(o)}return m}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(a,b){function c(a){this.body=a,this.neighbors=[],this.equations=[],this.visited=!1}b.exports=c,c.prototype.reset=function(){this.equations.length=0,this.neighbors.length=0,this.visited=!1,this.body=null}},{}],61:[function(a,b){function c(a){k.apply(this),a=a||{},this.springs=[],this.bodies=[],this.disabledBodyCollisionPairs=[],this.solver=a.solver||new d,this.narrowphase=new q(this),this.islandManager=new t,this.gravity=e.fromValues(0,-9.78),a.gravity&&e.copy(this.gravity,a.gravity),this.frictionGravity=e.length(this.gravity)||10,this.useWorldGravityAsFrictionGravity=!0,this.useFrictionGravityOnZeroGravity=!0,this.broadphase=a.broadphase||new p,this.broadphase.setWorld(this),this.constraints=[],this.defaultMaterial=new m,this.defaultContactMaterial=new n(this.defaultMaterial,this.defaultMaterial),this.lastTimeStep=1/60,this.applySpringForces=!0,this.applyDamping=!0,this.applyGravity=!0,this.solveConstraints=!0,this.contactMaterials=[],this.time=0,this.accumulator=0,this.stepping=!1,this.bodiesToBeRemoved=[],this.islandSplit="undefined"!=typeof a.islandSplit?!!a.islandSplit:!0,this.emitImpactEvent=!0,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=c.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 s}{var d=a("../solver/GSSolver"),e=(a("../solver/Solver"),a("../collision/Ray"),a("../math/vec2")),f=a("../shapes/Circle"),g=a("../shapes/Convex"),h=(a("../shapes/Line"),a("../shapes/Plane")),i=a("../shapes/Capsule"),j=a("../shapes/Particle"),k=a("../events/EventEmitter"),l=a("../objects/Body"),m=(a("../shapes/Shape"),a("../objects/LinearSpring"),a("../material/Material")),n=a("../material/ContactMaterial"),o=(a("../constraints/DistanceConstraint"),a("../constraints/Constraint"),a("../constraints/LockConstraint"),a("../constraints/RevoluteConstraint"),a("../constraints/PrismaticConstraint"),a("../constraints/GearConstraint"),a("../../package.json"),a("../collision/Broadphase"),a("../collision/AABB")),p=a("../collision/SAPBroadphase"),q=a("../collision/Narrowphase"),r=a("../utils/Utils"),s=a("../utils/OverlapKeeper"),t=a("./IslandManager");a("../objects/RotationalSpring")}b.exports=c,c.prototype=new Object(k.prototype),c.prototype.constructor=c,c.NO_SLEEPING=1,c.BODY_SLEEPING=2,c.ISLAND_SLEEPING=4,c.prototype.addConstraint=function(a){this.constraints.push(a)},c.prototype.addContactMaterial=function(a){this.contactMaterials.push(a)},c.prototype.removeContactMaterial=function(a){var b=this.contactMaterials.indexOf(a);-1!==b&&r.splice(this.contactMaterials,b,1)},c.prototype.getContactMaterial=function(a,b){for(var c=this.contactMaterials,d=0,e=c.length;d!==e;d++){var f=c[d];if(f.materialA.id===a.id&&f.materialB.id===b.id||f.materialA.id===b.id&&f.materialB.id===a.id)return f}return!1},c.prototype.removeConstraint=function(a){var b=this.constraints.indexOf(a);-1!==b&&r.splice(this.constraints,b,1)};{var u=(e.create(),e.create(),e.create(),e.create(),e.create(),e.create(),e.create()),v=e.fromValues(0,0),w=e.fromValues(0,0);e.fromValues(0,0),e.fromValues(0,0)}c.prototype.step=function(a,b,c){if(c=c||10,b=b||0,0===b)this.internalStep(a),this.time+=a;else{this.accumulator+=b;for(var d=0;this.accumulator>=a&&c>d;)this.internalStep(a),this.time+=a,this.accumulator-=a,d++;for(var f=this.accumulator%a/a,g=0;g!==this.bodies.length;g++){var h=this.bodies[g];e.lerp(h.interpolatedPosition,h.previousPosition,h.position,f),h.interpolatedAngle=h.previousAngle+f*(h.angle-h.previousAngle)}}};var x=[];c.prototype.internalStep=function(a){this.stepping=!0;var b=this.springs.length,d=this.springs,f=this.bodies,g=this.gravity,h=this.solver,i=this.bodies.length,j=this.broadphase,k=this.narrowphase,m=this.constraints,n=u,o=(e.scale,e.add),p=(e.rotate,this.islandManager);if(this.overlapKeeper.tick(),this.lastTimeStep=a,this.useWorldGravityAsFrictionGravity){var q=e.length(this.gravity);0===q&&this.useFrictionGravityOnZeroGravity||(this.frictionGravity=q)}if(this.applyGravity)for(var s=0;s!==i;s++){var t=f[s],v=t.force;t.type===l.DYNAMIC&&t.sleepState!==l.SLEEPING&&(e.scale(n,g,t.mass*t.gravityScale),o(v,v,n))}if(this.applySpringForces)for(var s=0;s!==b;s++){var w=d[s];w.applyForce()}if(this.applyDamping)for(var s=0;s!==i;s++){var t=f[s];t.type===l.DYNAMIC&&t.applyDamping(a)}for(var y=j.getCollisionPairs(this),z=this.disabledBodyCollisionPairs,s=z.length-2;s>=0;s-=2)for(var A=y.length-2;A>=0;A-=2)(z[s]===y[A]&&z[s+1]===y[A+1]||z[s+1]===y[A]&&z[s]===y[A+1])&&y.splice(A,2);var B=m.length;for(s=0;s!==B;s++){var C=m[s];if(!C.collideConnected)for(var A=y.length-2;A>=0;A-=2)(C.bodyA===y[A]&&C.bodyB===y[A+1]||C.bodyB===y[A]&&C.bodyA===y[A+1])&&y.splice(A,2)}this.postBroadphaseEvent.pairs=y,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,k.reset(this);for(var s=0,D=y.length;s!==D;s+=2)for(var E=y[s],F=y[s+1],G=0,H=E.shapes.length;G!==H;G++)for(var I=E.shapes[G],J=I.position,K=I.angle,L=0,M=F.shapes.length;L!==M;L++){var N=F.shapes[L],O=N.position,P=N.angle,Q=this.defaultContactMaterial;if(I.material&&N.material){var R=this.getContactMaterial(I.material,N.material);R&&(Q=R)}this.runNarrowphase(k,E,I,J,K,F,N,O,P,Q,this.frictionGravity)}for(var s=0;s!==i;s++){var S=f[s];S._wakeUpAfterNarrowphase&&(S.wakeUp(),S._wakeUpAfterNarrowphase=!1)}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(x);for(var T=this.endContactEvent,L=x.length;L--;){var U=x[L];T.shapeA=U.shapeA,T.shapeB=U.shapeB,T.bodyA=U.bodyA,T.bodyB=U.bodyB,this.emit(T)}x.length=0}var V=this.preSolveEvent;V.contactEquations=k.contactEquations,V.frictionEquations=k.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var B=m.length;for(s=0;s!==B;s++)m[s].update();if(k.contactEquations.length||k.frictionEquations.length||B)if(this.islandSplit){for(p.equations.length=0,r.appendArray(p.equations,k.contactEquations),r.appendArray(p.equations,k.frictionEquations),s=0;s!==B;s++)r.appendArray(p.equations,m[s].equations);p.split(this);for(var s=0;s!==p.islands.length;s++){var W=p.islands[s];W.equations.length&&h.solveIsland(a,W)}}else{for(h.addEquations(k.contactEquations),h.addEquations(k.frictionEquations),s=0;s!==B;s++)h.addEquations(m[s].equations);this.solveConstraints&&h.solve(a,this),h.removeAllEquations()}for(var s=0;s!==i;s++){var S=f[s];S.integrate(a)}for(var s=0;s!==i;s++)f[s].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var X=this.impactEvent,s=0;s!==k.contactEquations.length;s++){var Y=k.contactEquations[s];Y.firstImpact&&(X.bodyA=Y.bodyA,X.bodyB=Y.bodyB,X.shapeA=Y.shapeA,X.shapeB=Y.shapeB,X.contactEquation=Y,this.emit(X))}if(this.sleepMode===c.BODY_SLEEPING)for(s=0;s!==i;s++)f[s].sleepTick(this.time,!1,a);else if(this.sleepMode===c.ISLAND_SLEEPING&&this.islandSplit){for(s=0;s!==i;s++)f[s].sleepTick(this.time,!0,a);for(var s=0;s<this.islandManager.islands.length;s++){var W=this.islandManager.islands[s];W.wantsToSleep()&&W.sleep()}}this.stepping=!1;for(var Z=this.bodiesToBeRemoved,s=0;s!==Z.length;s++)this.removeBody(Z[s]);Z.length=0,this.emit(this.postStepEvent)},c.prototype.runNarrowphase=function(a,b,c,d,f,g,h,i,j,k,m){if(0!==(c.collisionGroup&h.collisionMask)&&0!==(h.collisionGroup&c.collisionMask)){e.rotate(v,d,b.angle),e.rotate(w,i,g.angle),e.add(v,v,b.position),e.add(w,w,g.position);var n=f+b.angle,o=j+g.angle;a.enableFriction=k.friction>0,a.frictionCoefficient=k.friction;var p;p=b.type===l.STATIC||b.type===l.KINEMATIC?g.mass:g.type===l.STATIC||g.type===l.KINEMATIC?b.mass:b.mass*g.mass/(b.mass+g.mass),a.slipForce=k.friction*m*p,a.restitution=k.restitution,a.surfaceVelocity=k.surfaceVelocity,a.frictionStiffness=k.frictionStiffness,a.frictionRelaxation=k.frictionRelaxation,a.stiffness=k.stiffness,a.relaxation=k.relaxation,a.contactSkinSize=k.contactSkinSize,a.enabledEquations=b.collisionResponse&&g.collisionResponse&&c.collisionResponse&&h.collisionResponse;var q=a[c.type|h.type],r=0;if(q){var s=c.sensor||h.sensor,t=a.frictionEquations.length;r=c.type<h.type?q.call(a,b,c,v,n,g,h,w,o,s):q.call(a,g,h,w,o,b,c,v,n,s);var u=a.frictionEquations.length-t;if(r){if(b.allowSleep&&b.type===l.DYNAMIC&&b.sleepState===l.SLEEPING&&g.sleepState===l.AWAKE&&g.type!==l.STATIC){var x=e.squaredLength(g.velocity)+Math.pow(g.angularVelocity,2),y=Math.pow(g.sleepSpeedLimit,2);x>=2*y&&(b._wakeUpAfterNarrowphase=!0)}if(g.allowSleep&&g.type===l.DYNAMIC&&g.sleepState===l.SLEEPING&&b.sleepState===l.AWAKE&&b.type!==l.STATIC){var z=e.squaredLength(b.velocity)+Math.pow(b.angularVelocity,2),A=Math.pow(b.sleepSpeedLimit,2);z>=2*A&&(g._wakeUpAfterNarrowphase=!0)}if(this.overlapKeeper.setOverlapping(b,c,g,h),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(c,h)){var B=this.beginContactEvent;if(B.shapeA=c,B.shapeB=h,B.bodyA=b,B.bodyB=g,B.contactEquations.length=0,"number"==typeof r)for(var C=a.contactEquations.length-r;C<a.contactEquations.length;C++)B.contactEquations.push(a.contactEquations[C]);this.emit(B)}if("number"==typeof r&&u>1)for(var C=a.frictionEquations.length-u;C<a.frictionEquations.length;C++){var D=a.frictionEquations[C];D.setSlipForce(D.getSlipForce()/u)}}}}},c.prototype.addSpring=function(a){this.springs.push(a);var b=this.addSpringEvent;b.spring=a,this.emit(b),b.spring=null},c.prototype.removeSpring=function(a){var b=this.springs.indexOf(a);-1!==b&&r.splice(this.springs,b,1)},c.prototype.addBody=function(a){if(-1===this.bodies.indexOf(a)){this.bodies.push(a),a.world=this;var b=this.addBodyEvent;b.body=a,this.emit(b),b.body=null}},c.prototype.removeBody=function(a){if(this.stepping)this.bodiesToBeRemoved.push(a);else{a.world=null;var b=this.bodies.indexOf(a);-1!==b&&(r.splice(this.bodies,b,1),this.removeBodyEvent.body=a,a.resetConstraintVelocity(),this.emit(this.removeBodyEvent),this.removeBodyEvent.body=null)}},c.prototype.getBodyById=function(a){for(var b=this.bodies,c=0;c<b.length;c++){var d=b[c];if(d.id===a)return d}return!1},c.prototype.disableBodyCollision=function(a,b){this.disabledBodyCollisionPairs.push(a,b)},c.prototype.enableBodyCollision=function(a,b){for(var c=this.disabledBodyCollisionPairs,d=0;d<c.length;d+=2)if(c[d]===a&&c[d+1]===b||c[d+1]===a&&c[d]===b)return void c.splice(d,2)},c.prototype.clear=function(){this.time=0,this.solver&&this.solver.equations.length&&this.solver.removeAllEquations();for(var a=this.constraints,b=a.length-1;b>=0;b--)this.removeConstraint(a[b]);for(var d=this.bodies,b=d.length-1;b>=0;b--)this.removeBody(d[b]);for(var e=this.springs,b=e.length-1;b>=0;b--)this.removeSpring(e[b]);for(var f=this.contactMaterials,b=f.length-1;b>=0;b--)this.removeContactMaterial(f[b]);c.apply(this)};var y=e.create(),z=(e.fromValues(0,0),e.fromValues(0,0));c.prototype.hitTest=function(a,b,c){c=c||0;var d=new l({position:a}),k=new j,m=a,n=0,o=y,p=z;d.addShape(k);for(var q=this.narrowphase,r=[],s=0,t=b.length;s!==t;s++)for(var u=b[s],v=0,w=u.shapes.length;v!==w;v++){var x=u.shapes[v];e.rotate(o,x.position,u.angle),e.add(o,o,u.position);var A=x.angle+u.angle;(x instanceof f&&q.circleParticle(u,x,o,A,d,k,m,n,!0)||x instanceof g&&q.particleConvex(d,k,m,n,u,x,o,A,!0)||x instanceof h&&q.particlePlane(d,k,m,n,u,x,o,A,!0)||x instanceof i&&q.particleCapsule(d,k,m,n,u,x,o,A,!0)||x instanceof j&&e.squaredLength(e.sub(p,o,a))<c*c)&&r.push(u)}return r},c.prototype.setGlobalStiffness=function(a){for(var b=this.constraints,c=0;c!==b.length;c++)for(var d=b[c],e=0;e!==d.equations.length;e++){var f=d.equations[e];f.stiffness=a,f.needsUpdate=!0}for(var g=this.contactMaterials,c=0;c!==g.length;c++){var d=g[c];d.stiffness=d.frictionStiffness=a}var d=this.defaultContactMaterial;d.stiffness=d.frictionStiffness=a},c.prototype.setGlobalRelaxation=function(a){for(var b=0;b!==this.constraints.length;b++)for(var c=this.constraints[b],d=0;d!==c.equations.length;d++){var e=c.equations[d];e.relaxation=a,e.needsUpdate=!0}for(var b=0;b!==this.contactMaterials.length;b++){var c=this.contactMaterials[b];c.relaxation=c.frictionRelaxation=a}var c=this.defaultContactMaterial;c.relaxation=c.frictionRelaxation=a};var A=new o,B=[];c.prototype.raycast=function(a,b){return b.getAABB(A),this.broadphase.aabbQuery(this,A,B),b.intersectBodies(a,B),B.length=0,a.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":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])(36)}),function(){var a=this,b=b||{};return b.WEBGL_RENDERER=0,b.CANVAS_RENDERER=1,b.VERSION="v2.2.8",b._UID=0,"undefined"!=typeof Float32Array?(b.Float32Array=Float32Array,b.Uint16Array=Uint16Array,b.Uint32Array=Uint32Array,b.ArrayBuffer=ArrayBuffer):(b.Float32Array=Array,b.Uint16Array=Array),b.PI_2=2*Math.PI,b.RAD_TO_DEG=180/Math.PI,b.DEG_TO_RAD=Math.PI/180,b.RETINA_PREFIX="@2x",b.defaultRenderOptions={view:null,transparent:!1,antialias:!1,preserveDrawingBuffer:!1,resolution:1,clearBeforeRender:!0,autoResize:!1},b.DisplayObject=function(){this.position=new b.Point(0,0),this.scale=new b.Point(1,1),this.transformCallback=null,this.transformCallbackContext=null,this.pivot=new b.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.renderable=!1,this.parent=null,this.stage=null,this.worldAlpha=1,this.worldTransform=new b.Matrix,this.worldPosition=new b.Point(0,0),this.worldScale=new b.Point(1,1),this.worldRotation=0,this._sr=0,this._cr=1,this.filterArea=null,this._bounds=new b.Rectangle(0,0,1,1),this._currentBounds=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheIsDirty=!1},b.DisplayObject.prototype.constructor=b.DisplayObject,b.DisplayObject.prototype.destroy=function(){if(this.children){for(var a=this.children.length;a--;)this.children[a].destroy();this.children=[]}this.transformCallback=null,this.transformCallbackContext=null,this.hitArea=null,this.parent=null,this.stage=null,this.worldTransform=null,this.filterArea=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.renderable=!1,this._destroyCachedSprite()},Object.defineProperty(b.DisplayObject.prototype,"worldVisible",{get:function(){var a=this;do{if(!a.visible)return!1;a=a.parent}while(a);return!0}}),Object.defineProperty(b.DisplayObject.prototype,"mask",{get:function(){return this._mask},set:function(a){this._mask&&(this._mask.isMask=!1),this._mask=a,this._mask&&(this._mask.isMask=!0)}}),Object.defineProperty(b.DisplayObject.prototype,"filters",{get:function(){return this._filters},set:function(a){if(a){for(var b=[],c=0;c<a.length;c++)for(var d=a[c].passes,e=0;e<d.length;e++)b.push(d[e]);this._filterBlock={target:this,filterPasses:b}}this._filters=a}}),Object.defineProperty(b.DisplayObject.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(a){this._cacheAsBitmap!==a&&(a?this._generateCachedSprite():this._destroyCachedSprite(),this._cacheAsBitmap=a)}}),b.DisplayObject.prototype.updateTransform=function(a){if(a||this.parent||this.game){var c=this.parent;a?c=a:this.parent||(c=this.game.world);var d,e,f,g,h,i,j=c.worldTransform,k=this.worldTransform;this.rotation%b.PI_2?(this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation)),d=this._cr*this.scale.x,e=this._sr*this.scale.x,f=-this._sr*this.scale.y,g=this._cr*this.scale.y,h=this.position.x,i=this.position.y,(this.pivot.x||this.pivot.y)&&(h-=this.pivot.x*d+this.pivot.y*f,i-=this.pivot.x*e+this.pivot.y*g),k.a=d*j.a+e*j.c,k.b=d*j.b+e*j.d,k.c=f*j.a+g*j.c,k.d=f*j.b+g*j.d,k.tx=h*j.a+i*j.c+j.tx,k.ty=h*j.b+i*j.d+j.ty):(d=this.scale.x,g=this.scale.y,h=this.position.x-this.pivot.x*d,i=this.position.y-this.pivot.y*g,k.a=d*j.a,k.b=d*j.b,k.c=g*j.c,k.d=g*j.d,k.tx=h*j.a+i*j.c+j.tx,k.ty=h*j.b+i*j.d+j.ty),this.worldAlpha=this.alpha*c.worldAlpha,this.worldPosition.set(k.tx,k.ty),this.worldScale.set(Math.sqrt(k.a*k.a+k.b*k.b),Math.sqrt(k.c*k.c+k.d*k.d)),this.worldRotation=Math.atan2(-k.c,k.d),this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,k,j)}},b.DisplayObject.prototype.displayObjectUpdateTransform=b.DisplayObject.prototype.updateTransform,b.DisplayObject.prototype.getBounds=function(a){return a=a,b.EmptyRectangle},b.DisplayObject.prototype.getLocalBounds=function(){return this.getBounds(b.identityMatrix)},b.DisplayObject.prototype.setStageReference=function(a){this.stage=a},b.DisplayObject.prototype.preUpdate=function(){},b.DisplayObject.prototype.generateTexture=function(a,c,d){var e=this.getLocalBounds(),f=new b.RenderTexture(0|e.width,0|e.height,d,c,a);return b.DisplayObject._tempMatrix.tx=-e.x,b.DisplayObject._tempMatrix.ty=-e.y,f.render(this,b.DisplayObject._tempMatrix),f},b.DisplayObject.prototype.updateCache=function(){this._generateCachedSprite()},b.DisplayObject.prototype.toGlobal=function(a){return this.displayObjectUpdateTransform(),this.worldTransform.apply(a)},b.DisplayObject.prototype.toLocal=function(a,b){return b&&(a=b.toGlobal(a)),this.displayObjectUpdateTransform(),this.worldTransform.applyInverse(a)},b.DisplayObject.prototype._renderCachedSprite=function(a){this._cachedSprite.worldAlpha=this.worldAlpha,a.gl?b.Sprite.prototype._renderWebGL.call(this._cachedSprite,a):b.Sprite.prototype._renderCanvas.call(this._cachedSprite,a)},b.DisplayObject.prototype._generateCachedSprite=function(){this._cacheAsBitmap=!1;var a=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.texture.resize(0|a.width,0|a.height);else{var c=new b.RenderTexture(0|a.width,0|a.height);this._cachedSprite=new b.Sprite(c),this._cachedSprite.worldTransform=this.worldTransform}var d=this._filters;this._filters=null,this._cachedSprite.filters=d,b.DisplayObject._tempMatrix.tx=-a.x,b.DisplayObject._tempMatrix.ty=-a.y,this._cachedSprite.texture.render(this,b.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-(a.x/a.width),this._cachedSprite.anchor.y=-(a.y/a.height),this._filters=d,this._cacheAsBitmap=!0},b.DisplayObject.prototype._destroyCachedSprite=function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)},b.DisplayObject.prototype._renderWebGL=function(a){a=a},b.DisplayObject.prototype._renderCanvas=function(a){a=a},Object.defineProperty(b.DisplayObject.prototype,"x",{get:function(){return this.position.x},set:function(a){this.position.x=a}}),Object.defineProperty(b.DisplayObject.prototype,"y",{get:function(){return this.position.y},set:function(a){this.position.y=a}}),b.DisplayObjectContainer=function(){b.DisplayObject.call(this),this.children=[]},b.DisplayObjectContainer.prototype=Object.create(b.DisplayObject.prototype),b.DisplayObjectContainer.prototype.constructor=b.DisplayObjectContainer,Object.defineProperty(b.DisplayObjectContainer.prototype,"width",{get:function(){return this.scale.x*this.getLocalBounds().width},set:function(a){var b=this.getLocalBounds().width;this.scale.x=0!==b?a/b:1,this._width=a}}),Object.defineProperty(b.DisplayObjectContainer.prototype,"height",{get:function(){return this.scale.y*this.getLocalBounds().height},set:function(a){var b=this.getLocalBounds().height;this.scale.y=0!==b?a/b:1,this._height=a}}),b.DisplayObjectContainer.prototype.addChild=function(a){return this.addChildAt(a,this.children.length)},b.DisplayObjectContainer.prototype.addChildAt=function(a,b){if(b>=0&&b<=this.children.length)return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),this.stage&&a.setStageReference(this.stage),a;throw new Error(a+"addChildAt: The index "+b+" supplied is out of bounds "+this.children.length)},b.DisplayObjectContainer.prototype.swapChildren=function(a,b){if(a!==b){var c=this.getChildIndex(a),d=this.getChildIndex(b);if(0>c||0>d)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[c]=b,this.children[d]=a}},b.DisplayObjectContainer.prototype.getChildIndex=function(a){var b=this.children.indexOf(a);if(-1===b)throw new Error("The supplied DisplayObject must be a child of the caller");return b},b.DisplayObjectContainer.prototype.setChildIndex=function(a,b){if(0>b||b>=this.children.length)throw new Error("The supplied index is out of bounds");var c=this.getChildIndex(a);this.children.splice(c,1),this.children.splice(b,0,a)},b.DisplayObjectContainer.prototype.getChildAt=function(a){if(0>a||a>=this.children.length)throw new Error("getChildAt: Supplied index "+a+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[a]},b.DisplayObjectContainer.prototype.removeChild=function(a){var b=this.children.indexOf(a);
-if(-1!==b)return this.removeChildAt(b)},b.DisplayObjectContainer.prototype.removeChildAt=function(a){var b=this.getChildAt(a);return this.stage&&b.removeStageReference(),b.parent=void 0,this.children.splice(a,1),b},b.DisplayObjectContainer.prototype.removeChildren=function(a,b){var c=a||0,d="number"==typeof b?b:this.children.length,e=d-c;if(e>0&&d>=e){for(var f=this.children.splice(c,e),g=0;g<f.length;g++){var h=f[g];this.stage&&h.removeStageReference(),h.parent=void 0}return f}if(0===e&&0===this.children.length)return[];throw new Error("removeChildren: Range Error, numeric values are outside the acceptable range")},b.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible&&(this.displayObjectUpdateTransform(),!this._cacheAsBitmap))for(var a=0;a<this.children.length;a++)this.children[a].updateTransform()},b.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform=b.DisplayObjectContainer.prototype.updateTransform,b.DisplayObjectContainer.prototype.getBounds=function(){if(0===this.children.length)return b.EmptyRectangle;for(var a,c,d,e=1/0,f=1/0,g=-1/0,h=-1/0,i=!1,j=0,k=this.children.length;k>j;j++){var l=this.children[j];l.visible&&(i=!0,a=this.children[j].getBounds(),e=e<a.x?e:a.x,f=f<a.y?f:a.y,c=a.width+a.x,d=a.height+a.y,g=g>c?g:c,h=h>d?h:d)}if(!i)return b.EmptyRectangle;var m=this._bounds;return m.x=e,m.y=f,m.width=g-e,m.height=h-f,m},b.DisplayObjectContainer.prototype.getLocalBounds=function(){var a=this.worldTransform;this.worldTransform=b.identityMatrix;for(var c=0,d=this.children.length;d>c;c++)this.children[c].updateTransform();var e=this.getBounds();return this.worldTransform=a,e},b.DisplayObjectContainer.prototype.setStageReference=function(a){this.stage=a;for(var b=0;b<this.children.length;b++)this.children[b].setStageReference(a)},b.DisplayObjectContainer.prototype.removeStageReference=function(){for(var a=0;a<this.children.length;a++)this.children[a].removeStageReference();this.stage=null},b.DisplayObjectContainer.prototype._renderWebGL=function(a){if(this.visible&&!(this.alpha<=0)){if(this._cacheAsBitmap)return void this._renderCachedSprite(a);var b;if(this._mask||this._filters){for(this._filters&&(a.spriteBatch.flush(),a.filterManager.pushFilter(this._filterBlock)),this._mask&&(a.spriteBatch.stop(),a.maskManager.pushMask(this.mask,a),a.spriteBatch.start()),b=0;b<this.children.length;b++)this.children[b]._renderWebGL(a);a.spriteBatch.stop(),this._mask&&a.maskManager.popMask(this._mask,a),this._filters&&a.filterManager.popFilter(),a.spriteBatch.start()}else for(b=0;b<this.children.length;b++)this.children[b]._renderWebGL(a)}},b.DisplayObjectContainer.prototype._renderCanvas=function(a){if(this.visible!==!1&&0!==this.alpha){if(this._cacheAsBitmap)return void this._renderCachedSprite(a);this._mask&&a.maskManager.pushMask(this._mask,a);for(var b=0;b<this.children.length;b++)this.children[b]._renderCanvas(a);this._mask&&a.maskManager.popMask(a)}},b.Sprite=function(a){b.DisplayObjectContainer.call(this),this.anchor=new b.Point,this.texture=a||b.Texture.emptyTexture,this._width=0,this._height=0,this.tint=16777215,this.cachedTint=-1,this.tintedTexture=null,this.blendMode=b.blendModes.NORMAL,this.shader=null,this.texture.baseTexture.hasLoaded&&this.onTextureUpdate(),this.renderable=!0},b.Sprite.prototype=Object.create(b.DisplayObjectContainer.prototype),b.Sprite.prototype.constructor=b.Sprite,Object.defineProperty(b.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(a){this.scale.x=a/this.texture.frame.width,this._width=a}}),Object.defineProperty(b.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(a){this.scale.y=a/this.texture.frame.height,this._height=a}}),b.Sprite.prototype.setTexture=function(a){this.texture=a,this.texture.valid=!0},b.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height)},b.Sprite.prototype.getBounds=function(a){var b=this.texture.frame.width,c=this.texture.frame.height,d=b*(1-this.anchor.x),e=b*-this.anchor.x,f=c*(1-this.anchor.y),g=c*-this.anchor.y,h=a||this.worldTransform,i=h.a,j=h.b,k=h.c,l=h.d,m=h.tx,n=h.ty,o=-1/0,p=-1/0,q=1/0,r=1/0;if(0===j&&0===k)0>i&&(i*=-1),0>l&&(l*=-1),q=i*e+m,o=i*d+m,r=l*g+n,p=l*f+n;else{var s=i*e+k*g+m,t=l*g+j*e+n,u=i*d+k*g+m,v=l*g+j*d+n,w=i*d+k*f+m,x=l*f+j*d+n,y=i*e+k*f+m,z=l*f+j*e+n;q=q>s?s:q,q=q>u?u:q,q=q>w?w:q,q=q>y?y:q,r=r>t?t:r,r=r>v?v:r,r=r>x?x:r,r=r>z?z:r,o=s>o?s:o,o=u>o?u:o,o=w>o?w:o,o=y>o?y:o,p=t>p?t:p,p=v>p?v:p,p=x>p?x:p,p=z>p?z:p}var A=this._bounds;return A.x=q,A.width=o-q,A.y=r,A.height=p-r,this._currentBounds=A,A},b.Sprite.prototype._renderWebGL=function(a,b){if(this.visible&&!(this.alpha<=0)&&this.renderable){var c=this.worldTransform;if(b&&(c=b),this._mask||this._filters){var d=a.spriteBatch;this._filters&&(d.flush(),a.filterManager.pushFilter(this._filterBlock)),this._mask&&(d.stop(),a.maskManager.pushMask(this.mask,a),d.start()),d.render(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(a);d.stop(),this._mask&&a.maskManager.popMask(this._mask,a),this._filters&&a.filterManager.popFilter(),d.start()}else{a.spriteBatch.render(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(a,c)}}},b.Sprite.prototype._renderCanvas=function(a,c){if(!(this.visible===!1||0===this.alpha||this.renderable===!1||this.texture.crop.width<=0||this.texture.crop.height<=0)){var d=this.worldTransform;if(c&&(d=c),this.blendMode!==a.currentBlendMode&&(a.currentBlendMode=this.blendMode,a.context.globalCompositeOperation=b.blendModesCanvas[a.currentBlendMode]),this._mask&&a.maskManager.pushMask(this._mask,a),this.texture.valid){var e=this.texture.baseTexture.resolution/a.resolution;a.context.globalAlpha=this.worldAlpha,a.smoothProperty&&a.scaleMode!==this.texture.baseTexture.scaleMode&&(a.scaleMode=this.texture.baseTexture.scaleMode,a.context[a.smoothProperty]=a.scaleMode===b.scaleModes.LINEAR);var f=this.texture.trim?this.texture.trim.x-this.anchor.x*this.texture.trim.width:this.anchor.x*-this.texture.frame.width,g=this.texture.trim?this.texture.trim.y-this.anchor.y*this.texture.trim.height:this.anchor.y*-this.texture.frame.height;a.roundPixels?(a.context.setTransform(d.a,d.b,d.c,d.d,d.tx*a.resolution|0,d.ty*a.resolution|0),f=0|f,g=0|g):a.context.setTransform(d.a,d.b,d.c,d.d,d.tx*a.resolution,d.ty*a.resolution);var h=this.texture.crop.width,i=this.texture.crop.height;if(f/=e,g/=e,16777215!==this.tint)(this.texture.requiresReTint||this.cachedTint!==this.tint)&&(this.tintedTexture=b.CanvasTinter.getTintedTexture(this,this.tint),this.cachedTint=this.tint),a.context.drawImage(this.tintedTexture,0,0,h,i,f,g,h/e,i/e);else{var j=this.texture.crop.x,k=this.texture.crop.y;a.context.drawImage(this.texture.baseTexture.source,j,k,h,i,f,g,h/e,i/e)}}for(var l=0;l<this.children.length;l++)this.children[l]._renderCanvas(a);this._mask&&a.maskManager.popMask(a)}},b.Sprite.fromFrame=function(a){var c=b.TextureCache[a];if(!c)throw new Error('The frameId "'+a+'" does not exist in the texture cache'+this);return new b.Sprite(c)},b.Sprite.fromImage=function(a,c,d){var e=b.Texture.fromImage(a,c,d);return new b.Sprite(e)},b.SpriteBatch=function(a){b.DisplayObjectContainer.call(this),this.textureThing=a,this.ready=!1},b.SpriteBatch.prototype=Object.create(b.DisplayObjectContainer.prototype),b.SpriteBatch.prototype.constructor=b.SpriteBatch,b.SpriteBatch.prototype.initWebGL=function(a){this.fastSpriteBatch=new b.WebGLFastSpriteBatch(a),this.ready=!0},b.SpriteBatch.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},b.SpriteBatch.prototype._renderWebGL=function(a){!this.visible||this.alpha<=0||!this.children.length||(this.ready||this.initWebGL(a.gl),this.fastSpriteBatch.gl!==a.gl&&this.fastSpriteBatch.setContext(a.gl),a.spriteBatch.stop(),a.shaderManager.setShader(a.shaderManager.fastShader),this.fastSpriteBatch.begin(this,a),this.fastSpriteBatch.render(this),a.spriteBatch.start())},b.SpriteBatch.prototype._renderCanvas=function(a){if(this.visible&&!(this.alpha<=0)&&this.children.length){var b=a.context;b.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var c=this.worldTransform,d=!0,e=0;e<this.children.length;e++){var f=this.children[e];if(f.visible){var g=f.texture,h=g.frame;if(b.globalAlpha=this.worldAlpha*f.alpha,f.rotation%(2*Math.PI)===0)d&&(b.setTransform(c.a,c.b,c.c,c.d,c.tx,c.ty),d=!1),b.drawImage(g.baseTexture.source,h.x,h.y,h.width,h.height,f.anchor.x*-h.width*f.scale.x+f.position.x+.5|0,f.anchor.y*-h.height*f.scale.y+f.position.y+.5|0,h.width*f.scale.x,h.height*f.scale.y);else{d||(d=!0),f.displayObjectUpdateTransform();var i=f.worldTransform;a.roundPixels?b.setTransform(i.a,i.b,i.c,i.d,0|i.tx,0|i.ty):b.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty),b.drawImage(g.baseTexture.source,h.x,h.y,h.width,h.height,f.anchor.x*-h.width+.5|0,f.anchor.y*-h.height+.5|0,h.width,h.height)}}}}},b.Stage=function(a){b.DisplayObjectContainer.call(this),this.worldTransform=new b.Matrix,this.stage=this,this.setBackgroundColor(a)},b.Stage.prototype=Object.create(b.DisplayObjectContainer.prototype),b.Stage.prototype.constructor=b.Stage,b.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var a=0;a<this.children.length;a++)this.children[a].updateTransform()},b.Stage.prototype.setBackgroundColor=function(a){this.backgroundColor=a||0,this.backgroundColorSplit=b.hex2rgb(this.backgroundColor);var c=this.backgroundColor.toString(16);c="000000".substr(0,6-c.length)+c,this.backgroundColorString="#"+c},b.hex2rgb=function(a){return[(a>>16&255)/255,(a>>8&255)/255,(255&a)/255]},b.rgb2hex=function(a){return(255*a[0]<<16)+(255*a[1]<<8)+255*a[2]},b.canUseNewCanvasBlendModes=function(){if(void 0===document)return!1;var a="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",b="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",c=new Image;c.src=a+"AP804Oa6"+b;var d=new Image;d.src=a+"/wCKxvRF"+b;var e=document.createElement("canvas");e.width=6,e.height=1;var f=e.getContext("2d");if(f.globalCompositeOperation="multiply",f.drawImage(c,0,0),f.drawImage(d,2,0),!f.getImageData(2,0,1,1))return!1;var g=f.getImageData(2,0,1,1).data;return 255===g[0]&&0===g[1]&&0===g[2]},b.getNextPowerOfTwo=function(a){if(a>0&&0===(a&a-1))return a;for(var b=1;a>b;)b<<=1;return b},b.isPowerOfTwo=function(a,b){return a>0&&0===(a&a-1)&&b>0&&0===(b&b-1)},b.PolyK={},b.PolyK.Triangulate=function(a){var c=!0,d=a.length>>1;if(3>d)return[];for(var e=[],f=[],g=0;d>g;g++)f.push(g);g=0;for(var h=d;h>3;){var i=f[(g+0)%h],j=f[(g+1)%h],k=f[(g+2)%h],l=a[2*i],m=a[2*i+1],n=a[2*j],o=a[2*j+1],p=a[2*k],q=a[2*k+1],r=!1;if(b.PolyK._convex(l,m,n,o,p,q,c)){r=!0;for(var s=0;h>s;s++){var t=f[s];if(t!==i&&t!==j&&t!==k&&b.PolyK._PointInTriangle(a[2*t],a[2*t+1],l,m,n,o,p,q)){r=!1;break}}}if(r)e.push(i,j,k),f.splice((g+1)%h,1),h--,g=0;else if(g++>3*h){if(!c)return null;for(e=[],f=[],g=0;d>g;g++)f.push(g);g=0,h=d,c=!1}}return e.push(f[0],f[1],f[2]),e},b.PolyK._PointInTriangle=function(a,b,c,d,e,f,g,h){var i=g-c,j=h-d,k=e-c,l=f-d,m=a-c,n=b-d,o=i*i+j*j,p=i*k+j*l,q=i*m+j*n,r=k*k+l*l,s=k*m+l*n,t=1/(o*r-p*p),u=(r*q-p*s)*t,v=(o*s-p*q)*t;return u>=0&&v>=0&&1>u+v},b.PolyK._convex=function(a,b,c,d,e,f,g){return(b-d)*(e-c)+(c-a)*(f-d)>=0===g},b.initDefaultShaders=function(){},b.CompileVertexShader=function(a,c){return b._CompileShader(a,c,a.VERTEX_SHADER)},b.CompileFragmentShader=function(a,c){return b._CompileShader(a,c,a.FRAGMENT_SHADER)},b._CompileShader=function(a,b,c){var d=b;Array.isArray(b)&&(d=b.join("\n"));var e=a.createShader(c);return a.shaderSource(e,d),a.compileShader(e),a.getShaderParameter(e,a.COMPILE_STATUS)?e:(window.console.log(a.getShaderInfoLog(e)),null)},b.compileProgram=function(a,c,d){var e=b.CompileFragmentShader(a,d),f=b.CompileVertexShader(a,c),g=a.createProgram();return a.attachShader(g,f),a.attachShader(g,e),a.linkProgram(g),a.getProgramParameter(g,a.LINK_STATUS)||window.console.log("Could not initialise shaders"),g},b.PixiShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.textureCount=0,this.firstRun=!0,this.dirty=!0,this.attributes=[],this.init()},b.PixiShader.prototype.constructor=b.PixiShader,b.PixiShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc||b.PixiShader.defaultVertexSrc,this.fragmentSrc);a.useProgram(c),this.uSampler=a.getUniformLocation(c,"uSampler"),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.dimensions=a.getUniformLocation(c,"dimensions"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.aTextureCoord=a.getAttribLocation(c,"aTextureCoord"),this.colorAttribute=a.getAttribLocation(c,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var d in this.uniforms)this.uniforms[d].uniformLocation=a.getUniformLocation(c,d);this.initUniforms(),this.program=c},b.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var a,b=this.gl;for(var c in this.uniforms){a=this.uniforms[c];var d=a.type;"sampler2D"===d?(a._init=!1,null!==a.value&&this.initSampler2D(a)):"mat2"===d||"mat3"===d||"mat4"===d?(a.glMatrix=!0,a.glValueLength=1,"mat2"===d?a.glFunc=b.uniformMatrix2fv:"mat3"===d?a.glFunc=b.uniformMatrix3fv:"mat4"===d&&(a.glFunc=b.uniformMatrix4fv)):(a.glFunc=b["uniform"+d],a.glValueLength="2f"===d||"2i"===d?2:"3f"===d||"3i"===d?3:"4f"===d||"4i"===d?4:1)}},b.PixiShader.prototype.initSampler2D=function(a){if(a.value&&a.value.baseTexture&&a.value.baseTexture.hasLoaded){var b=this.gl;if(b.activeTexture(b["TEXTURE"+this.textureCount]),b.bindTexture(b.TEXTURE_2D,a.value.baseTexture._glTextures[b.id]),a.textureData){var c=a.textureData,d=c.magFilter?c.magFilter:b.LINEAR,e=c.minFilter?c.minFilter:b.LINEAR,f=c.wrapS?c.wrapS:b.CLAMP_TO_EDGE,g=c.wrapT?c.wrapT:b.CLAMP_TO_EDGE,h=c.luminance?b.LUMINANCE:b.RGBA;if(c.repeat&&(f=b.REPEAT,g=b.REPEAT),b.pixelStorei(b.UNPACK_FLIP_Y_WEBGL,!!c.flipY),c.width){var i=c.width?c.width:512,j=c.height?c.height:2,k=c.border?c.border:0;b.texImage2D(b.TEXTURE_2D,0,h,i,j,k,h,b.UNSIGNED_BYTE,null)}else b.texImage2D(b.TEXTURE_2D,0,h,b.RGBA,b.UNSIGNED_BYTE,a.value.baseTexture.source);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,d),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,e),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,f),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,g)}b.uniform1i(a.uniformLocation,this.textureCount),a._init=!0,this.textureCount++}},b.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var a,c=this.gl;for(var d in this.uniforms)a=this.uniforms[d],1===a.glValueLength?a.glMatrix===!0?a.glFunc.call(c,a.uniformLocation,a.transpose,a.value):a.glFunc.call(c,a.uniformLocation,a.value):2===a.glValueLength?a.glFunc.call(c,a.uniformLocation,a.value.x,a.value.y):3===a.glValueLength?a.glFunc.call(c,a.uniformLocation,a.value.x,a.value.y,a.value.z):4===a.glValueLength?a.glFunc.call(c,a.uniformLocation,a.value.x,a.value.y,a.value.z,a.value.w):"sampler2D"===a.type&&(a._init?(c.activeTexture(c["TEXTURE"+this.textureCount]),a.value.baseTexture._dirty[c.id]?b.instances[c.id].updateTexture(a.value.baseTexture):c.bindTexture(c.TEXTURE_2D,a.value.baseTexture._glTextures[c.id]),c.uniform1i(a.uniformLocation,this.textureCount),this.textureCount++):this.initSampler2D(a))},b.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},b.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec4 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {","   gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);","   vTextureCoord = aTextureCoord;","   vColor = vec4(aColor.rgb * aColor.a, aColor.a);","}"],b.PixiFastShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {","   vec2 v;","   vec2 sv = aVertexPosition * aScale;","   v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);","   v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);","   v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;","   gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);","   vTextureCoord = aTextureCoord;","   vColor = aColor;","}"],this.textureCount=0,this.init()},b.PixiFastShader.prototype.constructor=b.PixiFastShader,b.PixiFastShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.uSampler=a.getUniformLocation(c,"uSampler"),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.dimensions=a.getUniformLocation(c,"dimensions"),this.uMatrix=a.getUniformLocation(c,"uMatrix"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.aPositionCoord=a.getAttribLocation(c,"aPositionCoord"),this.aScale=a.getAttribLocation(c,"aScale"),this.aRotation=a.getAttribLocation(c,"aRotation"),this.aTextureCoord=a.getAttribLocation(c,"aTextureCoord"),this.colorAttribute=a.getAttribLocation(c,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute],this.program=c},b.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},b.StripShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","void main(void) {","   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);","   v -= offsetVector.xyx;","   gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);","   vTextureCoord = aTextureCoord;","}"],this.init()},b.StripShader.prototype.constructor=b.StripShader,b.StripShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.uSampler=a.getUniformLocation(c,"uSampler"),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.colorAttribute=a.getAttribLocation(c,"aColor"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.aTextureCoord=a.getAttribLocation(c,"aTextureCoord"),this.attributes=[this.aVertexPosition,this.aTextureCoord],this.translationMatrix=a.getUniformLocation(c,"translationMatrix"),this.alpha=a.getUniformLocation(c,"alpha"),this.program=c},b.StripShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},b.PrimitiveShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {","   gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform float flipY;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {","   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);","   v -= offsetVector.xyx;","   gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);","   vColor = aColor * vec4(tint * alpha, alpha);","}"],this.init()},b.PrimitiveShader.prototype.constructor=b.PrimitiveShader,b.PrimitiveShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.tintColor=a.getUniformLocation(c,"tint"),this.flipY=a.getUniformLocation(c,"flipY"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.colorAttribute=a.getAttribLocation(c,"aColor"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=a.getUniformLocation(c,"translationMatrix"),this.alpha=a.getUniformLocation(c,"alpha"),this.program=c},b.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},b.ComplexPrimitiveShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {","   gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform vec3 tint;","uniform float alpha;","uniform vec3 color;","uniform float flipY;","varying vec4 vColor;","void main(void) {","   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);","   v -= offsetVector.xyx;","   gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);","   vColor = vec4(color * alpha * tint, alpha);","}"],this.init()},b.ComplexPrimitiveShader.prototype.constructor=b.ComplexPrimitiveShader,b.ComplexPrimitiveShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.tintColor=a.getUniformLocation(c,"tint"),this.color=a.getUniformLocation(c,"color"),this.flipY=a.getUniformLocation(c,"flipY"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=a.getUniformLocation(c,"translationMatrix"),this.alpha=a.getUniformLocation(c,"alpha"),this.program=c},b.ComplexPrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},b.WebGLGraphics=function(){},b.WebGLGraphics.renderGraphics=function(a,c){var d,e=c.gl,f=c.projection,g=c.offset,h=c.shaderManager.primitiveShader;a.dirty&&b.WebGLGraphics.updateGraphics(a,e);for(var i=a._webGL[e.id],j=0;j<i.data.length;j++)1===i.data[j].mode?(d=i.data[j],c.stencilManager.pushStencil(a,d,c),e.drawElements(e.TRIANGLE_FAN,4,e.UNSIGNED_SHORT,2*(d.indices.length-4)),c.stencilManager.popStencil(a,d,c)):(d=i.data[j],c.shaderManager.setShader(h),h=c.shaderManager.primitiveShader,e.uniformMatrix3fv(h.translationMatrix,!1,a.worldTransform.toArray(!0)),e.uniform1f(h.flipY,1),e.uniform2f(h.projectionVector,f.x,-f.y),e.uniform2f(h.offsetVector,-g.x,-g.y),e.uniform3fv(h.tintColor,b.hex2rgb(a.tint)),e.uniform1f(h.alpha,a.worldAlpha),e.bindBuffer(e.ARRAY_BUFFER,d.buffer),e.vertexAttribPointer(h.aVertexPosition,2,e.FLOAT,!1,24,0),e.vertexAttribPointer(h.colorAttribute,4,e.FLOAT,!1,24,8),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,d.indexBuffer),e.drawElements(e.TRIANGLE_STRIP,d.indices.length,e.UNSIGNED_SHORT,0))},b.WebGLGraphics.updateGraphics=function(a,c){var d=a._webGL[c.id];d||(d=a._webGL[c.id]={lastIndex:0,data:[],gl:c}),a.dirty=!1;var e;if(a.clearDirty){for(a.clearDirty=!1,e=0;e<d.data.length;e++){var f=d.data[e];f.reset(),b.WebGLGraphics.graphicsDataPool.push(f)}d.data=[],d.lastIndex=0}var g;for(e=d.lastIndex;e<a.graphicsData.length;e++){var h=a.graphicsData[e];if(h.type===b.Graphics.POLY){if(h.points=h.shape.points.slice(),h.shape.closed&&(h.points[0]!==h.points[h.points.length-2]||h.points[1]!==h.points[h.points.length-1])&&h.points.push(h.points[0],h.points[1]),h.fill&&h.points.length>=6)if(h.points.length<12){g=b.WebGLGraphics.switchMode(d,0);var i=b.WebGLGraphics.buildPoly(h,g);i||(g=b.WebGLGraphics.switchMode(d,1),b.WebGLGraphics.buildComplexPoly(h,g))}else g=b.WebGLGraphics.switchMode(d,1),b.WebGLGraphics.buildComplexPoly(h,g);h.lineWidth>0&&(g=b.WebGLGraphics.switchMode(d,0),b.WebGLGraphics.buildLine(h,g))}else g=b.WebGLGraphics.switchMode(d,0),h.type===b.Graphics.RECT?b.WebGLGraphics.buildRectangle(h,g):h.type===b.Graphics.CIRC||h.type===b.Graphics.ELIP?b.WebGLGraphics.buildCircle(h,g):h.type===b.Graphics.RREC&&b.WebGLGraphics.buildRoundedRectangle(h,g);d.lastIndex++}for(e=0;e<d.data.length;e++)g=d.data[e],g.dirty&&g.upload()},b.WebGLGraphics.switchMode=function(a,c){var d;return a.data.length?(d=a.data[a.data.length-1],(d.mode!==c||1===c)&&(d=b.WebGLGraphics.graphicsDataPool.pop()||new b.WebGLGraphicsData(a.gl),d.mode=c,a.data.push(d))):(d=b.WebGLGraphics.graphicsDataPool.pop()||new b.WebGLGraphicsData(a.gl),d.mode=c,a.data.push(d)),d.dirty=!0,d},b.WebGLGraphics.buildRectangle=function(a,c){var d=a.shape,e=d.x,f=d.y,g=d.width,h=d.height;if(a.fill){var i=b.hex2rgb(a.fillColor),j=a.fillAlpha,k=i[0]*j,l=i[1]*j,m=i[2]*j,n=c.points,o=c.indices,p=n.length/6;n.push(e,f),n.push(k,l,m,j),n.push(e+g,f),n.push(k,l,m,j),n.push(e,f+h),n.push(k,l,m,j),n.push(e+g,f+h),n.push(k,l,m,j),o.push(p,p,p+1,p+2,p+3,p+3)}if(a.lineWidth){var q=a.points;a.points=[e,f,e+g,f,e+g,f+h,e,f+h,e,f],b.WebGLGraphics.buildLine(a,c),a.points=q}},b.WebGLGraphics.buildRoundedRectangle=function(a,c){var d=a.shape,e=d.x,f=d.y,g=d.width,h=d.height,i=d.radius,j=[];if(j.push(e,f+i),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e,f+h-i,e,f+h,e+i,f+h)),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e+g-i,f+h,e+g,f+h,e+g,f+h-i)),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e+g,f+i,e+g,f,e+g-i,f)),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e+i,f,e,f,e,f+i)),a.fill){var k=b.hex2rgb(a.fillColor),l=a.fillAlpha,m=k[0]*l,n=k[1]*l,o=k[2]*l,p=c.points,q=c.indices,r=p.length/6,s=b.PolyK.Triangulate(j),t=0;for(t=0;t<s.length;t+=3)q.push(s[t]+r),q.push(s[t]+r),q.push(s[t+1]+r),q.push(s[t+2]+r),q.push(s[t+2]+r);for(t=0;t<j.length;t++)p.push(j[t],j[++t],m,n,o,l)}if(a.lineWidth){var u=a.points;a.points=j,b.WebGLGraphics.buildLine(a,c),a.points=u}},b.WebGLGraphics.quadraticBezierCurve=function(a,b,c,d,e,f){function g(a,b,c){var d=b-a;return a+d*c}for(var h,i,j,k,l,m,n=20,o=[],p=0,q=0;n>=q;q++)p=q/n,h=g(a,c,p),i=g(b,d,p),j=g(c,e,p),k=g(d,f,p),l=g(h,j,p),m=g(i,k,p),o.push(l,m);return o},b.WebGLGraphics.buildCircle=function(a,c){var d,e,f=a.shape,g=f.x,h=f.y;a.type===b.Graphics.CIRC?(d=f.radius,e=f.radius):(d=f.width,e=f.height);var i=40,j=2*Math.PI/i,k=0;if(a.fill){var l=b.hex2rgb(a.fillColor),m=a.fillAlpha,n=l[0]*m,o=l[1]*m,p=l[2]*m,q=c.points,r=c.indices,s=q.length/6;for(r.push(s),k=0;i+1>k;k++)q.push(g,h,n,o,p,m),q.push(g+Math.sin(j*k)*d,h+Math.cos(j*k)*e,n,o,p,m),r.push(s++,s++);r.push(s-1)}if(a.lineWidth){var t=a.points;for(a.points=[],k=0;i+1>k;k++)a.points.push(g+Math.sin(j*k)*d,h+Math.cos(j*k)*e);b.WebGLGraphics.buildLine(a,c),a.points=t}},b.WebGLGraphics.buildLine=function(a,c){var d=0,e=a.points;if(0!==e.length){if(a.lineWidth%2)for(d=0;d<e.length;d++)e[d]+=.5;var f=new b.Point(e[0],e[1]),g=new b.Point(e[e.length-2],e[e.length-1]);if(f.x===g.x&&f.y===g.y){e=e.slice(),e.pop(),e.pop(),g=new b.Point(e[e.length-2],e[e.length-1]);var h=g.x+.5*(f.x-g.x),i=g.y+.5*(f.y-g.y);e.unshift(h,i),e.push(h,i)}var j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G=c.points,H=c.indices,I=e.length/2,J=e.length,K=G.length/6,L=a.lineWidth/2,M=b.hex2rgb(a.lineColor),N=a.lineAlpha,O=M[0]*N,P=M[1]*N,Q=M[2]*N;for(l=e[0],m=e[1],n=e[2],o=e[3],r=-(m-o),s=l-n,F=Math.sqrt(r*r+s*s),r/=F,s/=F,r*=L,s*=L,G.push(l-r,m-s,O,P,Q,N),G.push(l+r,m+s,O,P,Q,N),d=1;I-1>d;d++)l=e[2*(d-1)],m=e[2*(d-1)+1],n=e[2*d],o=e[2*d+1],p=e[2*(d+1)],q=e[2*(d+1)+1],r=-(m-o),s=l-n,F=Math.sqrt(r*r+s*s),r/=F,s/=F,r*=L,s*=L,t=-(o-q),u=n-p,F=Math.sqrt(t*t+u*u),t/=F,u/=F,t*=L,u*=L,x=-s+m-(-s+o),y=-r+n-(-r+l),z=(-r+l)*(-s+o)-(-r+n)*(-s+m),A=-u+q-(-u+o),B=-t+n-(-t+p),C=(-t+p)*(-u+o)-(-t+n)*(-u+q),D=x*B-A*y,Math.abs(D)<.1?(D+=10.1,G.push(n-r,o-s,O,P,Q,N),G.push(n+r,o+s,O,P,Q,N)):(j=(y*C-B*z)/D,k=(A*z-x*C)/D,E=(j-n)*(j-n)+(k-o)+(k-o),E>19600?(v=r-t,w=s-u,F=Math.sqrt(v*v+w*w),v/=F,w/=F,v*=L,w*=L,G.push(n-v,o-w),G.push(O,P,Q,N),G.push(n+v,o+w),G.push(O,P,Q,N),G.push(n-v,o-w),G.push(O,P,Q,N),J++):(G.push(j,k),G.push(O,P,Q,N),G.push(n-(j-n),o-(k-o)),G.push(O,P,Q,N)));for(l=e[2*(I-2)],m=e[2*(I-2)+1],n=e[2*(I-1)],o=e[2*(I-1)+1],r=-(m-o),s=l-n,F=Math.sqrt(r*r+s*s),r/=F,s/=F,r*=L,s*=L,G.push(n-r,o-s),G.push(O,P,Q,N),G.push(n+r,o+s),G.push(O,P,Q,N),H.push(K),d=0;J>d;d++)H.push(K++);H.push(K-1)}},b.WebGLGraphics.buildComplexPoly=function(a,c){var d=a.points.slice();if(!(d.length<6)){var e=c.indices;c.points=d,c.alpha=a.fillAlpha,c.color=b.hex2rgb(a.fillColor);for(var f,g,h=1/0,i=-1/0,j=1/0,k=-1/0,l=0;l<d.length;l+=2)f=d[l],g=d[l+1],h=h>f?f:h,i=f>i?f:i,j=j>g?g:j,k=g>k?g:k;d.push(h,j,i,j,i,k,h,k);var m=d.length/2;for(l=0;m>l;l++)e.push(l)}},b.WebGLGraphics.buildPoly=function(a,c){var d=a.points;if(!(d.length<6)){var e=c.points,f=c.indices,g=d.length/2,h=b.hex2rgb(a.fillColor),i=a.fillAlpha,j=h[0]*i,k=h[1]*i,l=h[2]*i,m=b.PolyK.Triangulate(d);if(!m)return!1;var n=e.length/6,o=0;for(o=0;o<m.length;o+=3)f.push(m[o]+n),f.push(m[o]+n),f.push(m[o+1]+n),f.push(m[o+2]+n),f.push(m[o+2]+n);for(o=0;g>o;o++)e.push(d[2*o],d[2*o+1],j,k,l,i);return!0}},b.WebGLGraphics.graphicsDataPool=[],b.WebGLGraphicsData=function(a){this.gl=a,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),this.mode=1,this.alpha=1,this.dirty=!0},b.WebGLGraphicsData.prototype.reset=function(){this.points=[],this.indices=[]},b.WebGLGraphicsData.prototype.upload=function(){var a=this.gl;this.glPoints=new b.Float32Array(this.points),a.bindBuffer(a.ARRAY_BUFFER,this.buffer),a.bufferData(a.ARRAY_BUFFER,this.glPoints,a.STATIC_DRAW),this.glIndicies=new b.Uint16Array(this.indices),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,this.glIndicies,a.STATIC_DRAW),this.dirty=!1},b.glContexts=[],b.instances=[],b.WebGLRenderer=function(a,c,d){if(d)for(var e in b.defaultRenderOptions)void 0===d[e]&&(d[e]=b.defaultRenderOptions[e]);else d=b.defaultRenderOptions;b.defaultRenderer||(b.defaultRenderer=this),this.type=b.WEBGL_RENDERER,this.resolution=d.resolution,this.transparent=d.transparent,this.autoResize=d.autoResize||!1,this.preserveDrawingBuffer=d.preserveDrawingBuffer,this.clearBeforeRender=d.clearBeforeRender,this.width=a||800,this.height=c||600,this.view=d.view||document.createElement("canvas"),this._contextOptions={alpha:this.transparent,antialias:d.antialias,premultipliedAlpha:this.transparent&&"notMultiplied"!==this.transparent,stencil:!0,preserveDrawingBuffer:d.preserveDrawingBuffer},this.projection=new b.Point,this.offset=new b.Point(0,0),this.shaderManager=new b.WebGLShaderManager,this.spriteBatch=new b.WebGLSpriteBatch,this.maskManager=new b.WebGLMaskManager,this.filterManager=new b.WebGLFilterManager,this.stencilManager=new b.WebGLStencilManager,this.blendModeManager=new b.WebGLBlendModeManager,this.renderSession={},this.renderSession.gl=this.gl,this.renderSession.drawCount=0,this.renderSession.shaderManager=this.shaderManager,this.renderSession.maskManager=this.maskManager,this.renderSession.filterManager=this.filterManager,this.renderSession.blendModeManager=this.blendModeManager,this.renderSession.spriteBatch=this.spriteBatch,this.renderSession.stencilManager=this.stencilManager,this.renderSession.renderer=this,this.renderSession.resolution=this.resolution,this.initContext(),this.mapBlendModes()
-},b.WebGLRenderer.prototype.constructor=b.WebGLRenderer,b.WebGLRenderer.prototype.initContext=function(){var a=this.view.getContext("webgl",this._contextOptions)||this.view.getContext("experimental-webgl",this._contextOptions);if(this.gl=a,!a)throw new Error("This browser does not support webGL. Try using the canvas renderer");this.glContextId=a.id=b.WebGLRenderer.glContextId++,b.glContexts[this.glContextId]=a,b.instances[this.glContextId]=this,a.disable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.enable(a.BLEND),this.shaderManager.setContext(a),this.spriteBatch.setContext(a),this.maskManager.setContext(a),this.filterManager.setContext(a),this.blendModeManager.setContext(a),this.stencilManager.setContext(a),this.renderSession.gl=this.gl,this.resize(this.width,this.height)},b.WebGLRenderer.prototype.render=function(a){if(!this.contextLost){this.__stage!==a&&(this.__stage=a),a.updateTransform();var b=this.gl;b.viewport(0,0,this.width,this.height),b.bindFramebuffer(b.FRAMEBUFFER,null),this.clearBeforeRender&&(this.transparent?b.clearColor(0,0,0,0):b.clearColor(a.backgroundColorSplit[0],a.backgroundColorSplit[1],a.backgroundColorSplit[2],1),b.clear(b.COLOR_BUFFER_BIT)),this.renderDisplayObject(a,this.projection)}},b.WebGLRenderer.prototype.renderDisplayObject=function(a,c,d,e){this.renderSession.blendModeManager.setBlendMode(b.blendModes.NORMAL),this.renderSession.drawCount=0,this.renderSession.flipY=d?-1:1,this.renderSession.projection=c,this.renderSession.offset=this.offset,this.spriteBatch.begin(this.renderSession),this.filterManager.begin(this.renderSession,d),a._renderWebGL(this.renderSession,e),this.spriteBatch.end()},b.WebGLRenderer.prototype.resize=function(a,b){this.width=a*this.resolution,this.height=b*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.gl.viewport(0,0,this.width,this.height),this.projection.x=this.width/2/this.resolution,this.projection.y=-this.height/2/this.resolution},b.WebGLRenderer.prototype.updateTexture=function(a){if(a.hasLoaded){var c=this.gl;return a._glTextures[c.id]||(a._glTextures[c.id]=c.createTexture()),c.bindTexture(c.TEXTURE_2D,a._glTextures[c.id]),c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultipliedAlpha),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,a.source),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,a.scaleMode===b.scaleModes.LINEAR?c.LINEAR:c.NEAREST),a.mipmap&&b.isPowerOfTwo(a.width,a.height)?(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,a.scaleMode===b.scaleModes.LINEAR?c.LINEAR_MIPMAP_LINEAR:c.NEAREST_MIPMAP_NEAREST),c.generateMipmap(c.TEXTURE_2D)):c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,a.scaleMode===b.scaleModes.LINEAR?c.LINEAR:c.NEAREST),a._powerOf2?(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.REPEAT),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.REPEAT)):(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE)),a._dirty[c.id]=!1,a._glTextures[c.id]}},b.WebGLRenderer.prototype.destroy=function(){b.glContexts[this.glContextId]=null,this.projection=null,this.offset=null,this.shaderManager.destroy(),this.spriteBatch.destroy(),this.maskManager.destroy(),this.filterManager.destroy(),this.shaderManager=null,this.spriteBatch=null,this.maskManager=null,this.filterManager=null,this.gl=null,this.renderSession=null,b.instances[this.glContextId]=null,b.WebGLRenderer.glContextId--},b.WebGLRenderer.prototype.mapBlendModes=function(){var a=this.gl;b.blendModesWebGL||(b.blendModesWebGL=[],b.blendModesWebGL[b.blendModes.NORMAL]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.ADD]=[a.SRC_ALPHA,a.DST_ALPHA],b.blendModesWebGL[b.blendModes.MULTIPLY]=[a.DST_COLOR,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.SCREEN]=[a.SRC_ALPHA,a.ONE],b.blendModesWebGL[b.blendModes.OVERLAY]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.DARKEN]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.LIGHTEN]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.COLOR_DODGE]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.COLOR_BURN]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.HARD_LIGHT]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.SOFT_LIGHT]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.DIFFERENCE]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.EXCLUSION]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.HUE]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.SATURATION]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.COLOR]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.LUMINOSITY]=[a.ONE,a.ONE_MINUS_SRC_ALPHA])},b.WebGLRenderer.glContextId=0,b.WebGLBlendModeManager=function(){this.currentBlendMode=99999},b.WebGLBlendModeManager.prototype.constructor=b.WebGLBlendModeManager,b.WebGLBlendModeManager.prototype.setContext=function(a){this.gl=a},b.WebGLBlendModeManager.prototype.setBlendMode=function(a){if(this.currentBlendMode===a)return!1;this.currentBlendMode=a;var c=b.blendModesWebGL[this.currentBlendMode];return this.gl.blendFunc(c[0],c[1]),!0},b.WebGLBlendModeManager.prototype.destroy=function(){this.gl=null},b.WebGLMaskManager=function(){},b.WebGLMaskManager.prototype.constructor=b.WebGLMaskManager,b.WebGLMaskManager.prototype.setContext=function(a){this.gl=a},b.WebGLMaskManager.prototype.pushMask=function(a,c){var d=c.gl;a.dirty&&b.WebGLGraphics.updateGraphics(a,d),a._webGL[d.id].data.length&&c.stencilManager.pushStencil(a,a._webGL[d.id].data[0],c)},b.WebGLMaskManager.prototype.popMask=function(a,b){var c=this.gl;b.stencilManager.popStencil(a,a._webGL[c.id].data[0],b)},b.WebGLMaskManager.prototype.destroy=function(){this.gl=null},b.WebGLStencilManager=function(){this.stencilStack=[],this.reverse=!0,this.count=0},b.WebGLStencilManager.prototype.setContext=function(a){this.gl=a},b.WebGLStencilManager.prototype.pushStencil=function(a,b,c){var d=this.gl;this.bindGraphics(a,b,c),0===this.stencilStack.length&&(d.enable(d.STENCIL_TEST),d.clear(d.STENCIL_BUFFER_BIT),this.reverse=!0,this.count=0),this.stencilStack.push(b);var e=this.count;d.colorMask(!1,!1,!1,!1),d.stencilFunc(d.ALWAYS,0,255),d.stencilOp(d.KEEP,d.KEEP,d.INVERT),1===b.mode?(d.drawElements(d.TRIANGLE_FAN,b.indices.length-4,d.UNSIGNED_SHORT,0),this.reverse?(d.stencilFunc(d.EQUAL,255-e,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)):(d.stencilFunc(d.EQUAL,e,255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)),d.drawElements(d.TRIANGLE_FAN,4,d.UNSIGNED_SHORT,2*(b.indices.length-4)),this.reverse?d.stencilFunc(d.EQUAL,255-(e+1),255):d.stencilFunc(d.EQUAL,e+1,255),this.reverse=!this.reverse):(this.reverse?(d.stencilFunc(d.EQUAL,e,255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)):(d.stencilFunc(d.EQUAL,255-e,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)),d.drawElements(d.TRIANGLE_STRIP,b.indices.length,d.UNSIGNED_SHORT,0),this.reverse?d.stencilFunc(d.EQUAL,e+1,255):d.stencilFunc(d.EQUAL,255-(e+1),255)),d.colorMask(!0,!0,!0,!0),d.stencilOp(d.KEEP,d.KEEP,d.KEEP),this.count++},b.WebGLStencilManager.prototype.bindGraphics=function(a,c,d){this._currentGraphics=a;var e,f=this.gl,g=d.projection,h=d.offset;1===c.mode?(e=d.shaderManager.complexPrimitiveShader,d.shaderManager.setShader(e),f.uniform1f(e.flipY,d.flipY),f.uniformMatrix3fv(e.translationMatrix,!1,a.worldTransform.toArray(!0)),f.uniform2f(e.projectionVector,g.x,-g.y),f.uniform2f(e.offsetVector,-h.x,-h.y),f.uniform3fv(e.tintColor,b.hex2rgb(a.tint)),f.uniform3fv(e.color,c.color),f.uniform1f(e.alpha,a.worldAlpha*c.alpha),f.bindBuffer(f.ARRAY_BUFFER,c.buffer),f.vertexAttribPointer(e.aVertexPosition,2,f.FLOAT,!1,8,0),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c.indexBuffer)):(e=d.shaderManager.primitiveShader,d.shaderManager.setShader(e),f.uniformMatrix3fv(e.translationMatrix,!1,a.worldTransform.toArray(!0)),f.uniform1f(e.flipY,d.flipY),f.uniform2f(e.projectionVector,g.x,-g.y),f.uniform2f(e.offsetVector,-h.x,-h.y),f.uniform3fv(e.tintColor,b.hex2rgb(a.tint)),f.uniform1f(e.alpha,a.worldAlpha),f.bindBuffer(f.ARRAY_BUFFER,c.buffer),f.vertexAttribPointer(e.aVertexPosition,2,f.FLOAT,!1,24,0),f.vertexAttribPointer(e.colorAttribute,4,f.FLOAT,!1,24,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c.indexBuffer))},b.WebGLStencilManager.prototype.popStencil=function(a,b,c){var d=this.gl;if(this.stencilStack.pop(),this.count--,0===this.stencilStack.length)d.disable(d.STENCIL_TEST);else{var e=this.count;this.bindGraphics(a,b,c),d.colorMask(!1,!1,!1,!1),1===b.mode?(this.reverse=!this.reverse,this.reverse?(d.stencilFunc(d.EQUAL,255-(e+1),255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)):(d.stencilFunc(d.EQUAL,e+1,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)),d.drawElements(d.TRIANGLE_FAN,4,d.UNSIGNED_SHORT,2*(b.indices.length-4)),d.stencilFunc(d.ALWAYS,0,255),d.stencilOp(d.KEEP,d.KEEP,d.INVERT),d.drawElements(d.TRIANGLE_FAN,b.indices.length-4,d.UNSIGNED_SHORT,0),this.reverse?d.stencilFunc(d.EQUAL,e,255):d.stencilFunc(d.EQUAL,255-e,255)):(this.reverse?(d.stencilFunc(d.EQUAL,e+1,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)):(d.stencilFunc(d.EQUAL,255-(e+1),255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)),d.drawElements(d.TRIANGLE_STRIP,b.indices.length,d.UNSIGNED_SHORT,0),this.reverse?d.stencilFunc(d.EQUAL,e,255):d.stencilFunc(d.EQUAL,255-e,255)),d.colorMask(!0,!0,!0,!0),d.stencilOp(d.KEEP,d.KEEP,d.KEEP)}},b.WebGLStencilManager.prototype.destroy=function(){this.stencilStack=null,this.gl=null},b.WebGLShaderManager=function(){this.maxAttibs=10,this.attribState=[],this.tempAttribState=[];for(var a=0;a<this.maxAttibs;a++)this.attribState[a]=!1;this.stack=[]},b.WebGLShaderManager.prototype.constructor=b.WebGLShaderManager,b.WebGLShaderManager.prototype.setContext=function(a){this.gl=a,this.primitiveShader=new b.PrimitiveShader(a),this.complexPrimitiveShader=new b.ComplexPrimitiveShader(a),this.defaultShader=new b.PixiShader(a),this.fastShader=new b.PixiFastShader(a),this.stripShader=new b.StripShader(a),this.setShader(this.defaultShader)},b.WebGLShaderManager.prototype.setAttribs=function(a){var b;for(b=0;b<this.tempAttribState.length;b++)this.tempAttribState[b]=!1;for(b=0;b<a.length;b++){var c=a[b];this.tempAttribState[c]=!0}var d=this.gl;for(b=0;b<this.attribState.length;b++)this.attribState[b]!==this.tempAttribState[b]&&(this.attribState[b]=this.tempAttribState[b],this.tempAttribState[b]?d.enableVertexAttribArray(b):d.disableVertexAttribArray(b))},b.WebGLShaderManager.prototype.setShader=function(a){return this._currentId===a._UID?!1:(this._currentId=a._UID,this.currentShader=a,this.gl.useProgram(a.program),this.setAttribs(a.attributes),!0)},b.WebGLShaderManager.prototype.destroy=function(){this.attribState=null,this.tempAttribState=null,this.primitiveShader.destroy(),this.complexPrimitiveShader.destroy(),this.defaultShader.destroy(),this.fastShader.destroy(),this.stripShader.destroy(),this.gl=null},b.WebGLSpriteBatch=function(){this.vertSize=5,this.size=2e3;var a=4*this.size*4*this.vertSize,c=6*this.size;this.vertices=new b.ArrayBuffer(a),this.positions=new b.Float32Array(this.vertices),this.colors=new b.Uint32Array(this.vertices),this.indices=new b.Uint16Array(c),this.lastIndexCount=0;for(var d=0,e=0;c>d;d+=6,e+=4)this.indices[d+0]=e+0,this.indices[d+1]=e+1,this.indices[d+2]=e+2,this.indices[d+3]=e+0,this.indices[d+4]=e+2,this.indices[d+5]=e+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.dirty=!0,this.textures=[],this.blendModes=[],this.shaders=[],this.sprites=[],this.defaultShader=new b.AbstractFilter(["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"])},b.WebGLSpriteBatch.prototype.setContext=function(a){this.gl=a,this.vertexBuffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,this.indices,a.STATIC_DRAW),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bufferData(a.ARRAY_BUFFER,this.vertices,a.DYNAMIC_DRAW),this.currentBlendMode=99999;var c=new b.PixiShader(a);c.fragmentSrc=this.defaultShader.fragmentSrc,c.uniforms={},c.init(),this.defaultShader.shaders[a.id]=c},b.WebGLSpriteBatch.prototype.begin=function(a){this.renderSession=a,this.shader=this.renderSession.shaderManager.defaultShader,this.start()},b.WebGLSpriteBatch.prototype.end=function(){this.flush()},b.WebGLSpriteBatch.prototype.render=function(a,b){var c=a.texture,d=a.worldTransform;b&&(d=b),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=c.baseTexture);var e=c._uvs;if(e){var f,g,h,i,j=a.anchor.x,k=a.anchor.y;if(c.trim){var l=c.trim;g=l.x-j*l.width,f=g+c.crop.width,i=l.y-k*l.height,h=i+c.crop.height}else f=c.frame.width*(1-j),g=c.frame.width*-j,h=c.frame.height*(1-k),i=c.frame.height*-k;var m=4*this.currentBatchSize*this.vertSize,n=c.baseTexture.resolution,o=d.a/n,p=d.b/n,q=d.c/n,r=d.d/n,s=d.tx,t=d.ty,u=this.colors,v=this.positions;this.renderSession.roundPixels?(v[m]=o*g+q*i+s|0,v[m+1]=r*i+p*g+t|0,v[m+5]=o*f+q*i+s|0,v[m+6]=r*i+p*f+t|0,v[m+10]=o*f+q*h+s|0,v[m+11]=r*h+p*f+t|0,v[m+15]=o*g+q*h+s|0,v[m+16]=r*h+p*g+t|0):(v[m]=o*g+q*i+s,v[m+1]=r*i+p*g+t,v[m+5]=o*f+q*i+s,v[m+6]=r*i+p*f+t,v[m+10]=o*f+q*h+s,v[m+11]=r*h+p*f+t,v[m+15]=o*g+q*h+s,v[m+16]=r*h+p*g+t),v[m+2]=e.x0,v[m+3]=e.y0,v[m+7]=e.x1,v[m+8]=e.y1,v[m+12]=e.x2,v[m+13]=e.y2,v[m+17]=e.x3,v[m+18]=e.y3;var w=a.tint;u[m+4]=u[m+9]=u[m+14]=u[m+19]=(w>>16)+(65280&w)+((255&w)<<16)+(255*a.worldAlpha<<24),this.sprites[this.currentBatchSize++]=a}},b.WebGLSpriteBatch.prototype.renderTilingSprite=function(a){var c=a.tilingTexture;this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=c.baseTexture),a._uvs||(a._uvs=new b.TextureUvs);var d=a._uvs,e=c.baseTexture.width,f=c.baseTexture.height;a.tilePosition.x%=e*a.tileScaleOffset.x,a.tilePosition.y%=f*a.tileScaleOffset.y;var g=a.tilePosition.x/(e*a.tileScaleOffset.x),h=a.tilePosition.y/(f*a.tileScaleOffset.y),i=a.width/e/(a.tileScale.x*a.tileScaleOffset.x),j=a.height/f/(a.tileScale.y*a.tileScaleOffset.y);d.x0=0-g,d.y0=0-h,d.x1=1*i-g,d.y1=0-h,d.x2=1*i-g,d.y2=1*j-h,d.x3=0-g,d.y3=1*j-h;var k=a.tint,l=(k>>16)+(65280&k)+((255&k)<<16)+(255*a.worldAlpha<<24),m=this.positions,n=this.colors,o=a.width,p=a.height,q=a.anchor.x,r=a.anchor.y,s=o*(1-q),t=o*-q,u=p*(1-r),v=p*-r,w=4*this.currentBatchSize*this.vertSize,x=c.baseTexture.resolution,y=a.worldTransform,z=y.a/x,A=y.b/x,B=y.c/x,C=y.d/x,D=y.tx,E=y.ty;m[w++]=z*t+B*v+D,m[w++]=C*v+A*t+E,m[w++]=d.x0,m[w++]=d.y0,n[w++]=l,m[w++]=z*s+B*v+D,m[w++]=C*v+A*s+E,m[w++]=d.x1,m[w++]=d.y1,n[w++]=l,m[w++]=z*s+B*u+D,m[w++]=C*u+A*s+E,m[w++]=d.x2,m[w++]=d.y2,n[w++]=l,m[w++]=z*t+B*u+D,m[w++]=C*u+A*t+E,m[w++]=d.x3,m[w++]=d.y3,n[w++]=l,this.sprites[this.currentBatchSize++]=a},b.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var a,c=this.gl;if(this.dirty){this.dirty=!1,c.activeTexture(c.TEXTURE0),c.bindBuffer(c.ARRAY_BUFFER,this.vertexBuffer),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a=this.defaultShader.shaders[c.id];var d=4*this.vertSize;c.vertexAttribPointer(a.aVertexPosition,2,c.FLOAT,!1,d,0),c.vertexAttribPointer(a.aTextureCoord,2,c.FLOAT,!1,d,8),c.vertexAttribPointer(a.colorAttribute,4,c.UNSIGNED_BYTE,!0,d,16)}if(this.currentBatchSize>.5*this.size)c.bufferSubData(c.ARRAY_BUFFER,0,this.vertices);else{var e=this.positions.subarray(0,4*this.currentBatchSize*this.vertSize);c.bufferSubData(c.ARRAY_BUFFER,0,e)}for(var f,g,h,i,j=0,k=0,l=null,m=this.renderSession.blendModeManager.currentBlendMode,n=null,o=!1,p=!1,q=0,r=this.currentBatchSize;r>q;q++){if(i=this.sprites[q],f=i.tilingTexture?i.tilingTexture.baseTexture:i.texture.baseTexture,g=i.blendMode,h=i.shader||this.defaultShader,o=m!==g,p=n!==h,(l!==f||o||p)&&(this.renderBatch(l,j,k),k=q,j=0,l=f,o&&(m=g,this.renderSession.blendModeManager.setBlendMode(m)),p)){n=h,a=n.shaders[c.id],a||(a=new b.PixiShader(c),a.fragmentSrc=n.fragmentSrc,a.uniforms=n.uniforms,a.init(),n.shaders[c.id]=a),this.renderSession.shaderManager.setShader(a),a.dirty&&a.syncUniforms();var s=this.renderSession.projection;c.uniform2f(a.projectionVector,s.x,s.y);var t=this.renderSession.offset;c.uniform2f(a.offsetVector,t.x,t.y)}j++}this.renderBatch(l,j,k),this.currentBatchSize=0}},b.WebGLSpriteBatch.prototype.renderBatch=function(a,b,c){if(0!==b){var d=this.gl;a._dirty[d.id]?this.renderSession.renderer.updateTexture(a):d.bindTexture(d.TEXTURE_2D,a._glTextures[d.id]),d.drawElements(d.TRIANGLES,6*b,d.UNSIGNED_SHORT,6*c*2),this.renderSession.drawCount++}},b.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},b.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},b.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null,this.indices=null,this.gl.deleteBuffer(this.vertexBuffer),this.gl.deleteBuffer(this.indexBuffer),this.currentBaseTexture=null,this.gl=null},b.WebGLFastSpriteBatch=function(a){this.vertSize=10,this.maxSize=6e3,this.size=this.maxSize;var c=4*this.size*this.vertSize,d=6*this.maxSize;this.vertices=new b.Float32Array(c),this.indices=new b.Uint16Array(d),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var e=0,f=0;d>e;e+=6,f+=4)this.indices[e+0]=f+0,this.indices[e+1]=f+1,this.indices[e+2]=f+2,this.indices[e+3]=f+0,this.indices[e+4]=f+2,this.indices[e+5]=f+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.currentBlendMode=0,this.renderSession=null,this.shader=null,this.matrix=null,this.setContext(a)},b.WebGLFastSpriteBatch.prototype.constructor=b.WebGLFastSpriteBatch,b.WebGLFastSpriteBatch.prototype.setContext=function(a){this.gl=a,this.vertexBuffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,this.indices,a.STATIC_DRAW),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bufferData(a.ARRAY_BUFFER,this.vertices,a.DYNAMIC_DRAW)},b.WebGLFastSpriteBatch.prototype.begin=function(a,b){this.renderSession=b,this.shader=this.renderSession.shaderManager.fastShader,this.matrix=a.worldTransform.toArray(!0),this.start()},b.WebGLFastSpriteBatch.prototype.end=function(){this.flush()},b.WebGLFastSpriteBatch.prototype.render=function(a){var b=a.children,c=b[0];if(c.texture._uvs){this.currentBaseTexture=c.texture.baseTexture,c.blendMode!==this.renderSession.blendModeManager.currentBlendMode&&(this.flush(),this.renderSession.blendModeManager.setBlendMode(c.blendMode));for(var d=0,e=b.length;e>d;d++)this.renderSprite(b[d]);this.flush()}},b.WebGLFastSpriteBatch.prototype.renderSprite=function(a){if(a.visible&&(a.texture.baseTexture===this.currentBaseTexture||(this.flush(),this.currentBaseTexture=a.texture.baseTexture,a.texture._uvs))){var b,c,d,e,f,g,h,i,j=this.vertices;if(b=a.texture._uvs,c=a.texture.frame.width,d=a.texture.frame.height,a.texture.trim){var k=a.texture.trim;f=k.x-a.anchor.x*k.width,e=f+a.texture.crop.width,h=k.y-a.anchor.y*k.height,g=h+a.texture.crop.height}else e=a.texture.frame.width*(1-a.anchor.x),f=a.texture.frame.width*-a.anchor.x,g=a.texture.frame.height*(1-a.anchor.y),h=a.texture.frame.height*-a.anchor.y;i=4*this.currentBatchSize*this.vertSize,j[i++]=f,j[i++]=h,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x0,j[i++]=b.y1,j[i++]=a.alpha,j[i++]=e,j[i++]=h,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x1,j[i++]=b.y1,j[i++]=a.alpha,j[i++]=e,j[i++]=g,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x2,j[i++]=b.y2,j[i++]=a.alpha,j[i++]=f,j[i++]=g,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x3,j[i++]=b.y3,j[i++]=a.alpha,this.currentBatchSize++,this.currentBatchSize>=this.size&&this.flush()}},b.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var a=this.gl;if(this.currentBaseTexture._glTextures[a.id]||this.renderSession.renderer.updateTexture(this.currentBaseTexture,a),a.bindTexture(a.TEXTURE_2D,this.currentBaseTexture._glTextures[a.id]),this.currentBatchSize>.5*this.size)a.bufferSubData(a.ARRAY_BUFFER,0,this.vertices);else{var b=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);a.bufferSubData(a.ARRAY_BUFFER,0,b)}a.drawElements(a.TRIANGLES,6*this.currentBatchSize,a.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}},b.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},b.WebGLFastSpriteBatch.prototype.start=function(){var a=this.gl;a.activeTexture(a.TEXTURE0),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var b=this.renderSession.projection;a.uniform2f(this.shader.projectionVector,b.x,b.y),a.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var c=4*this.vertSize;a.vertexAttribPointer(this.shader.aVertexPosition,2,a.FLOAT,!1,c,0),a.vertexAttribPointer(this.shader.aPositionCoord,2,a.FLOAT,!1,c,8),a.vertexAttribPointer(this.shader.aScale,2,a.FLOAT,!1,c,16),a.vertexAttribPointer(this.shader.aRotation,1,a.FLOAT,!1,c,24),a.vertexAttribPointer(this.shader.aTextureCoord,2,a.FLOAT,!1,c,28),a.vertexAttribPointer(this.shader.colorAttribute,1,a.FLOAT,!1,c,36)},b.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},b.WebGLFilterManager.prototype.constructor=b.WebGLFilterManager,b.WebGLFilterManager.prototype.setContext=function(a){this.gl=a,this.texturePool=[],this.initShaderBuffers()},b.WebGLFilterManager.prototype.begin=function(a,b){this.renderSession=a,this.defaultShader=a.shaderManager.defaultShader;var c=this.renderSession.projection;this.width=2*c.x,this.height=2*-c.y,this.buffer=b},b.WebGLFilterManager.prototype.pushFilter=function(a){var c=this.gl,d=this.renderSession.projection,e=this.renderSession.offset;a._filterArea=a.target.filterArea||a.target.getBounds(),this.filterStack.push(a);var f=a.filterPasses[0];this.offsetX+=a._filterArea.x,this.offsetY+=a._filterArea.y;var g=this.texturePool.pop();g?g.resize(this.width,this.height):g=new b.FilterTexture(this.gl,this.width,this.height),c.bindTexture(c.TEXTURE_2D,g.texture);var h=a._filterArea,i=f.padding;h.x-=i,h.y-=i,h.width+=2*i,h.height+=2*i,h.x<0&&(h.x=0),h.width>this.width&&(h.width=this.width),h.y<0&&(h.y=0),h.height>this.height&&(h.height=this.height),c.bindFramebuffer(c.FRAMEBUFFER,g.frameBuffer),c.viewport(0,0,h.width,h.height),d.x=h.width/2,d.y=-h.height/2,e.x=-h.x,e.y=-h.y,c.colorMask(!0,!0,!0,!0),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),a._glFilterTexture=g},b.WebGLFilterManager.prototype.popFilter=function(){var a=this.gl,c=this.filterStack.pop(),d=c._filterArea,e=c._glFilterTexture,f=this.renderSession.projection,g=this.renderSession.offset;if(c.filterPasses.length>1){a.viewport(0,0,d.width,d.height),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=d.height,this.vertexArray[2]=d.width,this.vertexArray[3]=d.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=d.width,this.vertexArray[7]=0,a.bufferSubData(a.ARRAY_BUFFER,0,this.vertexArray),a.bindBuffer(a.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=d.width/this.width,this.uvArray[5]=d.height/this.height,this.uvArray[6]=d.width/this.width,this.uvArray[7]=d.height/this.height,a.bufferSubData(a.ARRAY_BUFFER,0,this.uvArray);var h=e,i=this.texturePool.pop();i||(i=new b.FilterTexture(this.gl,this.width,this.height)),i.resize(this.width,this.height),a.bindFramebuffer(a.FRAMEBUFFER,i.frameBuffer),a.clear(a.COLOR_BUFFER_BIT),a.disable(a.BLEND);for(var j=0;j<c.filterPasses.length-1;j++){var k=c.filterPasses[j];a.bindFramebuffer(a.FRAMEBUFFER,i.frameBuffer),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,h.texture),this.applyFilterPass(k,d,d.width,d.height);var l=h;h=i,i=l}a.enable(a.BLEND),e=h,this.texturePool.push(i)}var m=c.filterPasses[c.filterPasses.length-1];this.offsetX-=d.x,this.offsetY-=d.y;var n=this.width,o=this.height,p=0,q=0,r=this.buffer;if(0===this.filterStack.length)a.colorMask(!0,!0,!0,!0);else{var s=this.filterStack[this.filterStack.length-1];d=s._filterArea,n=d.width,o=d.height,p=d.x,q=d.y,r=s._glFilterTexture.frameBuffer}f.x=n/2,f.y=-o/2,g.x=p,g.y=q,d=c._filterArea;var t=d.x-p,u=d.y-q;a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=t,this.vertexArray[1]=u+d.height,this.vertexArray[2]=t+d.width,this.vertexArray[3]=u+d.height,this.vertexArray[4]=t,this.vertexArray[5]=u,this.vertexArray[6]=t+d.width,this.vertexArray[7]=u,a.bufferSubData(a.ARRAY_BUFFER,0,this.vertexArray),a.bindBuffer(a.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=d.width/this.width,this.uvArray[5]=d.height/this.height,this.uvArray[6]=d.width/this.width,this.uvArray[7]=d.height/this.height,a.bufferSubData(a.ARRAY_BUFFER,0,this.uvArray),a.viewport(0,0,n*this.renderSession.resolution,o*this.renderSession.resolution),a.bindFramebuffer(a.FRAMEBUFFER,r),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,e.texture),this.applyFilterPass(m,d,n,o),this.texturePool.push(e),c._glFilterTexture=null},b.WebGLFilterManager.prototype.applyFilterPass=function(a,c,d,e){var f=this.gl,g=a.shaders[f.id];g||(g=new b.PixiShader(f),g.fragmentSrc=a.fragmentSrc,g.uniforms=a.uniforms,g.init(),a.shaders[f.id]=g),this.renderSession.shaderManager.setShader(g),f.uniform2f(g.projectionVector,d/2,-e/2),f.uniform2f(g.offsetVector,0,0),a.uniforms.dimensions&&(a.uniforms.dimensions.value[0]=this.width,a.uniforms.dimensions.value[1]=this.height,a.uniforms.dimensions.value[2]=this.vertexArray[0],a.uniforms.dimensions.value[3]=this.vertexArray[5]),g.syncUniforms(),f.bindBuffer(f.ARRAY_BUFFER,this.vertexBuffer),f.vertexAttribPointer(g.aVertexPosition,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ARRAY_BUFFER,this.uvBuffer),f.vertexAttribPointer(g.aTextureCoord,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ARRAY_BUFFER,this.colorBuffer),f.vertexAttribPointer(g.colorAttribute,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,this.indexBuffer),f.drawElements(f.TRIANGLES,6,f.UNSIGNED_SHORT,0),this.renderSession.drawCount++},b.WebGLFilterManager.prototype.initShaderBuffers=function(){var a=this.gl;this.vertexBuffer=a.createBuffer(),this.uvBuffer=a.createBuffer(),this.colorBuffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),this.vertexArray=new b.Float32Array([0,0,1,0,0,1,1,1]),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bufferData(a.ARRAY_BUFFER,this.vertexArray,a.STATIC_DRAW),this.uvArray=new b.Float32Array([0,0,1,0,0,1,1,1]),a.bindBuffer(a.ARRAY_BUFFER,this.uvBuffer),a.bufferData(a.ARRAY_BUFFER,this.uvArray,a.STATIC_DRAW),this.colorArray=new b.Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),a.bindBuffer(a.ARRAY_BUFFER,this.colorBuffer),a.bufferData(a.ARRAY_BUFFER,this.colorArray,a.STATIC_DRAW),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),a.STATIC_DRAW)},b.WebGLFilterManager.prototype.destroy=function(){var a=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var b=0;b<this.texturePool.length;b++)this.texturePool[b].destroy();this.texturePool=null,a.deleteBuffer(this.vertexBuffer),a.deleteBuffer(this.uvBuffer),a.deleteBuffer(this.colorBuffer),a.deleteBuffer(this.indexBuffer)},b.FilterTexture=function(a,c,d,e){this.gl=a,this.frameBuffer=a.createFramebuffer(),this.texture=a.createTexture(),e=e||b.scaleModes.DEFAULT,a.bindTexture(a.TEXTURE_2D,this.texture),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,e===b.scaleModes.LINEAR?a.LINEAR:a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,e===b.scaleModes.LINEAR?a.LINEAR:a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.bindFramebuffer(a.FRAMEBUFFER,this.frameBuffer),a.bindFramebuffer(a.FRAMEBUFFER,this.frameBuffer),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,this.texture,0),this.renderBuffer=a.createRenderbuffer(),a.bindRenderbuffer(a.RENDERBUFFER,this.renderBuffer),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,this.renderBuffer),this.resize(c,d)},b.FilterTexture.prototype.constructor=b.FilterTexture,b.FilterTexture.prototype.clear=function(){var a=this.gl;a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT)},b.FilterTexture.prototype.resize=function(a,b){if(this.width!==a||this.height!==b){this.width=a,this.height=b;var c=this.gl;c.bindTexture(c.TEXTURE_2D,this.texture),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,a,b,0,c.RGBA,c.UNSIGNED_BYTE,null),c.bindRenderbuffer(c.RENDERBUFFER,this.renderBuffer),c.renderbufferStorage(c.RENDERBUFFER,c.DEPTH_STENCIL,a,b)}},b.FilterTexture.prototype.destroy=function(){var a=this.gl;a.deleteFramebuffer(this.frameBuffer),a.deleteTexture(this.texture),this.frameBuffer=null,this.texture=null},b.CanvasBuffer=function(a,b){this.width=a,this.height=b,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.canvas.width=a,this.canvas.height=b},b.CanvasBuffer.prototype.constructor=b.CanvasBuffer,b.CanvasBuffer.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.width,this.height)},b.CanvasBuffer.prototype.resize=function(a,b){this.width=this.canvas.width=a,this.height=this.canvas.height=b},b.CanvasMaskManager=function(){},b.CanvasMaskManager.prototype.constructor=b.CanvasMaskManager,b.CanvasMaskManager.prototype.pushMask=function(a,c){var d=c.context;d.save();var e=a.alpha,f=a.worldTransform,g=c.resolution;d.setTransform(f.a*g,f.b*g,f.c*g,f.d*g,f.tx*g,f.ty*g),b.CanvasGraphics.renderGraphicsMask(a,d),d.clip(),a.worldAlpha=e},b.CanvasMaskManager.prototype.popMask=function(a){a.context.restore()},b.CanvasTinter=function(){},b.CanvasTinter.getTintedTexture=function(a,c){var d=a.tintedTexture||document.createElement("canvas");return b.CanvasTinter.tintMethod(a.texture,c,d),d},b.CanvasTinter.tintWithMultiply=function(a,b,c){var d=c.getContext("2d"),e=a.crop;(c.width!==e.width||c.height!==e.height)&&(c.width=e.width,c.height=e.height),d.clearRect(0,0,e.width,e.height),d.fillStyle="#"+("00000"+(0|b).toString(16)).substr(-6),d.fillRect(0,0,e.width,e.height),d.globalCompositeOperation="multiply",d.drawImage(a.baseTexture.source,e.x,e.y,e.width,e.height,0,0,e.width,e.height),d.globalCompositeOperation="destination-atop",d.drawImage(a.baseTexture.source,e.x,e.y,e.width,e.height,0,0,e.width,e.height)},b.CanvasTinter.tintWithPerPixel=function(a,c,d){var e=d.getContext("2d"),f=a.crop;d.width=f.width,d.height=f.height,e.globalCompositeOperation="copy",e.drawImage(a.baseTexture.source,f.x,f.y,f.width,f.height,0,0,f.width,f.height);for(var g=b.hex2rgb(c),h=g[0],i=g[1],j=g[2],k=e.getImageData(0,0,f.width,f.height),l=k.data,m=0;m<l.length;m+=4)if(l[m+0]*=h,l[m+1]*=i,l[m+2]*=j,!b.CanvasTinter.canHandleAlpha){var n=l[m+3];l[m+0]/=255/n,l[m+1]/=255/n,l[m+2]/=255/n}e.putImageData(k,0,0)},b.CanvasTinter.checkInverseAlpha=function(){var a=new b.CanvasBuffer(2,1);a.context.fillStyle="rgba(10, 20, 30, 0.5)",a.context.fillRect(0,0,1,1);var c=a.context.getImageData(0,0,1,1);if(null===c)return!1;a.context.putImageData(c,1,0);var d=a.context.getImageData(1,0,1,1);return d.data[0]===c.data[0]&&d.data[1]===c.data[1]&&d.data[2]===c.data[2]&&d.data[3]===c.data[3]},b.CanvasTinter.canHandleAlpha=b.CanvasTinter.checkInverseAlpha(),b.CanvasTinter.canUseMultiply=b.canUseNewCanvasBlendModes(),b.CanvasTinter.tintMethod=b.CanvasTinter.canUseMultiply?b.CanvasTinter.tintWithMultiply:b.CanvasTinter.tintWithPerPixel,b.CanvasRenderer=function(a,c,d){if(d)for(var e in b.defaultRenderOptions)void 0===d[e]&&(d[e]=b.defaultRenderOptions[e]);else d=b.defaultRenderOptions;b.defaultRenderer||(b.defaultRenderer=this),this.type=b.CANVAS_RENDERER,this.resolution=d.resolution,this.clearBeforeRender=d.clearBeforeRender,this.transparent=d.transparent,this.autoResize=d.autoResize||!1,this.width=a||800,this.height=c||600,this.width*=this.resolution,this.height*=this.resolution,this.view=d.view||document.createElement("canvas"),this.context=this.view.getContext("2d",{alpha:this.transparent}),this.refresh=!0,this.view.width=this.width*this.resolution,this.view.height=this.height*this.resolution,this.count=0,this.maskManager=new b.CanvasMaskManager,this.renderSession={context:this.context,maskManager:this.maskManager,scaleMode:null,smoothProperty:null,roundPixels:!1},this.mapBlendModes(),this.resize(a,c),"imageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="imageSmoothingEnabled":"webkitImageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="webkitImageSmoothingEnabled":"mozImageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="mozImageSmoothingEnabled":"oImageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="oImageSmoothingEnabled":"msImageSmoothingEnabled"in this.context&&(this.renderSession.smoothProperty="msImageSmoothingEnabled")
-},b.CanvasRenderer.prototype.constructor=b.CanvasRenderer,b.CanvasRenderer.prototype.render=function(a){a.updateTransform(),this.context.setTransform(1,0,0,1,0,0),this.context.globalAlpha=1,this.renderSession.currentBlendMode=b.blendModes.NORMAL,this.context.globalCompositeOperation=b.blendModesCanvas[b.blendModes.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(this.context.fillStyle="black",this.context.clear()),this.clearBeforeRender&&(this.transparent?this.context.clearRect(0,0,this.width,this.height):(this.context.fillStyle=a.backgroundColorString,this.context.fillRect(0,0,this.width,this.height))),this.renderDisplayObject(a)},b.CanvasRenderer.prototype.destroy=function(a){void 0===a&&(a=!0),a&&this.view.parent&&this.view.parent.removeChild(this.view),this.view=null,this.context=null,this.maskManager=null,this.renderSession=null},b.CanvasRenderer.prototype.resize=function(a,b){this.width=a*this.resolution,this.height=b*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px")},b.CanvasRenderer.prototype.renderDisplayObject=function(a,b,c){this.renderSession.context=b||this.context,this.renderSession.resolution=this.resolution,a._renderCanvas(this.renderSession,c)},b.CanvasRenderer.prototype.mapBlendModes=function(){b.blendModesCanvas||(b.blendModesCanvas=[],b.canUseNewCanvasBlendModes()?(b.blendModesCanvas[b.blendModes.NORMAL]="source-over",b.blendModesCanvas[b.blendModes.ADD]="lighter",b.blendModesCanvas[b.blendModes.MULTIPLY]="multiply",b.blendModesCanvas[b.blendModes.SCREEN]="screen",b.blendModesCanvas[b.blendModes.OVERLAY]="overlay",b.blendModesCanvas[b.blendModes.DARKEN]="darken",b.blendModesCanvas[b.blendModes.LIGHTEN]="lighten",b.blendModesCanvas[b.blendModes.COLOR_DODGE]="color-dodge",b.blendModesCanvas[b.blendModes.COLOR_BURN]="color-burn",b.blendModesCanvas[b.blendModes.HARD_LIGHT]="hard-light",b.blendModesCanvas[b.blendModes.SOFT_LIGHT]="soft-light",b.blendModesCanvas[b.blendModes.DIFFERENCE]="difference",b.blendModesCanvas[b.blendModes.EXCLUSION]="exclusion",b.blendModesCanvas[b.blendModes.HUE]="hue",b.blendModesCanvas[b.blendModes.SATURATION]="saturation",b.blendModesCanvas[b.blendModes.COLOR]="color",b.blendModesCanvas[b.blendModes.LUMINOSITY]="luminosity"):(b.blendModesCanvas[b.blendModes.NORMAL]="source-over",b.blendModesCanvas[b.blendModes.ADD]="lighter",b.blendModesCanvas[b.blendModes.MULTIPLY]="source-over",b.blendModesCanvas[b.blendModes.SCREEN]="source-over",b.blendModesCanvas[b.blendModes.OVERLAY]="source-over",b.blendModesCanvas[b.blendModes.DARKEN]="source-over",b.blendModesCanvas[b.blendModes.LIGHTEN]="source-over",b.blendModesCanvas[b.blendModes.COLOR_DODGE]="source-over",b.blendModesCanvas[b.blendModes.COLOR_BURN]="source-over",b.blendModesCanvas[b.blendModes.HARD_LIGHT]="source-over",b.blendModesCanvas[b.blendModes.SOFT_LIGHT]="source-over",b.blendModesCanvas[b.blendModes.DIFFERENCE]="source-over",b.blendModesCanvas[b.blendModes.EXCLUSION]="source-over",b.blendModesCanvas[b.blendModes.HUE]="source-over",b.blendModesCanvas[b.blendModes.SATURATION]="source-over",b.blendModesCanvas[b.blendModes.COLOR]="source-over",b.blendModesCanvas[b.blendModes.LUMINOSITY]="source-over"))},b.CanvasGraphics=function(){},b.CanvasGraphics.renderGraphics=function(a,c){var d=a.worldAlpha;a.dirty&&(this.updateGraphicsTint(a),a.dirty=!1);for(var e=0;e<a.graphicsData.length;e++){var f=a.graphicsData[e],g=f.shape,h=f._fillTint,i=f._lineTint;if(c.lineWidth=f.lineWidth,f.type===b.Graphics.POLY){c.beginPath();var j=g.points;c.moveTo(j[0],j[1]);for(var k=1;k<j.length/2;k++)c.lineTo(j[2*k],j[2*k+1]);g.closed&&c.lineTo(j[0],j[1]),j[0]===j[j.length-2]&&j[1]===j[j.length-1]&&c.closePath(),f.fill&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke())}else if(f.type===b.Graphics.RECT)(f.fillColor||0===f.fillColor)&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fillRect(g.x,g.y,g.width,g.height)),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.strokeRect(g.x,g.y,g.width,g.height));else if(f.type===b.Graphics.CIRC)c.beginPath(),c.arc(g.x,g.y,g.radius,0,2*Math.PI),c.closePath(),f.fill&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke());else if(f.type===b.Graphics.ELIP){var l=2*g.width,m=2*g.height,n=g.x-l/2,o=g.y-m/2;c.beginPath();var p=.5522848,q=l/2*p,r=m/2*p,s=n+l,t=o+m,u=n+l/2,v=o+m/2;c.moveTo(n,v),c.bezierCurveTo(n,v-r,u-q,o,u,o),c.bezierCurveTo(u+q,o,s,v-r,s,v),c.bezierCurveTo(s,v+r,u+q,t,u,t),c.bezierCurveTo(u-q,t,n,v+r,n,v),c.closePath(),f.fill&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke())}else if(f.type===b.Graphics.RREC){var w=g.x,x=g.y,y=g.width,z=g.height,A=g.radius,B=Math.min(y,z)/2|0;A=A>B?B:A,c.beginPath(),c.moveTo(w,x+A),c.lineTo(w,x+z-A),c.quadraticCurveTo(w,x+z,w+A,x+z),c.lineTo(w+y-A,x+z),c.quadraticCurveTo(w+y,x+z,w+y,x+z-A),c.lineTo(w+y,x+A),c.quadraticCurveTo(w+y,x,w+y-A,x),c.lineTo(w+A,x),c.quadraticCurveTo(w,x,w,x+A),c.closePath(),(f.fillColor||0===f.fillColor)&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke())}}},b.CanvasGraphics.renderGraphicsMask=function(a,c){var d=a.graphicsData.length;if(0!==d){c.beginPath();for(var e=0;d>e;e++){var f=a.graphicsData[e],g=f.shape;if(f.type===b.Graphics.POLY){var h=g.points;c.moveTo(h[0],h[1]);for(var i=1;i<h.length/2;i++)c.lineTo(h[2*i],h[2*i+1]);h[0]===h[h.length-2]&&h[1]===h[h.length-1]&&c.closePath()}else if(f.type===b.Graphics.RECT)c.rect(g.x,g.y,g.width,g.height),c.closePath();else if(f.type===b.Graphics.CIRC)c.arc(g.x,g.y,g.radius,0,2*Math.PI),c.closePath();else if(f.type===b.Graphics.ELIP){var j=2*g.width,k=2*g.height,l=g.x-j/2,m=g.y-k/2,n=.5522848,o=j/2*n,p=k/2*n,q=l+j,r=m+k,s=l+j/2,t=m+k/2;c.moveTo(l,t),c.bezierCurveTo(l,t-p,s-o,m,s,m),c.bezierCurveTo(s+o,m,q,t-p,q,t),c.bezierCurveTo(q,t+p,s+o,r,s,r),c.bezierCurveTo(s-o,r,l,t+p,l,t),c.closePath()}else if(f.type===b.Graphics.RREC){var u=g.x,v=g.y,w=g.width,x=g.height,y=g.radius,z=Math.min(w,x)/2|0;y=y>z?z:y,c.moveTo(u,v+y),c.lineTo(u,v+x-y),c.quadraticCurveTo(u,v+x,u+y,v+x),c.lineTo(u+w-y,v+x),c.quadraticCurveTo(u+w,v+x,u+w,v+x-y),c.lineTo(u+w,v+y),c.quadraticCurveTo(u+w,v,u+w-y,v),c.lineTo(u+y,v),c.quadraticCurveTo(u,v,u,v+y),c.closePath()}}}},b.CanvasGraphics.updateGraphicsTint=function(a){if(16777215!==a.tint)for(var b=(a.tint>>16&255)/255,c=(a.tint>>8&255)/255,d=(255&a.tint)/255,e=0;e<a.graphicsData.length;e++){var f=a.graphicsData[e],g=0|f.fillColor,h=0|f.lineColor;f._fillTint=((g>>16&255)/255*b*255<<16)+((g>>8&255)/255*c*255<<8)+(255&g)/255*d*255,f._lineTint=((h>>16&255)/255*b*255<<16)+((h>>8&255)/255*c*255<<8)+(255&h)/255*d*255}},b.BaseTextureCache={},b.BaseTextureCacheIdGenerator=0,b.BaseTexture=function(a,c){this.resolution=1,this.width=100,this.height=100,this.scaleMode=c||b.scaleModes.DEFAULT,this.hasLoaded=!1,this.source=a,this._UID=b._UID++,this.premultipliedAlpha=!0,this._glTextures=[],this.mipmap=!1,this._dirty=[!0,!0,!0,!0],a&&((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height&&(this.hasLoaded=!0,this.width=this.source.naturalWidth||this.source.width,this.height=this.source.naturalHeight||this.source.height,this.dirty()),this.imageUrl=null,this._powerOf2=!1)},b.BaseTexture.prototype.constructor=b.BaseTexture,b.BaseTexture.prototype.forceLoaded=function(a,b){this.hasLoaded=!0,this.width=a,this.height=b,this.dirty()},b.BaseTexture.prototype.destroy=function(){this.imageUrl?(delete b.BaseTextureCache[this.imageUrl],delete b.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")):this.source&&this.source._pixiId&&delete b.BaseTextureCache[this.source._pixiId],this.source=null,this.unloadFromGPU()},b.BaseTexture.prototype.updateSourceImage=function(a){this.hasLoaded=!1,this.source.src=null,this.source.src=a},b.BaseTexture.prototype.dirty=function(){for(var a=0;a<this._glTextures.length;a++)this._dirty[a]=!0},b.BaseTexture.prototype.unloadFromGPU=function(){this.dirty();for(var a=this._glTextures.length-1;a>=0;a--){var c=this._glTextures[a],d=b.glContexts[a];d&&c&&d.deleteTexture(c)}this._glTextures.length=0,this.dirty()},b.BaseTexture.fromImage=function(a,c,d){var e=b.BaseTextureCache[a];if(void 0===c&&-1===a.indexOf("data:")&&(c=!0),!e){var f=new Image;c&&(f.crossOrigin=""),f.src=a,e=new b.BaseTexture(f,d),e.imageUrl=a,b.BaseTextureCache[a]=e,-1!==a.indexOf(b.RETINA_PREFIX+".")&&(e.resolution=2)}return e},b.BaseTexture.fromCanvas=function(a,c){a._pixiId||(a._pixiId="canvas_"+b.TextureCacheIdGenerator++),0===a.width&&(a.width=1),0===a.height&&(a.height=1);var d=b.BaseTextureCache[a._pixiId];return d||(d=new b.BaseTexture(a,c),b.BaseTextureCache[a._pixiId]=d),d},b.TextureCache={},b.FrameCache={},b.TextureSilentFail=!1,b.TextureCacheIdGenerator=0,b.Texture=function(a,c,d,e){this.noFrame=!1,c||(this.noFrame=!0,c=new b.Rectangle(0,0,1,1)),a instanceof b.Texture&&(a=a.baseTexture),this.baseTexture=a,this.frame=c,this.trim=e,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=d||new b.Rectangle(0,0,1,1),a.hasLoaded&&(this.noFrame&&(c=new b.Rectangle(0,0,a.width,a.height)),this.setFrame(c))},b.Texture.prototype.constructor=b.Texture,b.Texture.prototype.onBaseTextureLoaded=function(){var a=this.baseTexture;this.noFrame&&(this.frame=new b.Rectangle(0,0,a.width,a.height)),this.setFrame(this.frame)},b.Texture.prototype.destroy=function(a){a&&this.baseTexture.destroy(),this.valid=!1},b.Texture.prototype.setFrame=function(a){if(this.noFrame=!1,this.frame=a,this.width=a.width,this.height=a.height,this.crop.x=a.x,this.crop.y=a.y,this.crop.width=a.width,this.crop.height=a.height,!this.trim&&(a.x+a.width>this.baseTexture.width||a.y+a.height>this.baseTexture.height)){if(!b.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);return void(this.valid=!1)}this.valid=a&&a.width&&a.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs()},b.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new b.TextureUvs);var a=this.crop,c=this.baseTexture.width,d=this.baseTexture.height;this._uvs.x0=a.x/c,this._uvs.y0=a.y/d,this._uvs.x1=(a.x+a.width)/c,this._uvs.y1=a.y/d,this._uvs.x2=(a.x+a.width)/c,this._uvs.y2=(a.y+a.height)/d,this._uvs.x3=a.x/c,this._uvs.y3=(a.y+a.height)/d},b.Texture.fromImage=function(a,c,d){var e=b.TextureCache[a];return e||(e=new b.Texture(b.BaseTexture.fromImage(a,c,d)),b.TextureCache[a]=e),e},b.Texture.fromFrame=function(a){var c=b.TextureCache[a];if(!c)throw new Error('The frameId "'+a+'" does not exist in the texture cache ');return c},b.Texture.fromCanvas=function(a,c){var d=b.BaseTexture.fromCanvas(a,c);return new b.Texture(d)},b.Texture.addTextureToCache=function(a,c){b.TextureCache[c]=a},b.Texture.removeTextureFromCache=function(a){var c=b.TextureCache[a];return delete b.TextureCache[a],delete b.BaseTextureCache[a],c},b.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},b.RenderTexture=function(a,c,d,e,f){if(this.width=a||100,this.height=c||100,this.resolution=f||1,this.frame=new b.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=new b.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.baseTexture=new b.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=e||b.scaleModes.DEFAULT,this.baseTexture.hasLoaded=!0,b.Texture.call(this,this.baseTexture,new b.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution)),this.renderer=d||b.defaultRenderer,this.renderer.type===b.WEBGL_RENDERER){var g=this.renderer.gl;this.baseTexture._dirty[g.id]=!1,this.textureBuffer=new b.FilterTexture(g,this.width,this.height,this.baseTexture.scaleMode),this.baseTexture._glTextures[g.id]=this.textureBuffer.texture,this.render=this.renderWebGL,this.projection=new b.Point(.5*this.width,.5*-this.height)}else this.render=this.renderCanvas,this.textureBuffer=new b.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new Phaser.Matrix,this._updateUvs()},b.RenderTexture.prototype=Object.create(b.Texture.prototype),b.RenderTexture.prototype.constructor=b.RenderTexture,b.RenderTexture.prototype.resize=function(a,c,d){(a!==this.width||c!==this.height)&&(this.valid=a>0&&c>0,this.width=a,this.height=c,this.frame.width=this.crop.width=a*this.resolution,this.frame.height=this.crop.height=c*this.resolution,d&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===b.WEBGL_RENDERER&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},b.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===b.WEBGL_RENDERER&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},b.RenderTexture.prototype.renderWebGL=function(a,b,c){if(this.valid&&0!==a.alpha){var d=a.worldTransform;d.identity(),d.translate(0,2*this.projection.y),b&&d.append(b),d.scale(1,-1);for(var e=0;e<a.children.length;e++)a.children[e].updateTransform();var f=this.renderer.gl;f.viewport(0,0,this.width*this.resolution,this.height*this.resolution),f.bindFramebuffer(f.FRAMEBUFFER,this.textureBuffer.frameBuffer),c&&this.textureBuffer.clear(),this.renderer.spriteBatch.dirty=!0,this.renderer.renderDisplayObject(a,this.projection,this.textureBuffer.frameBuffer,b),this.renderer.spriteBatch.dirty=!0}},b.RenderTexture.prototype.renderCanvas=function(a,b,c){if(this.valid&&0!==a.alpha){for(var d=0;d<a.children.length;d++)a.children[d].updateTransform();c&&this.textureBuffer.clear();var e=this.renderer.resolution;this.renderer.resolution=this.resolution,this.renderer.renderDisplayObject(a,this.textureBuffer.context,b),this.renderer.resolution=e}},b.RenderTexture.prototype.getImage=function(){var a=new Image;return a.src=this.getBase64(),a},b.RenderTexture.prototype.getBase64=function(){return this.getCanvas().toDataURL()},b.RenderTexture.prototype.getCanvas=function(){if(this.renderer.type===b.WEBGL_RENDERER){var a=this.renderer.gl,c=this.textureBuffer.width,d=this.textureBuffer.height,e=new Uint8Array(4*c*d);a.bindFramebuffer(a.FRAMEBUFFER,this.textureBuffer.frameBuffer),a.readPixels(0,0,c,d,a.RGBA,a.UNSIGNED_BYTE,e),a.bindFramebuffer(a.FRAMEBUFFER,null);var f=new b.CanvasBuffer(c,d),g=f.context.getImageData(0,0,c,d);return g.data.set(e),f.context.putImageData(g,0,0),f.canvas}return this.textureBuffer.canvas},b.AbstractFilter=function(a,b){this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.uniforms=b||{},this.fragmentSrc=a||[]},b.AbstractFilter.prototype.constructor=b.AbstractFilter,b.AbstractFilter.prototype.syncUniforms=function(){for(var a=0,b=this.shaders.length;b>a;a++)this.shaders[a].dirty=!0},b.Strip=function(a){b.DisplayObjectContainer.call(this),this.texture=a,this.uvs=new b.Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new b.Float32Array([0,0,100,0,100,100,0,100]),this.colors=new b.Float32Array([1,1,1,1]),this.indices=new b.Uint16Array([0,1,2,3]),this.dirty=!0,this.blendMode=b.blendModes.NORMAL,this.canvasPadding=0,this.drawMode=b.Strip.DrawModes.TRIANGLE_STRIP},b.Strip.prototype=Object.create(b.DisplayObjectContainer.prototype),b.Strip.prototype.constructor=b.Strip,b.Strip.prototype._renderWebGL=function(a){!this.visible||this.alpha<=0||(a.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(a),a.shaderManager.setShader(a.shaderManager.stripShader),this._renderStrip(a),a.spriteBatch.start())},b.Strip.prototype._initWebGL=function(a){var b=a.gl;this._vertexBuffer=b.createBuffer(),this._indexBuffer=b.createBuffer(),this._uvBuffer=b.createBuffer(),this._colorBuffer=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,this._vertexBuffer),b.bufferData(b.ARRAY_BUFFER,this.vertices,b.DYNAMIC_DRAW),b.bindBuffer(b.ARRAY_BUFFER,this._uvBuffer),b.bufferData(b.ARRAY_BUFFER,this.uvs,b.STATIC_DRAW),b.bindBuffer(b.ARRAY_BUFFER,this._colorBuffer),b.bufferData(b.ARRAY_BUFFER,this.colors,b.STATIC_DRAW),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,this._indexBuffer),b.bufferData(b.ELEMENT_ARRAY_BUFFER,this.indices,b.STATIC_DRAW)},b.Strip.prototype._renderStrip=function(a){var c=a.gl,d=a.projection,e=a.offset,f=a.shaderManager.stripShader,g=this.drawMode===b.Strip.DrawModes.TRIANGLE_STRIP?c.TRIANGLE_STRIP:c.TRIANGLES;a.blendModeManager.setBlendMode(this.blendMode),c.uniformMatrix3fv(f.translationMatrix,!1,this.worldTransform.toArray(!0)),c.uniform2f(f.projectionVector,d.x,-d.y),c.uniform2f(f.offsetVector,-e.x,-e.y),c.uniform1f(f.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,c.bindBuffer(c.ARRAY_BUFFER,this._vertexBuffer),c.bufferData(c.ARRAY_BUFFER,this.vertices,c.STATIC_DRAW),c.vertexAttribPointer(f.aVertexPosition,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this._uvBuffer),c.bufferData(c.ARRAY_BUFFER,this.uvs,c.STATIC_DRAW),c.vertexAttribPointer(f.aTextureCoord,2,c.FLOAT,!1,0,0),c.activeTexture(c.TEXTURE0),this.texture.baseTexture._dirty[c.id]?a.renderer.updateTexture(this.texture.baseTexture):c.bindTexture(c.TEXTURE_2D,this.texture.baseTexture._glTextures[c.id]),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this._indexBuffer),c.bufferData(c.ELEMENT_ARRAY_BUFFER,this.indices,c.STATIC_DRAW)):(c.bindBuffer(c.ARRAY_BUFFER,this._vertexBuffer),c.bufferSubData(c.ARRAY_BUFFER,0,this.vertices),c.vertexAttribPointer(f.aVertexPosition,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this._uvBuffer),c.vertexAttribPointer(f.aTextureCoord,2,c.FLOAT,!1,0,0),c.activeTexture(c.TEXTURE0),this.texture.baseTexture._dirty[c.id]?a.renderer.updateTexture(this.texture.baseTexture):c.bindTexture(c.TEXTURE_2D,this.texture.baseTexture._glTextures[c.id]),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),c.drawElements(g,this.indices.length,c.UNSIGNED_SHORT,0)},b.Strip.prototype._renderCanvas=function(a){var c=a.context,d=this.worldTransform;a.roundPixels?c.setTransform(d.a,d.b,d.c,d.d,0|d.tx,0|d.ty):c.setTransform(d.a,d.b,d.c,d.d,d.tx,d.ty),this.drawMode===b.Strip.DrawModes.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(c):this._renderCanvasTriangles(c)},b.Strip.prototype._renderCanvasTriangleStrip=function(a){var b=this.vertices,c=this.uvs,d=b.length/2;this.count++;for(var e=0;d-2>e;e++){var f=2*e;this._renderCanvasDrawTriangle(a,b,c,f,f+2,f+4)}},b.Strip.prototype._renderCanvasTriangles=function(a){var b=this.vertices,c=this.uvs,d=this.indices,e=d.length;this.count++;for(var f=0;e>f;f+=3){var g=2*d[f],h=2*d[f+1],i=2*d[f+2];this._renderCanvasDrawTriangle(a,b,c,g,h,i)}},b.Strip.prototype._renderCanvasDrawTriangle=function(a,b,c,d,e,f){var g=this.texture.baseTexture.source,h=this.texture.width,i=this.texture.height,j=b[d],k=b[e],l=b[f],m=b[d+1],n=b[e+1],o=b[f+1],p=c[d]*h,q=c[e]*h,r=c[f]*h,s=c[d+1]*i,t=c[e+1]*i,u=c[f+1]*i;if(this.canvasPadding>0){var v=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,x=(j+k+l)/3,y=(m+n+o)/3,z=j-x,A=m-y,B=Math.sqrt(z*z+A*A);j=x+z/B*(B+v),m=y+A/B*(B+w),z=k-x,A=n-y,B=Math.sqrt(z*z+A*A),k=x+z/B*(B+v),n=y+A/B*(B+w),z=l-x,A=o-y,B=Math.sqrt(z*z+A*A),l=x+z/B*(B+v),o=y+A/B*(B+w)}a.save(),a.beginPath(),a.moveTo(j,m),a.lineTo(k,n),a.lineTo(l,o),a.closePath(),a.clip();var C=p*t+s*r+q*u-t*r-s*q-p*u,D=j*t+s*l+k*u-t*l-s*k-j*u,E=p*k+j*r+q*l-k*r-j*q-p*l,F=p*t*l+s*k*r+j*q*u-j*t*r-s*q*l-p*k*u,G=m*t+s*o+n*u-t*o-s*n-m*u,H=p*n+m*r+q*o-n*r-m*q-p*o,I=p*t*o+s*n*r+m*q*u-m*t*r-s*q*o-p*n*u;a.transform(D/C,G/C,E/C,H/C,F/C,I/C),a.drawImage(g,0,0),a.restore()},b.Strip.prototype.renderStripFlat=function(a){var b=this.context,c=a.vertices,d=c.length/2;this.count++,b.beginPath();for(var e=1;d-2>e;e++){var f=2*e,g=c[f],h=c[f+2],i=c[f+4],j=c[f+1],k=c[f+3],l=c[f+5];b.moveTo(g,j),b.lineTo(h,k),b.lineTo(i,l)}b.fillStyle="#FF0000",b.fill(),b.closePath()},b.Strip.prototype.onTextureUpdate=function(){this.updateFrame=!0},b.Strip.prototype.getBounds=function(a){for(var c=a||this.worldTransform,d=c.a,e=c.b,f=c.c,g=c.d,h=c.tx,i=c.ty,j=-1/0,k=-1/0,l=1/0,m=1/0,n=this.vertices,o=0,p=n.length;p>o;o+=2){var q=n[o],r=n[o+1],s=d*q+f*r+h,t=g*r+e*q+i;l=l>s?s:l,m=m>t?t:m,j=s>j?s:j,k=t>k?t:k}if(l===-1/0||1/0===k)return b.EmptyRectangle;var u=this._bounds;return u.x=l,u.width=j-l,u.y=m,u.height=k-m,this._currentBounds=u,u},b.Strip.DrawModes={TRIANGLE_STRIP:0,TRIANGLES:1},b.Rope=function(a,c){b.Strip.call(this,a),this.points=c,this.vertices=new b.Float32Array(4*c.length),this.uvs=new b.Float32Array(4*c.length),this.colors=new b.Float32Array(2*c.length),this.indices=new b.Uint16Array(2*c.length),this.refresh()},b.Rope.prototype=Object.create(b.Strip.prototype),b.Rope.prototype.constructor=b.Rope,b.Rope.prototype.refresh=function(){var a=this.points;if(!(a.length<1)){var b=this.uvs,c=a[0],d=this.indices,e=this.colors;this.count-=.2,b[0]=0,b[1]=0,b[2]=0,b[3]=1,e[0]=1,e[1]=1,d[0]=0,d[1]=1;for(var f,g,h,i=a.length,j=1;i>j;j++)f=a[j],g=4*j,h=j/(i-1),j%2?(b[g]=h,b[g+1]=0,b[g+2]=h,b[g+3]=1):(b[g]=h,b[g+1]=0,b[g+2]=h,b[g+3]=1),g=2*j,e[g]=1,e[g+1]=1,g=2*j,d[g]=g,d[g+1]=g+1,c=f}},b.Rope.prototype.updateTransform=function(){var a=this.points;if(!(a.length<1)){var c,d=a[0],e={x:0,y:0};this.count-=.2;for(var f,g,h,i,j,k=this.vertices,l=a.length,m=0;l>m;m++)f=a[m],g=4*m,c=m<a.length-1?a[m+1]:f,e.y=-(c.x-d.x),e.x=c.y-d.y,h=10*(1-m/(l-1)),h>1&&(h=1),i=Math.sqrt(e.x*e.x+e.y*e.y),j=this.texture.height/2,e.x/=i,e.y/=i,e.x*=j,e.y*=j,k[g]=f.x+e.x,k[g+1]=f.y+e.y,k[g+2]=f.x-e.x,k[g+3]=f.y-e.y,d=f;b.DisplayObjectContainer.prototype.updateTransform.call(this)}},b.Rope.prototype.setTexture=function(a){this.texture=a},b.TilingSprite=function(a,c,d){b.Sprite.call(this,a),this._width=c||128,this._height=d||128,this.tileScale=new b.Point(1,1),this.tileScaleOffset=new b.Point(1,1),this.tilePosition=new b.Point,this.renderable=!0,this.tint=16777215,this.textureDebug=!1,this.blendMode=b.blendModes.NORMAL,this.canvasBuffer=null,this.tilingTexture=null,this.tilePattern=null,this.refreshTexture=!0,this.frameWidth=0,this.frameHeight=0},b.TilingSprite.prototype=Object.create(b.Sprite.prototype),b.TilingSprite.prototype.constructor=b.TilingSprite,b.TilingSprite.prototype.setTexture=function(a){this.texture!==a&&(this.texture=a,this.refreshTexture=!0,this.cachedTint=16777215)},b.TilingSprite.prototype._renderWebGL=function(a){if(this.visible!==!1&&0!==this.alpha){if(this._mask&&(a.spriteBatch.stop(),a.maskManager.pushMask(this.mask,a),a.spriteBatch.start()),this._filters&&(a.spriteBatch.flush(),a.filterManager.pushFilter(this._filterBlock)),this.refreshTexture){if(this.generateTilingTexture(!0),!this.tilingTexture)return;this.tilingTexture.needsUpdate&&(a.renderer.updateTexture(this.tilingTexture.baseTexture),this.tilingTexture.needsUpdate=!1)}a.spriteBatch.renderTilingSprite(this);for(var b=0;b<this.children.length;b++)this.children[b]._renderWebGL(a);a.spriteBatch.stop(),this._filters&&a.filterManager.popFilter(),this._mask&&a.maskManager.popMask(this._mask,a),a.spriteBatch.start()}},b.TilingSprite.prototype._renderCanvas=function(a){if(this.visible!==!1&&0!==this.alpha){var c=a.context;this._mask&&a.maskManager.pushMask(this._mask,a),c.globalAlpha=this.worldAlpha;var d=this.worldTransform,e=a.resolution;if(c.setTransform(d.a*e,d.b*e,d.c*e,d.d*e,d.tx*e,d.ty*e),this.refreshTexture){if(this.generateTilingTexture(!1),!this.tilingTexture)return;this.tilePattern=c.createPattern(this.tilingTexture.baseTexture.source,"repeat")}var f=a.currentBlendMode;this.blendMode!==a.currentBlendMode&&(a.currentBlendMode=this.blendMode,c.globalCompositeOperation=b.blendModesCanvas[a.currentBlendMode]);var g=this.tilePosition,h=this.tileScale;g.x%=this.tilingTexture.baseTexture.width,g.y%=this.tilingTexture.baseTexture.height,c.scale(h.x,h.y),c.translate(g.x+this.anchor.x*-this._width,g.y+this.anchor.y*-this._height),c.fillStyle=this.tilePattern;var i=-g.x,j=-g.y,k=this._width/h.x,l=this._height/h.y;a.roundPixels,c.fillRect(i,j,k,l),c.scale(1/h.x,1/h.y),c.translate(-g.x+this.anchor.x*this._width,-g.y+this.anchor.y*this._height),this._mask&&a.maskManager.popMask(a);for(var m=0;m<this.children.length;m++)this.children[m]._renderCanvas(a);f!==this.blendMode&&(a.currentBlendMode=f,c.globalCompositeOperation=b.blendModesCanvas[f])}},b.TilingSprite.prototype.onTextureUpdate=function(){},b.TilingSprite.prototype.generateTilingTexture=function(a){if(this.texture.baseTexture.hasLoaded){var c=this.texture,d=c.frame,e=this._frame.sourceSizeW,f=this._frame.sourceSizeH,g=0,h=0;this._frame.trimmed&&(g=this._frame.spriteSourceSizeX,h=this._frame.spriteSourceSizeY),a&&(e=b.getNextPowerOfTwo(e),f=b.getNextPowerOfTwo(f)),this.canvasBuffer?(this.canvasBuffer.resize(e,f),this.tilingTexture.baseTexture.width=e,this.tilingTexture.baseTexture.height=f,this.tilingTexture.needsUpdate=!0):(this.canvasBuffer=new b.CanvasBuffer(e,f),this.tilingTexture=b.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture=b.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture.isTiling=!0,this.tilingTexture.needsUpdate=!0),this.textureDebug&&(this.canvasBuffer.context.strokeStyle="#00ff00",this.canvasBuffer.context.strokeRect(0,0,e,f));var i=c.crop.width,j=c.crop.height;(i!==e||j!==f)&&(i=e,j=f),this.canvasBuffer.context.drawImage(c.baseTexture.source,c.crop.x,c.crop.y,c.crop.width,c.crop.height,g,h,i,j),this.tileScaleOffset.x=d.width/e,this.tileScaleOffset.y=d.height/f,this.refreshTexture=!1,this.tilingTexture.baseTexture._powerOf2=!0}},b.TilingSprite.prototype.getBounds=function(){var a=this._width,b=this._height,c=a*(1-this.anchor.x),d=a*-this.anchor.x,e=b*(1-this.anchor.y),f=b*-this.anchor.y,g=this.worldTransform,h=g.a,i=g.b,j=g.c,k=g.d,l=g.tx,m=g.ty,n=h*d+j*f+l,o=k*f+i*d+m,p=h*c+j*f+l,q=k*f+i*c+m,r=h*c+j*e+l,s=k*e+i*c+m,t=h*d+j*e+l,u=k*e+i*d+m,v=-1/0,w=-1/0,x=1/0,y=1/0;x=x>n?n:x,x=x>p?p:x,x=x>r?r:x,x=x>t?t:x,y=y>o?o:y,y=y>q?q:y,y=y>s?s:y,y=y>u?u:y,v=n>v?n:v,v=p>v?p:v,v=r>v?r:v,v=t>v?t:v,w=o>w?o:w,w=q>w?q:w,w=s>w?s:w,w=u>w?u:w;var z=this._bounds;return z.x=x,z.width=v-x,z.y=y,z.height=w-y,this._currentBounds=z,z},b.TilingSprite.prototype.destroy=function(){b.Sprite.prototype.destroy.call(this),this.tileScale=null,this.tileScaleOffset=null,this.tilePosition=null,this.tilingTexture&&(this.tilingTexture.destroy(!0),this.tilingTexture=null)},Object.defineProperty(b.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(a){this._width=a}}),Object.defineProperty(b.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(a){this._height=a}}),"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=b),exports.PIXI=b):"undefined"!=typeof define&&define.amd?define("PIXI",function(){return a.PIXI=b}()):a.PIXI=b,b}.call(this),function(){function a(a,b){this._scaleFactor=a,this._deltaMode=b,this.originalEvent=null}var b=this,c=c||{VERSION:"2.4.2",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,blendModes:{NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{}};if(Math.trunc||(Math.trunc=function(a){return 0>a?Math.ceil(a):Math.floor(a)}),Function.prototype.bind||(Function.prototype.bind=function(){var a=Array.prototype.slice;return function(b){function c(){var f=e.concat(a.call(arguments));d.apply(this instanceof c?this:b,f)}var d=this,e=a.call(arguments,1);if("function"!=typeof d)throw new TypeError;return c.prototype=function f(a){return a&&(f.prototype=a),this instanceof f?void 0:new f}(d.prototype),c}}()),Array.isArray||(Array.isArray=function(a){return"[object Array]"==Object.prototype.toString.call(a)}),Array.prototype.forEach||(Array.prototype.forEach=function(a){"use strict";if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=arguments.length>=2?arguments[1]:void 0,e=0;c>e;e++)e in b&&a.call(d,b[e],e,b)}),"function"!=typeof window.Uint32Array&&"object"!=typeof window.Uint32Array){var d=function(a){var b=new Array;window[a]=function(a){if("number"==typeof a){Array.call(this,a),this.length=a;for(var b=0;b<this.length;b++)this[b]=0}else{Array.call(this,a.length),this.length=a.length;for(var b=0;b<this.length;b++)this[b]=a[b]}},window[a].prototype=b,window[a].constructor=window[a]};d("Uint32Array"),d("Int16Array")}window.console||(window.console={},window.console.log=window.console.assert=function(){},window.console.warn=window.console.assert=function(){}),c.Utils={getProperty:function(a,b){for(var c=b.split("."),d=c.pop(),e=c.length,f=1,g=c[0];e>f&&(a=a[g]);)g=c[f],f++;return a?a[d]:null},setProperty:function(a,b,c){for(var d=b.split("."),e=d.pop(),f=d.length,g=1,h=d[0];f>g&&(a=a[h]);)h=d[g],g++;return a&&(a[e]=c),a},chanceRoll:function(a){return void 0===a&&(a=50),a>0&&100*Math.random()<=a},randomChoice:function(a,b){return Math.random()<.5?a:b},parseDimension:function(a,b){var c=0,d=0;return"string"==typeof a?"%"===a.substr(-1)?(c=parseInt(a,10)/100,d=0===b?window.innerWidth*c:window.innerHeight*c):d=parseInt(a,10):d=a,d},pad:function(a,b,c,d){if(void 0===b)var b=0;if(void 0===c)var c=" ";if(void 0===d)var d=3;var e=0;if(b+1>=a.length)switch(d){case 1:a=new Array(b+1-a.length).join(c)+a;break;case 3:var f=Math.ceil((e=b-a.length)/2),g=e-f;a=new Array(g+1).join(c)+a+new Array(f+1).join(c);break;default:a+=new Array(b+1-a.length).join(c)}return a},isPlainObject:function(a){if("object"!=typeof a||a.nodeType||a===a.window)return!1;try{if(a.constructor&&!{}.hasOwnProperty.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},extend:function(){var a,b,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;for("boolean"==typeof h&&(k=h,h=arguments[1]||{},i=2),j===i&&(h=this,--i);j>i;i++)if(null!=(a=arguments[i]))for(b in a)d=h[b],e=a[b],h!==e&&(k&&e&&(c.Utils.isPlainObject(e)||(f=Array.isArray(e)))?(f?(f=!1,g=d&&Array.isArray(d)?d:[]):g=d&&c.Utils.isPlainObject(d)?d:{},h[b]=c.Utils.extend(k,g,e)):void 0!==e&&(h[b]=e));return h},mixinPrototype:function(a,b,c){void 0===c&&(c=!1);for(var d=Object.keys(b),e=0;e<d.length;e++){var f=d[e],g=b[f];!c&&f in a||(!g||"function"!=typeof g.get&&"function"!=typeof g.set?a[f]=g:"function"==typeof g.clone?a[f]=g.clone():Object.defineProperty(a,f,g))}},mixin:function(a,b){if(!a||"object"!=typeof a)return b;for(var d in a){var e=a[d];if(!e.childNodes&&!e.cloneNode){var f=typeof a[d];b[d]=a[d]&&"object"===f?typeof b[d]===f?c.Utils.mixin(a[d],b[d]):c.Utils.mixin(a[d],new e.constructor):a[d]
-}}return b}},c.Circle=function(a,b,d){a=a||0,b=b||0,d=d||0,this.x=a,this.y=b,this._diameter=d,this._radius=0,d>0&&(this._radius=.5*d),this.type=c.CIRCLE},c.Circle.prototype={circumference:function(){return 2*Math.PI*this._radius},random:function(a){void 0===a&&(a=new c.Point);var b=2*Math.PI*Math.random(),d=Math.random()+Math.random(),e=d>1?2-d:d,f=e*Math.cos(b),g=e*Math.sin(b);return a.x=this.x+f*this.radius,a.y=this.y+g*this.radius,a},getBounds:function(){return new c.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(a,b,c){return this.x=a,this.y=b,this._diameter=c,this._radius=.5*c,this},copyFrom:function(a){return this.setTo(a.x,a.y,a.diameter)},copyTo:function(a){return a.x=this.x,a.y=this.y,a.diameter=this._diameter,a},distance:function(a,b){var d=c.Math.distance(this.x,this.y,a.x,a.y);return b?Math.round(d):d},clone:function(a){return void 0===a||null===a?a=new c.Circle(this.x,this.y,this.diameter):a.setTo(this.x,this.y,this.diameter),a},contains:function(a,b){return c.Circle.contains(this,a,b)},circumferencePoint:function(a,b,d){return c.Circle.circumferencePoint(this,a,b,d)},offset:function(a,b){return this.x+=a,this.y+=b,this},offsetPoint:function(a){return this.offset(a.x,a.y)},toString:function(){return"[{Phaser.Circle (x="+this.x+" y="+this.y+" diameter="+this.diameter+" radius="+this.radius+")}]"}},c.Circle.prototype.constructor=c.Circle,Object.defineProperty(c.Circle.prototype,"diameter",{get:function(){return this._diameter},set:function(a){a>0&&(this._diameter=a,this._radius=.5*a)}}),Object.defineProperty(c.Circle.prototype,"radius",{get:function(){return this._radius},set:function(a){a>0&&(this._radius=a,this._diameter=2*a)}}),Object.defineProperty(c.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(a){a>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-a}}),Object.defineProperty(c.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(a){a<this.x?(this._radius=0,this._diameter=0):this.radius=a-this.x}}),Object.defineProperty(c.Circle.prototype,"top",{get:function(){return this.y-this._radius},set:function(a){a>this.y?(this._radius=0,this._diameter=0):this.radius=this.y-a}}),Object.defineProperty(c.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(a){a<this.y?(this._radius=0,this._diameter=0):this.radius=a-this.y}}),Object.defineProperty(c.Circle.prototype,"area",{get:function(){return this._radius>0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(c.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(a){a===!0&&this.setTo(0,0,0)}}),c.Circle.contains=function(a,b,c){if(a.radius>0&&b>=a.left&&b<=a.right&&c>=a.top&&c<=a.bottom){var d=(a.x-b)*(a.x-b),e=(a.y-c)*(a.y-c);return d+e<=a.radius*a.radius}return!1},c.Circle.equals=function(a,b){return a.x==b.x&&a.y==b.y&&a.diameter==b.diameter},c.Circle.intersects=function(a,b){return c.Math.distance(a.x,a.y,b.x,b.y)<=a.radius+b.radius},c.Circle.circumferencePoint=function(a,b,d,e){return void 0===d&&(d=!1),void 0===e&&(e=new c.Point),d===!0&&(b=c.Math.degToRad(b)),e.x=a.x+a.radius*Math.cos(b),e.y=a.y+a.radius*Math.sin(b),e},c.Circle.intersectsRectangle=function(a,b){var c=Math.abs(a.x-b.x-b.halfWidth),d=b.halfWidth+a.radius;if(c>d)return!1;var e=Math.abs(a.y-b.y-b.halfHeight),f=b.halfHeight+a.radius;if(e>f)return!1;if(c<=b.halfWidth||e<=b.halfHeight)return!0;var g=c-b.halfWidth,h=e-b.halfHeight,i=g*g,j=h*h,k=a.radius*a.radius;return k>=i+j},PIXI.Circle=c.Circle,c.Ellipse=function(a,b,d,e){a=a||0,b=b||0,d=d||0,e=e||0,this.x=a,this.y=b,this.width=d,this.height=e,this.type=c.ELLIPSE},c.Ellipse.prototype={setTo:function(a,b,c,d){return this.x=a,this.y=b,this.width=c,this.height=d,this},getBounds:function(){return new c.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(a){return this.setTo(a.x,a.y,a.width,a.height)},copyTo:function(a){return a.x=this.x,a.y=this.y,a.width=this.width,a.height=this.height,a},clone:function(a){return void 0===a||null===a?a=new c.Ellipse(this.x,this.y,this.width,this.height):a.setTo(this.x,this.y,this.width,this.height),a},contains:function(a,b){return c.Ellipse.contains(this,a,b)},random:function(a){void 0===a&&(a=new c.Point);var b=Math.random()*Math.PI*2,d=Math.random();return a.x=Math.sqrt(d)*Math.cos(b),a.y=Math.sqrt(d)*Math.sin(b),a.x=this.x+a.x*this.width/2,a.y=this.y+a.y*this.height/2,a},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},c.Ellipse.prototype.constructor=c.Ellipse,Object.defineProperty(c.Ellipse.prototype,"left",{get:function(){return this.x},set:function(a){this.x=a}}),Object.defineProperty(c.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(a){this.width=a<this.x?0:a-this.x}}),Object.defineProperty(c.Ellipse.prototype,"top",{get:function(){return this.y},set:function(a){this.y=a}}),Object.defineProperty(c.Ellipse.prototype,"bottom",{get:function(){return this.y+this.height},set:function(a){this.height=a<this.y?0:a-this.y}}),Object.defineProperty(c.Ellipse.prototype,"empty",{get:function(){return 0===this.width||0===this.height},set:function(a){a===!0&&this.setTo(0,0,0,0)}}),c.Ellipse.contains=function(a,b,c){if(a.width<=0||a.height<=0)return!1;var d=(b-a.x)/a.width-.5,e=(c-a.y)/a.height-.5;return d*=d,e*=e,.25>d+e},PIXI.Ellipse=c.Ellipse,c.Line=function(a,b,d,e){a=a||0,b=b||0,d=d||0,e=e||0,this.start=new c.Point(a,b),this.end=new c.Point(d,e),this.type=c.LINE},c.Line.prototype={setTo:function(a,b,c,d){return this.start.setTo(a,b),this.end.setTo(c,d),this},fromSprite:function(a,b,c){return void 0===c&&(c=!1),c?this.setTo(a.center.x,a.center.y,b.center.x,b.center.y):this.setTo(a.x,a.y,b.x,b.y)},fromAngle:function(a,b,c,d){return this.start.setTo(a,b),this.end.setTo(a+Math.cos(c)*d,b+Math.sin(c)*d),this},rotate:function(a,b){var c=this.start.x,d=this.start.y;return this.start.rotate(this.end.x,this.end.y,a,b,this.length),this.end.rotate(c,d,a,b,this.length),this},intersects:function(a,b,d){return c.Line.intersectsPoints(this.start,this.end,a.start,a.end,b,d)},reflect:function(a){return c.Line.reflect(this,a)},pointOnLine:function(a,b){return(a-this.start.x)*(this.end.y-this.start.y)===(this.end.x-this.start.x)*(b-this.start.y)},pointOnSegment:function(a,b){var c=Math.min(this.start.x,this.end.x),d=Math.max(this.start.x,this.end.x),e=Math.min(this.start.y,this.end.y),f=Math.max(this.start.y,this.end.y);return this.pointOnLine(a,b)&&a>=c&&d>=a&&b>=e&&f>=b},random:function(a){void 0===a&&(a=new c.Point);var b=Math.random();return a.x=this.start.x+b*(this.end.x-this.start.x),a.y=this.start.y+b*(this.end.y-this.start.y),a},coordinatesOnLine:function(a,b){void 0===a&&(a=1),void 0===b&&(b=[]);var c=Math.round(this.start.x),d=Math.round(this.start.y),e=Math.round(this.end.x),f=Math.round(this.end.y),g=Math.abs(e-c),h=Math.abs(f-d),i=e>c?1:-1,j=f>d?1:-1,k=g-h;b.push([c,d]);for(var l=1;c!=e||d!=f;){var m=k<<1;m>-h&&(k-=h,c+=i),g>m&&(k+=g,d+=j),l%a===0&&b.push([c,d]),l++}return b},clone:function(a){return void 0===a||null===a?a=new c.Line(this.start.x,this.start.y,this.end.x,this.end.y):a.setTo(this.start.x,this.start.y,this.end.x,this.end.y),a}},Object.defineProperty(c.Line.prototype,"length",{get:function(){return Math.sqrt((this.end.x-this.start.x)*(this.end.x-this.start.x)+(this.end.y-this.start.y)*(this.end.y-this.start.y))}}),Object.defineProperty(c.Line.prototype,"angle",{get:function(){return Math.atan2(this.end.y-this.start.y,this.end.x-this.start.x)}}),Object.defineProperty(c.Line.prototype,"slope",{get:function(){return(this.end.y-this.start.y)/(this.end.x-this.start.x)}}),Object.defineProperty(c.Line.prototype,"perpSlope",{get:function(){return-((this.end.x-this.start.x)/(this.end.y-this.start.y))}}),Object.defineProperty(c.Line.prototype,"x",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(c.Line.prototype,"y",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(c.Line.prototype,"left",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(c.Line.prototype,"right",{get:function(){return Math.max(this.start.x,this.end.x)}}),Object.defineProperty(c.Line.prototype,"top",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(c.Line.prototype,"bottom",{get:function(){return Math.max(this.start.y,this.end.y)}}),Object.defineProperty(c.Line.prototype,"width",{get:function(){return Math.abs(this.start.x-this.end.x)}}),Object.defineProperty(c.Line.prototype,"height",{get:function(){return Math.abs(this.start.y-this.end.y)}}),Object.defineProperty(c.Line.prototype,"normalX",{get:function(){return Math.cos(this.angle-1.5707963267948966)}}),Object.defineProperty(c.Line.prototype,"normalY",{get:function(){return Math.sin(this.angle-1.5707963267948966)}}),Object.defineProperty(c.Line.prototype,"normalAngle",{get:function(){return c.Math.wrap(this.angle-1.5707963267948966,-Math.PI,Math.PI)}}),c.Line.intersectsPoints=function(a,b,d,e,f,g){void 0===f&&(f=!0),void 0===g&&(g=new c.Point);var h=b.y-a.y,i=e.y-d.y,j=a.x-b.x,k=d.x-e.x,l=b.x*a.y-a.x*b.y,m=e.x*d.y-d.x*e.y,n=h*k-i*j;if(0===n)return null;if(g.x=(j*m-k*l)/n,g.y=(i*l-h*m)/n,f){var o=(e.y-d.y)*(b.x-a.x)-(e.x-d.x)*(b.y-a.y),p=((e.x-d.x)*(a.y-d.y)-(e.y-d.y)*(a.x-d.x))/o,q=((b.x-a.x)*(a.y-d.y)-(b.y-a.y)*(a.x-d.x))/o;return p>=0&&1>=p&&q>=0&&1>=q?g:null}return g},c.Line.intersects=function(a,b,d,e){return c.Line.intersectsPoints(a.start,a.end,b.start,b.end,d,e)},c.Line.reflect=function(a,b){return 2*b.normalAngle-3.141592653589793-a.angle},c.Matrix=function(a,b,d,e,f,g){a=a||1,b=b||0,d=d||0,e=e||1,f=f||0,g=g||0,this.a=a,this.b=b,this.c=d,this.d=e,this.tx=f,this.ty=g,this.type=c.MATRIX},c.Matrix.prototype={fromArray:function(a){return this.setTo(a[0],a[1],a[3],a[4],a[2],a[5])},setTo:function(a,b,c,d,e,f){return this.a=a,this.b=b,this.c=c,this.d=d,this.tx=e,this.ty=f,this},clone:function(a){return void 0===a||null===a?a=new c.Matrix(this.a,this.b,this.c,this.d,this.tx,this.ty):(a.a=this.a,a.b=this.b,a.c=this.c,a.d=this.d,a.tx=this.tx,a.ty=this.ty),a},copyTo:function(a){return a.copyFrom(this),a},copyFrom:function(a){return this.a=a.a,this.b=a.b,this.c=a.c,this.d=a.d,this.tx=a.tx,this.ty=a.ty,this},toArray:function(a,b){return void 0===b&&(b=new PIXI.Float32Array(9)),a?(b[0]=this.a,b[1]=this.b,b[2]=0,b[3]=this.c,b[4]=this.d,b[5]=0,b[6]=this.tx,b[7]=this.ty,b[8]=1):(b[0]=this.a,b[1]=this.c,b[2]=this.tx,b[3]=this.b,b[4]=this.d,b[5]=this.ty,b[6]=0,b[7]=0,b[8]=1),b},apply:function(a,b){return void 0===b&&(b=new c.Point),b.x=this.a*a.x+this.c*a.y+this.tx,b.y=this.b*a.x+this.d*a.y+this.ty,b},applyInverse:function(a,b){void 0===b&&(b=new c.Point);var d=1/(this.a*this.d+this.c*-this.b),e=a.x,f=a.y;return b.x=this.d*d*e+-this.c*d*f+(this.ty*this.c-this.tx*this.d)*d,b.y=this.a*d*f+-this.b*d*e+(-this.ty*this.a+this.tx*this.b)*d,b},translate:function(a,b){return this.tx+=a,this.ty+=b,this},scale:function(a,b){return this.a*=a,this.d*=b,this.c*=a,this.b*=b,this.tx*=a,this.ty*=b,this},rotate:function(a){var b=Math.cos(a),c=Math.sin(a),d=this.a,e=this.c,f=this.tx;return this.a=d*b-this.b*c,this.b=d*c+this.b*b,this.c=e*b-this.d*c,this.d=e*c+this.d*b,this.tx=f*b-this.ty*c,this.ty=f*c+this.ty*b,this},append:function(a){var b=this.a,c=this.b,d=this.c,e=this.d;return this.a=a.a*b+a.b*d,this.b=a.a*c+a.b*e,this.c=a.c*b+a.d*d,this.d=a.c*c+a.d*e,this.tx=a.tx*b+a.ty*d+this.tx,this.ty=a.tx*c+a.ty*e+this.ty,this},identity:function(){return this.setTo(1,0,0,1,0,0)}},c.identityMatrix=new c.Matrix,PIXI.Matrix=c.Matrix,PIXI.identityMatrix=c.identityMatrix,c.Point=function(a,b){a=a||0,b=b||0,this.x=a,this.y=b,this.type=c.POINT},c.Point.prototype={copyFrom:function(a){return this.setTo(a.x,a.y)},invert:function(){return this.setTo(this.y,this.x)},setTo:function(a,b){return this.x=a||0,this.y=b||(0!==b?this.x:0),this},set:function(a,b){return this.x=a||0,this.y=b||(0!==b?this.x:0),this},add:function(a,b){return this.x+=a,this.y+=b,this},subtract:function(a,b){return this.x-=a,this.y-=b,this},multiply:function(a,b){return this.x*=a,this.y*=b,this},divide:function(a,b){return this.x/=a,this.y/=b,this},clampX:function(a,b){return this.x=c.Math.clamp(this.x,a,b),this},clampY:function(a,b){return this.y=c.Math.clamp(this.y,a,b),this},clamp:function(a,b){return this.x=c.Math.clamp(this.x,a,b),this.y=c.Math.clamp(this.y,a,b),this},clone:function(a){return void 0===a||null===a?a=new c.Point(this.x,this.y):a.setTo(this.x,this.y),a},copyTo:function(a){return a.x=this.x,a.y=this.y,a},distance:function(a,b){return c.Point.distance(this,a,b)},equals:function(a){return a.x===this.x&&a.y===this.y},angle:function(a,b){return void 0===b&&(b=!1),b?c.Math.radToDeg(Math.atan2(a.y-this.y,a.x-this.x)):Math.atan2(a.y-this.y,a.x-this.x)},rotate:function(a,b,d,e,f){return c.Point.rotate(this,a,b,d,e,f)},getMagnitude:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},getMagnitudeSq:function(){return this.x*this.x+this.y*this.y},setMagnitude:function(a){return this.normalize().multiply(a,a)},normalize:function(){if(!this.isZero()){var a=this.getMagnitude();this.x/=a,this.y/=a}return this},isZero:function(){return 0===this.x&&0===this.y},dot:function(a){return this.x*a.x+this.y*a.y},cross:function(a){return this.x*a.y-this.y*a.x},perp:function(){return this.setTo(-this.y,this.x)},rperp:function(){return this.setTo(this.y,-this.x)},normalRightHand:function(){return this.setTo(-1*this.y,this.x)},floor:function(){return this.setTo(Math.floor(this.x),Math.floor(this.y))},ceil:function(){return this.setTo(Math.ceil(this.x),Math.ceil(this.y))},toString:function(){return"[{Point (x="+this.x+" y="+this.y+")}]"}},c.Point.prototype.constructor=c.Point,c.Point.add=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x+b.x,d.y=a.y+b.y,d},c.Point.subtract=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x-b.x,d.y=a.y-b.y,d},c.Point.multiply=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x*b.x,d.y=a.y*b.y,d},c.Point.divide=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x/b.x,d.y=a.y/b.y,d},c.Point.equals=function(a,b){return a.x===b.x&&a.y===b.y},c.Point.angle=function(a,b){return Math.atan2(a.y-b.y,a.x-b.x)},c.Point.negative=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(-a.x,-a.y)},c.Point.multiplyAdd=function(a,b,d,e){return void 0===e&&(e=new c.Point),e.setTo(a.x+b.x*d,a.y+b.y*d)},c.Point.interpolate=function(a,b,d,e){return void 0===e&&(e=new c.Point),e.setTo(a.x+(b.x-a.x)*d,a.y+(b.y-a.y)*d)},c.Point.perp=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(-a.y,a.x)},c.Point.rperp=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(a.y,-a.x)},c.Point.distance=function(a,b,d){var e=c.Math.distance(a.x,a.y,b.x,b.y);return d?Math.round(e):e},c.Point.project=function(a,b,d){void 0===d&&(d=new c.Point);var e=a.dot(b)/b.getMagnitudeSq();return 0!==e&&d.setTo(e*b.x,e*b.y),d},c.Point.projectUnit=function(a,b,d){void 0===d&&(d=new c.Point);var e=a.dot(b);return 0!==e&&d.setTo(e*b.x,e*b.y),d},c.Point.normalRightHand=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(-1*a.y,a.x)},c.Point.normalize=function(a,b){void 0===b&&(b=new c.Point);var d=a.getMagnitude();return 0!==d&&b.setTo(a.x/d,a.y/d),b},c.Point.rotate=function(a,b,d,e,f,g){void 0===f&&(f=!1),void 0===g&&(g=null),f&&(e=c.Math.degToRad(e)),null===g&&(g=Math.sqrt((b-a.x)*(b-a.x)+(d-a.y)*(d-a.y)));var h=e+Math.atan2(a.y-d,a.x-b);return a.x=b+g*Math.cos(h),a.y=d+g*Math.sin(h),a},c.Point.centroid=function(a,b){if(void 0===b&&(b=new c.Point),"[object Array]"!==Object.prototype.toString.call(a))throw new Error("Phaser.Point. Parameter 'points' must be an array");var d=a.length;if(1>d)throw new Error("Phaser.Point. Parameter 'points' array must not be empty");if(1===d)return b.copyFrom(a[0]),b;for(var e=0;d>e;e++)c.Point.add(b,a[e],b);return b.divide(d,d),b},c.Point.parse=function(a,b,d){b=b||"x",d=d||"y";var e=new c.Point;return a[b]&&(e.x=parseInt(a[b],10)),a[d]&&(e.y=parseInt(a[d],10)),e},PIXI.Point=c.Point,c.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.type=c.POLYGON},c.Polygon.prototype={toNumberArray:function(a){void 0===a&&(a=[]);for(var b=0;b<this._points.length;b++)"number"==typeof this._points[b]?(a.push(this._points[b]),a.push(this._points[b+1]),b++):(a.push(this._points[b].x),a.push(this._points[b].y));return a},flatten:function(){return this._points=this.toNumberArray(),this},clone:function(a){var b=this._points.slice();return void 0===a||null===a?a=new c.Polygon(b):a.setTo(b),a},contains:function(a,b){for(var c=this._points.length,d=!1,e=-1,f=c-1;++e<c;f=e){var g=this._points[e].x,h=this._points[e].y,i=this._points[f].x,j=this._points[f].y;(b>=h&&j>b||b>=j&&h>b)&&(i-g)*(b-h)/(j-h)+g>a&&(d=!d)}return d},setTo:function(a){if(this.area=0,this._points=[],arguments.length>0){Array.isArray(a)||(a=Array.prototype.slice.call(arguments));for(var b=Number.MAX_VALUE,c=0,d=a.length;d>c;c++){if("number"==typeof a[c]){var e=new PIXI.Point(a[c],a[c+1]);c++}else var e=new PIXI.Point(a[c].x,a[c].y);this._points.push(e),e.y<b&&(b=e.y)}this.calculateArea(b)}return this},calculateArea:function(a){for(var b,c,d,e,f=0,g=this._points.length;g>f;f++)b=this._points[f],c=f===g-1?this._points[0]:this._points[f+1],d=(b.y-a+(c.y-a))/2,e=b.x-c.x,this.area+=d*e;return this.area}},c.Polygon.prototype.constructor=c.Polygon,Object.defineProperty(c.Polygon.prototype,"points",{get:function(){return this._points},set:function(a){null!=a?this.setTo(a):this.setTo()}}),PIXI.Polygon=c.Polygon,c.Rectangle=function(a,b,d,e){a=a||0,b=b||0,d=d||0,e=e||0,this.x=a,this.y=b,this.width=d,this.height=e,this.type=c.RECTANGLE},c.Rectangle.prototype={offset:function(a,b){return this.x+=a,this.y+=b,this},offsetPoint:function(a){return this.offset(a.x,a.y)},setTo:function(a,b,c,d){return this.x=a,this.y=b,this.width=c,this.height=d,this},scale:function(a,b){return void 0===b&&(b=a),this.width*=a,this.height*=b,this},centerOn:function(a,b){return this.centerX=a,this.centerY=b,this},floor:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y)},floorAll:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.width=Math.floor(this.width),this.height=Math.floor(this.height)},ceil:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y)},ceilAll:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.width=Math.ceil(this.width),this.height=Math.ceil(this.height)},copyFrom:function(a){return this.setTo(a.x,a.y,a.width,a.height)},copyTo:function(a){return a.x=this.x,a.y=this.y,a.width=this.width,a.height=this.height,a},inflate:function(a,b){return c.Rectangle.inflate(this,a,b)},size:function(a){return c.Rectangle.size(this,a)},resize:function(a,b){return this.width=a,this.height=b,this},clone:function(a){return c.Rectangle.clone(this,a)},contains:function(a,b){return c.Rectangle.contains(this,a,b)},containsRect:function(a){return c.Rectangle.containsRect(a,this)},equals:function(a){return c.Rectangle.equals(this,a)},intersection:function(a,b){return c.Rectangle.intersection(this,a,b)},intersects:function(a){return c.Rectangle.intersects(this,a)},intersectsRaw:function(a,b,d,e,f){return c.Rectangle.intersectsRaw(this,a,b,d,e,f)},union:function(a,b){return c.Rectangle.union(this,a,b)},random:function(a){return void 0===a&&(a=new c.Point),a.x=this.randomX,a.y=this.randomY,a},toString:function(){return"[{Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+" empty="+this.empty+")}]"}},Object.defineProperty(c.Rectangle.prototype,"halfWidth",{get:function(){return Math.round(this.width/2)}}),Object.defineProperty(c.Rectangle.prototype,"halfHeight",{get:function(){return Math.round(this.height/2)}}),Object.defineProperty(c.Rectangle.prototype,"bottom",{get:function(){return this.y+this.height},set:function(a){this.height=a<=this.y?0:a-this.y}}),Object.defineProperty(c.Rectangle.prototype,"bottomLeft",{get:function(){return new c.Point(this.x,this.bottom)},set:function(a){this.x=a.x,this.bottom=a.y}}),Object.defineProperty(c.Rectangle.prototype,"bottomRight",{get:function(){return new c.Point(this.right,this.bottom)},set:function(a){this.right=a.x,this.bottom=a.y}}),Object.defineProperty(c.Rectangle.prototype,"left",{get:function(){return this.x},set:function(a){this.width=a>=this.right?0:this.right-a,this.x=a}}),Object.defineProperty(c.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(a){this.width=a<=this.x?0:a-this.x}}),Object.defineProperty(c.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(c.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(c.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(a){this.x=a-this.halfWidth}}),Object.defineProperty(c.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(a){this.y=a-this.halfHeight}}),Object.defineProperty(c.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(c.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(c.Rectangle.prototype,"top",{get:function(){return this.y},set:function(a){a>=this.bottom?(this.height=0,this.y=a):this.height=this.bottom-a}}),Object.defineProperty(c.Rectangle.prototype,"topLeft",{get:function(){return new c.Point(this.x,this.y)},set:function(a){this.x=a.x,this.y=a.y}}),Object.defineProperty(c.Rectangle.prototype,"topRight",{get:function(){return new c.Point(this.x+this.width,this.y)},set:function(a){this.right=a.x,this.y=a.y}}),Object.defineProperty(c.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(a){a===!0&&this.setTo(0,0,0,0)}}),c.Rectangle.prototype.constructor=c.Rectangle,c.Rectangle.inflate=function(a,b,c){return a.x-=b,a.width+=2*b,a.y-=c,a.height+=2*c,a},c.Rectangle.inflatePoint=function(a,b){return c.Rectangle.inflate(a,b.x,b.y)},c.Rectangle.size=function(a,b){return void 0===b||null===b?b=new c.Point(a.width,a.height):b.setTo(a.width,a.height),b},c.Rectangle.clone=function(a,b){return void 0===b||null===b?b=new c.Rectangle(a.x,a.y,a.width,a.height):b.setTo(a.x,a.y,a.width,a.height),b},c.Rectangle.contains=function(a,b,c){return a.width<=0||a.height<=0?!1:b>=a.x&&b<a.right&&c>=a.y&&c<a.bottom},c.Rectangle.containsRaw=function(a,b,c,d,e,f){return e>=a&&a+c>e&&f>=b&&b+d>f},c.Rectangle.containsPoint=function(a,b){return c.Rectangle.contains(a,b.x,b.y)},c.Rectangle.containsRect=function(a,b){return a.volume>b.volume?!1:a.x>=b.x&&a.y>=b.y&&a.right<b.right&&a.bottom<b.bottom},c.Rectangle.equals=function(a,b){return a.x==b.x&&a.y==b.y&&a.width==b.width&&a.height==b.height},c.Rectangle.sameDimensions=function(a,b){return a.width===b.width&&a.height===b.height},c.Rectangle.intersection=function(a,b,d){return void 0===d&&(d=new c.Rectangle),c.Rectangle.intersects(a,b)&&(d.x=Math.max(a.x,b.x),d.y=Math.max(a.y,b.y),d.width=Math.min(a.right,b.right)-d.x,d.height=Math.min(a.bottom,b.bottom)-d.y),d},c.Rectangle.intersects=function(a,b){return a.width<=0||a.height<=0||b.width<=0||b.height<=0?!1:!(a.right<b.x||a.bottom<b.y||a.x>b.right||a.y>b.bottom)},c.Rectangle.intersectsRaw=function(a,b,c,d,e,f){return void 0===f&&(f=0),!(b>a.right+f||c<a.left-f||d>a.bottom+f||e<a.top-f)},c.Rectangle.union=function(a,b,d){return void 0===d&&(d=new c.Rectangle),d.setTo(Math.min(a.x,b.x),Math.min(a.y,b.y),Math.max(a.right,b.right)-Math.min(a.left,b.left),Math.max(a.bottom,b.bottom)-Math.min(a.top,b.top))},c.Rectangle.aabb=function(a,b){void 0===b&&(b=new c.Rectangle);var d=Number.MIN_VALUE,e=Number.MAX_VALUE,f=Number.MIN_VALUE,g=Number.MAX_VALUE;return a.forEach(function(a){a.x>d&&(d=a.x),a.x<e&&(e=a.x),a.y>f&&(f=a.y),a.y<g&&(g=a.y)}),b.setTo(e,g,d-e,f-g),b},PIXI.Rectangle=c.Rectangle,PIXI.EmptyRectangle=new c.Rectangle(0,0,0,0),c.RoundedRectangle=function(a,b,d,e,f){void 0===a&&(a=0),void 0===b&&(b=0),void 0===d&&(d=0),void 0===e&&(e=0),void 0===f&&(f=20),this.x=a,this.y=b,this.width=d,this.height=e,this.radius=f||20,this.type=c.ROUNDEDRECTANGLE},c.RoundedRectangle.prototype={clone:function(){return new c.RoundedRectangle(this.x,this.y,this.width,this.height,this.radius)},contains:function(a,b){if(this.width<=0||this.height<=0)return!1;var c=this.x;if(a>=c&&a<=c+this.width){var d=this.y;if(b>=d&&b<=d+this.height)return!0}return!1}},c.RoundedRectangle.prototype.constructor=c.RoundedRectangle,PIXI.RoundedRectangle=c.RoundedRectangle,c.Camera=function(a,b,d,e,f,g){this.game=a,this.world=a.world,this.id=0,this.view=new c.Rectangle(d,e,f,g),this.bounds=new c.Rectangle(d,e,f,g),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this._targetPosition=new c.Point,this._edge=0,this._position=new c.Point},c.Camera.FOLLOW_LOCKON=0,c.Camera.FOLLOW_PLATFORMER=1,c.Camera.FOLLOW_TOPDOWN=2,c.Camera.FOLLOW_TOPDOWN_TIGHT=3,c.Camera.prototype={preUpdate:function(){this.totalInView=0},follow:function(a,b){void 0===b&&(b=c.Camera.FOLLOW_LOCKON),this.target=a;var d;switch(b){case c.Camera.FOLLOW_PLATFORMER:var e=this.width/8,f=this.height/3;this.deadzone=new c.Rectangle((this.width-e)/2,(this.height-f)/2-.25*f,e,f);break;case c.Camera.FOLLOW_TOPDOWN:d=Math.max(this.width,this.height)/4,this.deadzone=new c.Rectangle((this.width-d)/2,(this.height-d)/2,d,d);break;case c.Camera.FOLLOW_TOPDOWN_TIGHT:d=Math.max(this.width,this.height)/8,this.deadzone=new c.Rectangle((this.width-d)/2,(this.height-d)/2,d,d);break;case c.Camera.FOLLOW_LOCKON:this.deadzone=null;break;default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(a){this.setPosition(Math.round(a.x-this.view.halfWidth),Math.round(a.y-this.view.halfHeight))},focusOnXY:function(a,b){this.setPosition(Math.round(a-this.view.halfWidth),Math.round(b-this.view.halfHeight))},update:function(){this.target&&this.updateTarget(),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateTarget:function(){this._targetPosition.copyFrom(this.target),this.target.parent&&this._targetPosition.multiply(this.target.parent.worldTransform.a,this.target.parent.worldTransform.d),this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edge<this.deadzone.left?this.view.x=this._targetPosition.x-this.deadzone.left:this._edge>this.deadzone.right&&(this.view.x=this._targetPosition.x-this.deadzone.right),this._edge=this._targetPosition.y-this.view.y,this._edge<this.deadzone.top?this.view.y=this._targetPosition.y-this.deadzone.top:this._edge>this.deadzone.bottom&&(this.view.y=this._targetPosition.y-this.deadzone.bottom)):(this.view.x=this._targetPosition.x-this.view.halfWidth,this.view.y=this._targetPosition.y-this.view.halfHeight)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1,this.view.x<=this.bounds.x&&(this.atLimit.x=!0,this.view.x=this.bounds.x),this.view.right>=this.bounds.right&&(this.atLimit.x=!0,this.view.x=this.bounds.right-this.width),this.view.y<=this.bounds.top&&(this.atLimit.y=!0,this.view.y=this.bounds.top),this.view.bottom>=this.bounds.bottom&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom-this.height)},setPosition:function(a,b){this.view.x=a,this.view.y=b,this.bounds&&this.checkBounds()},setSize:function(a,b){this.view.width=a,this.view.height=b},reset:function(){this.target=null,this.view.x=0,this.view.y=0}},c.Camera.prototype.constructor=c.Camera,Object.defineProperty(c.Camera.prototype,"x",{get:function(){return this.view.x},set:function(a){this.view.x=a,this.bounds&&this.checkBounds()}}),Object.defineProperty(c.Camera.prototype,"y",{get:function(){return this.view.y},set:function(a){this.view.y=a,this.bounds&&this.checkBounds()}}),Object.defineProperty(c.Camera.prototype,"position",{get:function(){return this._position.set(this.view.centerX,this.view.centerY),this._position},set:function(a){"undefined"!=typeof a.x&&(this.view.x=a.x),"undefined"!=typeof a.y&&(this.view.y=a.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(c.Camera.prototype,"width",{get:function(){return this.view.width},set:function(a){this.view.width=a}}),Object.defineProperty(c.Camera.prototype,"height",{get:function(){return this.view.height},set:function(a){this.view.height=a}}),c.Create=function(a){this.game=a,this.bmd=a.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context,this.palettes=[{0:"#000",1:"#9D9D9D",2:"#FFF",3:"#BE2633",4:"#E06F8B",5:"#493C2B",6:"#A46422",7:"#EB8931",8:"#F7E26B",9:"#2F484E",A:"#44891A",B:"#A3CE27",C:"#1B2632",D:"#005784",E:"#31A2F2",F:"#B2DCEF"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"},{0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"},{0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}]},c.Create.PALETTE_ARNE=0,c.Create.PALETTE_JMP=1,c.Create.PALETTE_CGA=2,c.Create.PALETTE_C64=3,c.Create.PALETTE_JAPANESE_MACHINE=4,c.Create.prototype={texture:function(a,b,c,d,e){void 0===c&&(c=8),void 0===d&&(d=c),void 0===e&&(e=0);var f=b[0].length*c,g=b.length*d;this.bmd.resize(f,g),this.bmd.clear();for(var h=0;h<b.length;h++)for(var i=b[h],j=0;j<i.length;j++){var k=i[j];"."!==k&&" "!==k&&(this.ctx.fillStyle=this.palettes[e][k],this.ctx.fillRect(j*c,h*d,c,d))}return this.bmd.generateTexture(a)},grid:function(a,b,c,d,e,f){this.bmd.resize(b,c),this.ctx.fillStyle=f;for(var g=0;c>g;g+=e)this.ctx.fillRect(0,g,b,1);for(var h=0;b>h;h+=d)this.ctx.fillRect(h,0,1,c);return this.bmd.generateTexture(a)}},c.Create.prototype.constructor=c.Create,c.State=function(){this.game=null,this.key="",this.add=null,this.make=null,this.camera=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.sound=null,this.scale=null,this.stage=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},c.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},c.State.prototype.constructor=c.State,c.StateManager=function(a,b){this.game=a,this.states={},this._pendingState=null,"undefined"!=typeof b&&null!==b&&(this._pendingState=b),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new c.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},c.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(a,b,d){void 0===d&&(d=!1);
-var e;return b instanceof c.State?e=b:"object"==typeof b?(e=b,e.game=this.game):"function"==typeof b&&(e=new b(this.game)),this.states[a]=e,d&&(this.game.isBooted?this.start(a):this._pendingState=a),e},remove:function(a){this.current===a&&(this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[a]},start:function(a,b,c){void 0===b&&(b=!0),void 0===c&&(c=!1),this.checkState(a)&&(this._pendingState=a,this._clearWorld=b,this._clearCache=c,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(a,b){void 0===a&&(a=!0),void 0===b&&(b=!1),this._pendingState=this.current,this._clearWorld=a,this._clearCache=b,arguments.length>2&&(this._args=Array.prototype.splice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var a=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,a),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache===!0&&this.game.cache.destroy()))},checkState:function(a){if(this.states[a]){var b=!1;return(this.states[a].preload||this.states[a].create||this.states[a].update||this.states[a].render)&&(b=!0),b===!1?(console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render"),!1):!0}return console.warn("Phaser.StateManager - No state found with the key: "+a),!1},link:function(a){this.states[a].game=this.game,this.states[a].add=this.game.add,this.states[a].make=this.game.make,this.states[a].camera=this.game.camera,this.states[a].cache=this.game.cache,this.states[a].input=this.game.input,this.states[a].load=this.game.load,this.states[a].math=this.game.math,this.states[a].sound=this.game.sound,this.states[a].scale=this.game.scale,this.states[a].state=this,this.states[a].stage=this.game.stage,this.states[a].time=this.game.time,this.states[a].tweens=this.game.tweens,this.states[a].world=this.game.world,this.states[a].particles=this.game.particles,this.states[a].rnd=this.game.rnd,this.states[a].physics=this.game.physics,this.states[a].key=a},unlink:function(a){this.states[a]&&(this.states[a].game=null,this.states[a].add=null,this.states[a].make=null,this.states[a].camera=null,this.states[a].cache=null,this.states[a].input=null,this.states[a].load=null,this.states[a].math=null,this.states[a].sound=null,this.states[a].scale=null,this.states[a].state=null,this.states[a].stage=null,this.states[a].time=null,this.states[a].tweens=null,this.states[a].world=null,this.states[a].particles=null,this.states[a].rnd=null,this.states[a].physics=null)},setCurrentState:function(a){this.callbackContext=this.states[a],this.link(a),this.onInitCallback=this.states[a].init||this.dummy,this.onPreloadCallback=this.states[a].preload||null,this.onLoadRenderCallback=this.states[a].loadRender||null,this.onLoadUpdateCallback=this.states[a].loadUpdate||null,this.onCreateCallback=this.states[a].create||null,this.onUpdateCallback=this.states[a].update||null,this.onPreRenderCallback=this.states[a].preRender||null,this.onRenderCallback=this.states[a].render||null,this.onResizeCallback=this.states[a].resize||null,this.onPausedCallback=this.states[a].paused||null,this.onResumedCallback=this.states[a].resumed||null,this.onPauseUpdateCallback=this.states[a].pauseUpdate||null,this.onShutDownCallback=this.states[a].shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=a,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),a===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){this._created===!1&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(a){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,a)},resize:function(a,b){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,a,b)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===c.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this.clearCurrentState(),this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.game=null,this.states={},this._pendingState=null,this.current=""}},c.StateManager.prototype.constructor=c.StateManager,Object.defineProperty(c.StateManager.prototype,"created",{get:function(){return this._created}}),c.Signal=function(){},c.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!0,validateListener:function(a,b){if("function"!=typeof a)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",b))},_registerListener:function(a,b,d,e,f){var g,h=this._indexOfListener(a,d);if(-1!==h){if(g=this._bindings[h],g.isOnce()!==b)throw new Error("You cannot add"+(b?"":"Once")+"() then add"+(b?"Once":"")+"() the same listener without removing the relationship first.")}else g=new c.SignalBinding(this,a,b,d,e,f),this._addBinding(g);return this.memorize&&this._prevParams&&g.execute(this._prevParams),g},_addBinding:function(a){this._bindings||(this._bindings=[]);var b=this._bindings.length;do b--;while(this._bindings[b]&&a._priority<=this._bindings[b]._priority);this._bindings.splice(b+1,0,a)},_indexOfListener:function(a,b){if(!this._bindings)return-1;void 0===b&&(b=null);for(var c,d=this._bindings.length;d--;)if(c=this._bindings[d],c._listener===a&&c.context===b)return d;return-1},has:function(a,b){return-1!==this._indexOfListener(a,b)},add:function(a,b,c){this.validateListener(a,"add");var d=[];if(arguments.length>3)for(var e=3;e<arguments.length;e++)d.push(arguments[e]);return this._registerListener(a,!1,b,c,d)},addOnce:function(a,b,c){this.validateListener(a,"addOnce");var d=[];if(arguments.length>3)for(var e=3;e<arguments.length;e++)d.push(arguments[e]);return this._registerListener(a,!0,b,c,d)},remove:function(a,b){this.validateListener(a,"remove");var c=this._indexOfListener(a,b);return-1!==c&&(this._bindings[c]._destroy(),this._bindings.splice(c,1)),a},removeAll:function(a){if(void 0===a&&(a=null),this._bindings){for(var b=this._bindings.length;b--;)a?this._bindings[b].context===a&&(this._bindings[b]._destroy(),this._bindings.splice(b,1)):this._bindings[b]._destroy();a||(this._bindings.length=0)}},getNumListeners:function(){return this._bindings?this._bindings.length:0},halt:function(){this._shouldPropagate=!1},dispatch:function(){if(this.active&&this._bindings){var a,b=Array.prototype.slice.call(arguments),c=this._bindings.length;if(this.memorize&&(this._prevParams=b),c){a=this._bindings.slice(),this._shouldPropagate=!0;do c--;while(a[c]&&this._shouldPropagate&&a[c].execute(b)!==!1)}}},forget:function(){this._prevParams&&(this._prevParams=null)},dispose:function(){this.removeAll(),this._bindings=null,this._prevParams&&(this._prevParams=null)},toString:function(){return"[Phaser.Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}},Object.defineProperty(c.Signal.prototype,"boundDispatch",{get:function(){var a=this;return this._boundDispatch||(this._boundDispatch=function(){return a.dispatch.apply(a,arguments)})}}),c.Signal.prototype.constructor=c.Signal,c.SignalBinding=function(a,b,c,d,e,f){this._listener=b,c&&(this._isOnce=!0),null!=d&&(this.context=d),this._signal=a,e&&(this._priority=e),f&&f.length&&(this._args=f)},c.SignalBinding.prototype={context:null,_isOnce:!1,_priority:0,_args:null,callCount:0,active:!0,params:null,execute:function(a){var b,c;return this.active&&this._listener&&(c=this.params?this.params.concat(a):a,this._args&&(c=c.concat(this._args)),b=this._listener.apply(this.context,c),this.callCount++,this._isOnce&&this.detach()),b},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},isOnce:function(){return this._isOnce},getListener:function(){return this._listener},getSignal:function(){return this._signal},_destroy:function(){delete this._signal,delete this._listener,delete this.context},toString:function(){return"[Phaser.SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}},c.SignalBinding.prototype.constructor=c.SignalBinding,c.Filter=function(a,b,d){this.game=a,this.type=c.WEBGL_FILTER,this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.prevPoint=new c.Point;var e=new Date;if(this.uniforms={resolution:{type:"2f",value:{x:256,y:256}},time:{type:"1f",value:0},mouse:{type:"2f",value:{x:0,y:0}},date:{type:"4fv",value:[e.getFullYear(),e.getMonth(),e.getDate(),60*e.getHours()*60+60*e.getMinutes()+e.getSeconds()]},sampleRate:{type:"1f",value:44100},iChannel0:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel1:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel2:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel3:{type:"sampler2D",value:null,textureData:{repeat:!0}}},b)for(var f in b)this.uniforms[f]=b[f];this.fragmentSrc=d||""},c.Filter.prototype={init:function(){},setResolution:function(a,b){this.uniforms.resolution.value.x=a,this.uniforms.resolution.value.y=b},update:function(a){if("undefined"!=typeof a){var b=a.x/this.game.width,c=1-a.y/this.game.height;(b!==this.prevPoint.x||c!==this.prevPoint.y)&&(this.uniforms.mouse.value.x=b.toFixed(2),this.uniforms.mouse.value.y=c.toFixed(2),this.prevPoint.set(b,c))}this.uniforms.time.value=this.game.time.totalElapsedSeconds()},destroy:function(){this.game=null}},c.Filter.prototype.constructor=c.Filter,Object.defineProperty(c.Filter.prototype,"width",{get:function(){return this.uniforms.resolution.value.x},set:function(a){this.uniforms.resolution.value.x=a}}),Object.defineProperty(c.Filter.prototype,"height",{get:function(){return this.uniforms.resolution.value.y},set:function(a){this.uniforms.resolution.value.y=a}}),c.Plugin=function(a,b){void 0===b&&(b=null),this.game=a,this.parent=b,this.active=!1,this.visible=!1,this.hasPreUpdate=!1,this.hasUpdate=!1,this.hasPostUpdate=!1,this.hasRender=!1,this.hasPostRender=!1},c.Plugin.prototype={preUpdate:function(){},update:function(){},render:function(){},postRender:function(){},destroy:function(){this.game=null,this.parent=null,this.active=!1,this.visible=!1}},c.Plugin.prototype.constructor=c.Plugin,c.PluginManager=function(a){this.game=a,this.plugins=[],this._len=0,this._i=0},c.PluginManager.prototype={add:function(a){var b=Array.prototype.splice.call(arguments,1),c=!1;return"function"==typeof a?a=new a(this.game,this):(a.game=this.game,a.parent=this),"function"==typeof a.preUpdate&&(a.hasPreUpdate=!0,c=!0),"function"==typeof a.update&&(a.hasUpdate=!0,c=!0),"function"==typeof a.postUpdate&&(a.hasPostUpdate=!0,c=!0),"function"==typeof a.render&&(a.hasRender=!0,c=!0),"function"==typeof a.postRender&&(a.hasPostRender=!0,c=!0),c?((a.hasPreUpdate||a.hasUpdate||a.hasPostUpdate)&&(a.active=!0),(a.hasRender||a.hasPostRender)&&(a.visible=!0),this._len=this.plugins.push(a),"function"==typeof a.init&&a.init.apply(a,b),a):null},remove:function(a){for(this._i=this._len;this._i--;)if(this.plugins[this._i]===a)return a.destroy(),this.plugins.splice(this._i,1),void this._len--},removeAll:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].destroy();this.plugins.length=0,this._len=0},preUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPreUpdate&&this.plugins[this._i].preUpdate()},update:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasUpdate&&this.plugins[this._i].update()},postUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPostUpdate&&this.plugins[this._i].postUpdate()},render:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasRender&&this.plugins[this._i].render()},postRender:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasPostRender&&this.plugins[this._i].postRender()},destroy:function(){this.removeAll(),this.game=null}},c.PluginManager.prototype.constructor=c.PluginManager,c.Stage=function(a){this.game=a,PIXI.Stage.call(this,0),this.name="_stage_root",this.disableVisibilityChange=!1,this.exists=!0,this.currentRenderOrderID=0,this._hiddenVar="hidden",this._onChange=null,this._backgroundColor=0,a.config&&this.parseConfig(a.config)},c.Stage.prototype=Object.create(PIXI.Stage.prototype),c.Stage.prototype.constructor=c.Stage,c.Stage.prototype.parseConfig=function(a){a.disableVisibilityChange&&(this.disableVisibilityChange=a.disableVisibilityChange),a.backgroundColor&&(this.backgroundColor=a.backgroundColor)},c.Stage.prototype.boot=function(){c.DOM.getOffset(this.game.canvas,this.offset),c.Canvas.setUserSelect(this.game.canvas,"none"),c.Canvas.setTouchAction(this.game.canvas,"none"),this.checkVisibility()},c.Stage.prototype.preUpdate=function(){this.currentRenderOrderID=0;for(var a=0;a<this.children.length;a++)this.children[a].preUpdate()},c.Stage.prototype.update=function(){for(var a=this.children.length;a--;)this.children[a].update()},c.Stage.prototype.postUpdate=function(){if(this.game.world.camera.target){this.game.world.camera.target.postUpdate(),this.game.world.camera.update();for(var a=this.children.length;a--;)this.children[a]!==this.game.world.camera.target&&this.children[a].postUpdate()}else{this.game.world.camera.update();for(var a=this.children.length;a--;)this.children[a].postUpdate()}},c.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var a=0;a<this.children.length;a++)this.children[a].updateTransform()},c.Stage.prototype.checkVisibility=function(){this._hiddenVar=void 0!==document.webkitHidden?"webkitvisibilitychange":void 0!==document.mozHidden?"mozvisibilitychange":void 0!==document.msHidden?"msvisibilitychange":void 0!==document.hidden?"visibilitychange":null;var a=this;this._onChange=function(b){return a.visibilityChange(b)},this._hiddenVar&&document.addEventListener(this._hiddenVar,this._onChange,!1),window.onblur=this._onChange,window.onfocus=this._onChange,window.onpagehide=this._onChange,window.onpageshow=this._onChange,this.game.device.cocoonJSApp&&(CocoonJS.App.onSuspended.addEventListener(function(){c.Stage.prototype.visibilityChange.call(a,{type:"pause"})}),CocoonJS.App.onActivated.addEventListener(function(){c.Stage.prototype.visibilityChange.call(a,{type:"resume"})}))},c.Stage.prototype.visibilityChange=function(a){return"pagehide"===a.type||"blur"===a.type||"pageshow"===a.type||"focus"===a.type?void("pagehide"===a.type||"blur"===a.type?this.game.focusLoss(a):("pageshow"===a.type||"focus"===a.type)&&this.game.focusGain(a)):void(this.disableVisibilityChange||(document.hidden||document.mozHidden||document.msHidden||document.webkitHidden||"pause"===a.type?this.game.gamePaused(a):this.game.gameResumed(a)))},c.Stage.prototype.setBackgroundColor=function(a){var b=c.Color.valueToColor(a);this._backgroundColor=c.Color.getColor(b.r,b.g,b.b),this.backgroundColorSplit=[b.r/255,b.g/255,b.b/255],this.backgroundColorString=c.Color.RGBtoString(b.r,b.g,b.b,255,"#")},c.Stage.prototype.destroy=function(){this._hiddenVar&&document.removeEventListener(this._hiddenVar,this._onChange,!1),window.onpagehide=null,window.onpageshow=null,window.onblur=null,window.onfocus=null},Object.defineProperty(c.Stage.prototype,"backgroundColor",{get:function(){return this._backgroundColor},set:function(a){this.game.transparent||this.setBackgroundColor(a)}}),Object.defineProperty(c.Stage.prototype,"smoothed",{get:function(){return PIXI.scaleModes.DEFAULT===PIXI.scaleModes.LINEAR},set:function(a){PIXI.scaleModes.DEFAULT=a?PIXI.scaleModes.LINEAR:PIXI.scaleModes.NEAREST}}),c.Group=function(a,b,d,e,f,g){void 0===e&&(e=!1),void 0===f&&(f=!1),void 0===g&&(g=c.Physics.ARCADE),this.game=a,void 0===b&&(b=a.world),this.name=d||"group",this.z=0,PIXI.DisplayObjectContainer.call(this),e?(this.game.stage.addChild(this),this.z=this.game.stage.children.length):b&&(b.addChild(this),this.z=b.children.length),this.type=c.GROUP,this.physicsType=c.GROUP,this.alive=!0,this.exists=!0,this.ignoreDestroy=!1,this.pendingDestroy=!1,this.classType=c.Sprite,this.cursor=null,this.enableBody=f,this.enableBodyDebug=!1,this.physicsBodyType=g,this.physicsSortDirection=null,this.onDestroy=new c.Signal,this.cursorIndex=0,this.fixedToCamera=!1,this.cameraOffset=new c.Point,this.hash=[],this._sortProperty="z"},c.Group.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),c.Group.prototype.constructor=c.Group,c.Group.RETURN_NONE=0,c.Group.RETURN_TOTAL=1,c.Group.RETURN_CHILD=2,c.Group.SORT_ASCENDING=-1,c.Group.SORT_DESCENDING=1,c.Group.prototype.add=function(a,b){return void 0===b&&(b=!1),a.parent!==this&&(this.addChild(a),a.z=this.children.length,this.enableBody&&null===a.body?this.game.physics.enable(a,this.physicsBodyType):a.body&&this.addToHash(a),!b&&a.events&&a.events.onAddedToGroup$dispatch(a,this),null===this.cursor&&(this.cursor=a)),a},c.Group.prototype.addToHash=function(a){if(a.parent===this){var b=this.hash.indexOf(a);if(-1===b)return this.hash.push(a),!0}return!1},c.Group.prototype.removeFromHash=function(a){if(a){var b=this.hash.indexOf(a);if(-1!==b)return this.hash.splice(b,1),!0}return!1},c.Group.prototype.addMultiple=function(a,b){if(a instanceof c.Group)a.moveAll(this,b);else if(Array.isArray(a))for(var d=0;d<a.length;d++)this.add(a[d],b);return a},c.Group.prototype.addAt=function(a,b,c){return void 0===c&&(c=!1),a.parent!==this&&(this.addChildAt(a,b),this.updateZ(),this.enableBody&&null===a.body?this.game.physics.enable(a,this.physicsBodyType):a.body&&this.addToHash(a),!c&&a.events&&a.events.onAddedToGroup$dispatch(a,this),null===this.cursor&&(this.cursor=a)),a},c.Group.prototype.getAt=function(a){return 0>a||a>=this.children.length?-1:this.getChildAt(a)},c.Group.prototype.create=function(a,b,c,d,e){void 0===e&&(e=!0);var f=new this.classType(this.game,a,b,c,d);return f.exists=e,f.visible=e,f.alive=e,this.addChild(f),f.z=this.children.length,this.enableBody&&this.game.physics.enable(f,this.physicsBodyType,this.enableBodyDebug),f.events&&f.events.onAddedToGroup$dispatch(f,this),null===this.cursor&&(this.cursor=f),f},c.Group.prototype.createMultiple=function(a,b,c,d){void 0===d&&(d=!1);for(var e=0;a>e;e++)this.create(0,0,b,c,d)},c.Group.prototype.updateZ=function(){for(var a=this.children.length;a--;)this.children[a].z=a},c.Group.prototype.resetCursor=function(a){return void 0===a&&(a=0),a>this.children.length-1&&(a=0),this.cursor?(this.cursorIndex=a,this.cursor=this.children[this.cursorIndex],this.cursor):void 0},c.Group.prototype.next=function(){return this.cursor?(this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor):void 0},c.Group.prototype.previous=function(){return this.cursor?(0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor):void 0},c.Group.prototype.swap=function(a,b){this.swapChildren(a,b),this.updateZ()},c.Group.prototype.bringToTop=function(a){return a.parent===this&&this.getIndex(a)<this.children.length&&(this.remove(a,!1,!0),this.add(a,!0)),a},c.Group.prototype.sendToBack=function(a){return a.parent===this&&this.getIndex(a)>0&&(this.remove(a,!1,!0),this.addAt(a,0,!0)),a},c.Group.prototype.moveUp=function(a){if(a.parent===this&&this.getIndex(a)<this.children.length-1){var b=this.getIndex(a),c=this.getAt(b+1);c&&this.swap(a,c)}return a},c.Group.prototype.moveDown=function(a){if(a.parent===this&&this.getIndex(a)>0){var b=this.getIndex(a),c=this.getAt(b-1);c&&this.swap(a,c)}return a},c.Group.prototype.xy=function(a,b,c){return 0>a||a>this.children.length?-1:(this.getChildAt(a).x=b,void(this.getChildAt(a).y=c))},c.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},c.Group.prototype.getIndex=function(a){return this.children.indexOf(a)},c.Group.prototype.replace=function(a,b){var d=this.getIndex(a);return-1!==d?(b.parent&&(b.parent instanceof c.Group?b.parent.remove(b):b.parent.removeChild(b)),this.remove(a),this.addAt(b,d),a):void 0},c.Group.prototype.hasProperty=function(a,b){var c=b.length;return 1===c&&b[0]in a?!0:2===c&&b[0]in a&&b[1]in a[b[0]]?!0:3===c&&b[0]in a&&b[1]in a[b[0]]&&b[2]in a[b[0]][b[1]]?!0:4===c&&b[0]in a&&b[1]in a[b[0]]&&b[2]in a[b[0]][b[1]]&&b[3]in a[b[0]][b[1]][b[2]]?!0:!1},c.Group.prototype.setProperty=function(a,b,c,d,e){if(void 0===e&&(e=!1),d=d||0,!this.hasProperty(a,b)&&(!e||d>0))return!1;var f=b.length;return 1===f?0===d?a[b[0]]=c:1==d?a[b[0]]+=c:2==d?a[b[0]]-=c:3==d?a[b[0]]*=c:4==d&&(a[b[0]]/=c):2===f?0===d?a[b[0]][b[1]]=c:1==d?a[b[0]][b[1]]+=c:2==d?a[b[0]][b[1]]-=c:3==d?a[b[0]][b[1]]*=c:4==d&&(a[b[0]][b[1]]/=c):3===f?0===d?a[b[0]][b[1]][b[2]]=c:1==d?a[b[0]][b[1]][b[2]]+=c:2==d?a[b[0]][b[1]][b[2]]-=c:3==d?a[b[0]][b[1]][b[2]]*=c:4==d&&(a[b[0]][b[1]][b[2]]/=c):4===f&&(0===d?a[b[0]][b[1]][b[2]][b[3]]=c:1==d?a[b[0]][b[1]][b[2]][b[3]]+=c:2==d?a[b[0]][b[1]][b[2]][b[3]]-=c:3==d?a[b[0]][b[1]][b[2]][b[3]]*=c:4==d&&(a[b[0]][b[1]][b[2]][b[3]]/=c)),!0},c.Group.prototype.checkProperty=function(a,b,d,e){return void 0===e&&(e=!1),!c.Utils.getProperty(a,b)&&e?!1:c.Utils.getProperty(a,b)!==d?!1:!0},c.Group.prototype.set=function(a,b,c,d,e,f,g){return void 0===g&&(g=!1),b=b.split("."),void 0===d&&(d=!1),void 0===e&&(e=!1),(d===!1||d&&a.alive)&&(e===!1||e&&a.visible)?this.setProperty(a,b,c,f,g):void 0},c.Group.prototype.setAll=function(a,b,c,d,e,f){void 0===c&&(c=!1),void 0===d&&(d=!1),void 0===f&&(f=!1),a=a.split("."),e=e||0;for(var g=0;g<this.children.length;g++)(!c||c&&this.children[g].alive)&&(!d||d&&this.children[g].visible)&&this.setProperty(this.children[g],a,b,e,f)},c.Group.prototype.setAllChildren=function(a,b,d,e,f,g){void 0===d&&(d=!1),void 0===e&&(e=!1),void 0===g&&(g=!1),f=f||0;for(var h=0;h<this.children.length;h++)(!d||d&&this.children[h].alive)&&(!e||e&&this.children[h].visible)&&(this.children[h]instanceof c.Group?this.children[h].setAllChildren(a,b,d,e,f,g):this.setProperty(this.children[h],a.split("."),b,f,g))},c.Group.prototype.checkAll=function(a,b,c,d,e){void 0===c&&(c=!1),void 0===d&&(d=!1),void 0===e&&(e=!1);for(var f=0;f<this.children.length;f++)if((!c||c&&this.children[f].alive)&&(!d||d&&this.children[f].visible)&&!this.checkProperty(this.children[f],a,b,e))return!1;return!0},c.Group.prototype.addAll=function(a,b,c,d){this.setAll(a,b,c,d,1)},c.Group.prototype.subAll=function(a,b,c,d){this.setAll(a,b,c,d,2)},c.Group.prototype.multiplyAll=function(a,b,c,d){this.setAll(a,b,c,d,3)},c.Group.prototype.divideAll=function(a,b,c,d){this.setAll(a,b,c,d,4)},c.Group.prototype.callAllExists=function(a,b){var c;if(arguments.length>2){c=[];for(var d=2;d<arguments.length;d++)c.push(arguments[d])}for(var d=0;d<this.children.length;d++)this.children[d].exists===b&&this.children[d][a]&&this.children[d][a].apply(this.children[d],c)},c.Group.prototype.callbackFromArray=function(a,b,c){if(1==c){if(a[b[0]])return a[b[0]]}else if(2==c){if(a[b[0]][b[1]])return a[b[0]][b[1]]}else if(3==c){if(a[b[0]][b[1]][b[2]])return a[b[0]][b[1]][b[2]]}else if(4==c){if(a[b[0]][b[1]][b[2]][b[3]])return a[b[0]][b[1]][b[2]][b[3]]}else if(a[b])return a[b];return!1},c.Group.prototype.callAll=function(a,b){if(void 0!==a){a=a.split(".");var c=a.length;if(void 0===b||null===b||""===b)b=null;else if("string"==typeof b){b=b.split(".");var d=b.length}var e;if(arguments.length>2){e=[];for(var f=2;f<arguments.length;f++)e.push(arguments[f])}for(var g=null,h=null,f=0;f<this.children.length;f++)g=this.callbackFromArray(this.children[f],a,c),b&&g?(h=this.callbackFromArray(this.children[f],b,d),g&&g.apply(h,e)):g&&g.apply(this.children[f],e)}},c.Group.prototype.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;for(var a=this.children.length;a--;)this.children[a].preUpdate();return!0},c.Group.prototype.update=function(){for(var a=this.children.length;a--;)this.children[a].update()},c.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=this.game.camera.view.x+this.cameraOffset.x,this.y=this.game.camera.view.y+this.cameraOffset.y);for(var a=this.children.length;a--;)this.children[a].postUpdate()},c.Group.prototype.filter=function(a,b){for(var d=-1,e=this.children.length,f=[];++d<e;){var g=this.children[d];(!b||b&&g.exists)&&a(g,d,this.children)&&f.push(g)}return new c.ArraySet(f)},c.Group.prototype.forEach=function(a,b,c){if(void 0===c&&(c=!1),arguments.length<=3)for(var d=0;d<this.children.length;d++)(!c||c&&this.children[d].exists)&&a.call(b,this.children[d]);else{for(var e=[null],d=3;d<arguments.length;d++)e.push(arguments[d]);for(var d=0;d<this.children.length;d++)(!c||c&&this.children[d].exists)&&(e[0]=this.children[d],a.apply(b,e))}},c.Group.prototype.forEachExists=function(a,b){var d;if(arguments.length>2){d=[null];for(var e=2;e<arguments.length;e++)d.push(arguments[e])}this.iterate("exists",!0,c.Group.RETURN_TOTAL,a,b,d)},c.Group.prototype.forEachAlive=function(a,b){var d;if(arguments.length>2){d=[null];for(var e=2;e<arguments.length;e++)d.push(arguments[e])}this.iterate("alive",!0,c.Group.RETURN_TOTAL,a,b,d)},c.Group.prototype.forEachDead=function(a,b){var d;if(arguments.length>2){d=[null];for(var e=2;e<arguments.length;e++)d.push(arguments[e])}this.iterate("alive",!1,c.Group.RETURN_TOTAL,a,b,d)},c.Group.prototype.sort=function(a,b){this.children.length<2||(void 0===a&&(a="z"),void 0===b&&(b=c.Group.SORT_ASCENDING),this._sortProperty=a,this.children.sort(b===c.Group.SORT_ASCENDING?this.ascendingSortHandler.bind(this):this.descendingSortHandler.bind(this)),this.updateZ())},c.Group.prototype.customSort=function(a,b){this.children.length<2||(this.children.sort(a.bind(b)),this.updateZ())},c.Group.prototype.ascendingSortHandler=function(a,b){return a[this._sortProperty]<b[this._sortProperty]?-1:a[this._sortProperty]>b[this._sortProperty]?1:a.z<b.z?-1:1},c.Group.prototype.descendingSortHandler=function(a,b){return a[this._sortProperty]<b[this._sortProperty]?1:a[this._sortProperty]>b[this._sortProperty]?-1:0},c.Group.prototype.iterate=function(a,b,d,e,f,g){if(d===c.Group.RETURN_TOTAL&&0===this.children.length)return 0;for(var h=0,i=0;i<this.children.length;i++)if(this.children[i][a]===b&&(h++,e&&(g?(g[0]=this.children[i],e.apply(f,g)):e.call(f,this.children[i])),d===c.Group.RETURN_CHILD))return this.children[i];return d===c.Group.RETURN_TOTAL?h:null},c.Group.prototype.getFirstExists=function(a){return"boolean"!=typeof a&&(a=!0),this.iterate("exists",a,c.Group.RETURN_CHILD)},c.Group.prototype.getFirstAlive=function(){return this.iterate("alive",!0,c.Group.RETURN_CHILD)},c.Group.prototype.getFirstDead=function(){return this.iterate("alive",!1,c.Group.RETURN_CHILD)},c.Group.prototype.getTop=function(){return this.children.length>0?this.children[this.children.length-1]:void 0},c.Group.prototype.getBottom=function(){return this.children.length>0?this.children[0]:void 0},c.Group.prototype.countLiving=function(){return this.iterate("alive",!0,c.Group.RETURN_TOTAL)},c.Group.prototype.countDead=function(){return this.iterate("alive",!1,c.Group.RETURN_TOTAL)},c.Group.prototype.getRandom=function(a,b){return 0===this.children.length?null:(a=a||0,b=b||this.children.length,c.ArrayUtils.getRandomItem(this.children,a,b))},c.Group.prototype.remove=function(a,b,c){if(void 0===b&&(b=!1),void 0===c&&(c=!1),0===this.children.length||-1===this.children.indexOf(a))return!1;c||!a.events||a.destroyPhase||a.events.onRemovedFromGroup$dispatch(a,this);var d=this.removeChild(a);return this.removeFromHash(a),this.updateZ(),this.cursor===a&&this.next(),b&&d&&d.destroy(!0),!0},c.Group.prototype.moveAll=function(a,b){if(void 0===b&&(b=!1),this.children.length>0&&a instanceof c.Group){do a.add(this.children[0],b);while(this.children.length>0);this.hash=[],this.cursor=null}return a},c.Group.prototype.removeAll=function(a,b){if(void 0===a&&(a=!1),void 0===b&&(b=!1),0!==this.children.length){do{!b&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var c=this.removeChild(this.children[0]);this.removeFromHash(c),a&&c&&c.destroy(!0)}while(this.children.length>0);this.hash=[],this.cursor=null}},c.Group.prototype.removeBetween=function(a,b,c,d){if(void 0===b&&(b=this.children.length-1),void 0===c&&(c=!1),void 0===d&&(d=!1),0!==this.children.length){if(a>b||0>a||b>this.children.length)return!1;for(var e=b;e>=a;){!d&&this.children[e].events&&this.children[e].events.onRemovedFromGroup$dispatch(this.children[e],this);var f=this.removeChild(this.children[e]);this.removeFromHash(f),c&&f&&f.destroy(!0),this.cursor===this.children[e]&&(this.cursor=null),e--}this.updateZ()}},c.Group.prototype.destroy=function(a,b){null===this.game||this.ignoreDestroy||(void 0===a&&(a=!0),void 0===b&&(b=!1),this.onDestroy.dispatch(this,a,b),this.removeAll(a),this.cursor=null,this.filters=null,this.pendingDestroy=!1,b||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(c.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,c.Group.RETURN_TOTAL)}}),Object.defineProperty(c.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(c.Group.prototype,"angle",{get:function(){return c.Math.radToDeg(this.rotation)},set:function(a){this.rotation=c.Math.degToRad(a)}}),c.World=function(a){c.Group.call(this,a,null,"__world",!1),this.bounds=new c.Rectangle(0,0,a.width,a.height),this.camera=null,this._definedSize=!1,this._width=a.width,this._height=a.height,this.game.state.onStateChange.add(this.stateChange,this)
-},c.World.prototype=Object.create(c.Group.prototype),c.World.prototype.constructor=c.World,c.World.prototype.boot=function(){this.camera=new c.Camera(this.game,0,0,0,this.game.width,this.game.height),this.camera.displayObject=this,this.camera.scale=this.scale,this.game.camera=this.camera,this.game.stage.addChild(this)},c.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},c.World.prototype.setBounds=function(a,b,c,d){this._definedSize=!0,this._width=c,this._height=d,this.bounds.setTo(a,b,c,d),this.x=a,this.y=b,this.camera.bounds&&this.camera.bounds.setTo(a,b,Math.max(c,this.game.width),Math.max(d,this.game.height)),this.game.physics.setBoundsToWorld()},c.World.prototype.resize=function(a,b){this._definedSize&&(a<this._width&&(a=this._width),b<this._height&&(b=this._height)),this.bounds.width=a,this.bounds.height=b,this.game.camera.setBoundsToWorld(),this.game.physics.setBoundsToWorld()},c.World.prototype.shutdown=function(){this.destroy(!0,!0)},c.World.prototype.wrap=function(a,b,c,d,e){void 0===b&&(b=0),void 0===c&&(c=!1),void 0===d&&(d=!0),void 0===e&&(e=!0),c?(a.getBounds(),d&&(a.x+a._currentBounds.width<this.bounds.x?a.x=this.bounds.right:a.x>this.bounds.right&&(a.x=this.bounds.left)),e&&(a.y+a._currentBounds.height<this.bounds.top?a.y=this.bounds.bottom:a.y>this.bounds.bottom&&(a.y=this.bounds.top))):(d&&a.x+b<this.bounds.x?a.x=this.bounds.right+b:d&&a.x-b>this.bounds.right&&(a.x=this.bounds.left-b),e&&a.y+b<this.bounds.top?a.y=this.bounds.bottom+b:e&&a.y-b>this.bounds.bottom&&(a.y=this.bounds.top-b))},Object.defineProperty(c.World.prototype,"width",{get:function(){return this.bounds.width},set:function(a){a<this.game.width&&(a=this.game.width),this.bounds.width=a,this._width=a,this._definedSize=!0}}),Object.defineProperty(c.World.prototype,"height",{get:function(){return this.bounds.height},set:function(a){a<this.game.height&&(a=this.game.height),this.bounds.height=a,this._height=a,this._definedSize=!0}}),Object.defineProperty(c.World.prototype,"centerX",{get:function(){return this.bounds.halfWidth}}),Object.defineProperty(c.World.prototype,"centerY",{get:function(){return this.bounds.halfHeight}}),Object.defineProperty(c.World.prototype,"randomX",{get:function(){return this.bounds.x<0?this.game.rnd.between(this.bounds.x,this.bounds.width-Math.abs(this.bounds.x)):this.game.rnd.between(this.bounds.x,this.bounds.width)}}),Object.defineProperty(c.World.prototype,"randomY",{get:function(){return this.bounds.y<0?this.game.rnd.between(this.bounds.y,this.bounds.height-Math.abs(this.bounds.y)):this.game.rnd.between(this.bounds.y,this.bounds.height)}}),c.FlexGrid=function(a,b,d){this.game=a.game,this.manager=a,this.width=b,this.height=d,this.boundsCustom=new c.Rectangle(0,0,b,d),this.boundsFluid=new c.Rectangle(0,0,b,d),this.boundsFull=new c.Rectangle(0,0,b,d),this.boundsNone=new c.Rectangle(0,0,b,d),this.positionCustom=new c.Point(0,0),this.positionFluid=new c.Point(0,0),this.positionFull=new c.Point(0,0),this.positionNone=new c.Point(0,0),this.scaleCustom=new c.Point(1,1),this.scaleFluid=new c.Point(1,1),this.scaleFluidInversed=new c.Point(1,1),this.scaleFull=new c.Point(1,1),this.scaleNone=new c.Point(1,1),this.customWidth=0,this.customHeight=0,this.customOffsetX=0,this.customOffsetY=0,this.ratioH=b/d,this.ratioV=d/b,this.multiplier=0,this.layers=[]},c.FlexGrid.prototype={setSize:function(a,b){this.width=a,this.height=b,this.ratioH=a/b,this.ratioV=b/a,this.scaleNone=new c.Point(1,1),this.boundsNone.width=this.width,this.boundsNone.height=this.height,this.refresh()},createCustomLayer:function(a,b,d,e){void 0===e&&(e=!0),this.customWidth=a,this.customHeight=b,this.boundsCustom.width=a,this.boundsCustom.height=b;var f=new c.FlexLayer(this,this.positionCustom,this.boundsCustom,this.scaleCustom);return e&&this.game.world.add(f),this.layers.push(f),"undefined"!=typeof d&&null!==typeof d&&f.addMultiple(d),f},createFluidLayer:function(a,b){void 0===b&&(b=!0);var d=new c.FlexLayer(this,this.positionFluid,this.boundsFluid,this.scaleFluid);return b&&this.game.world.add(d),this.layers.push(d),"undefined"!=typeof a&&null!==typeof a&&d.addMultiple(a),d},createFullLayer:function(a){var b=new c.FlexLayer(this,this.positionFull,this.boundsFull,this.scaleFluid);return this.game.world.add(b),this.layers.push(b),"undefined"!=typeof a&&b.addMultiple(a),b},createFixedLayer:function(a){var b=new c.FlexLayer(this,this.positionNone,this.boundsNone,this.scaleNone);return this.game.world.add(b),this.layers.push(b),"undefined"!=typeof a&&b.addMultiple(a),b},reset:function(){for(var a=this.layers.length;a--;)this.layers[a].persist||(this.layers[a].position=null,this.layers[a].scale=null,this.layers.slice(a,1))},onResize:function(a,b){this.ratioH=a/b,this.ratioV=b/a,this.refresh(a,b)},refresh:function(){this.multiplier=Math.min(this.manager.height/this.height,this.manager.width/this.width),this.boundsFluid.width=Math.round(this.width*this.multiplier),this.boundsFluid.height=Math.round(this.height*this.multiplier),this.scaleFluid.set(this.boundsFluid.width/this.width,this.boundsFluid.height/this.height),this.scaleFluidInversed.set(this.width/this.boundsFluid.width,this.height/this.boundsFluid.height),this.scaleFull.set(this.boundsFull.width/this.width,this.boundsFull.height/this.height),this.boundsFull.width=Math.round(this.manager.width*this.scaleFluidInversed.x),this.boundsFull.height=Math.round(this.manager.height*this.scaleFluidInversed.y),this.boundsFluid.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.boundsNone.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.positionFluid.set(this.boundsFluid.x,this.boundsFluid.y),this.positionNone.set(this.boundsNone.x,this.boundsNone.y)},fitSprite:function(a){this.manager.scaleSprite(a),a.x=this.manager.bounds.centerX,a.y=this.manager.bounds.centerY},debug:function(){this.game.debug.text(this.boundsFluid.width+" x "+this.boundsFluid.height,this.boundsFluid.x+4,this.boundsFluid.y+16),this.game.debug.geom(this.boundsFluid,"rgba(255,0,0,0.9",!1)}},c.FlexGrid.prototype.constructor=c.FlexGrid,c.FlexLayer=function(a,b,d,e){c.Group.call(this,a.game,null,"__flexLayer"+a.game.rnd.uuid(),!1),this.manager=a.manager,this.grid=a,this.persist=!1,this.position=b,this.bounds=d,this.scale=e,this.topLeft=d.topLeft,this.topMiddle=new c.Point(d.halfWidth,0),this.topRight=d.topRight,this.bottomLeft=d.bottomLeft,this.bottomMiddle=new c.Point(d.halfWidth,d.bottom),this.bottomRight=d.bottomRight},c.FlexLayer.prototype=Object.create(c.Group.prototype),c.FlexLayer.prototype.constructor=c.FlexLayer,c.FlexLayer.prototype.resize=function(){},c.FlexLayer.prototype.debug=function(){this.game.debug.text(this.bounds.width+" x "+this.bounds.height,this.bounds.x+4,this.bounds.y+16),this.game.debug.geom(this.bounds,"rgba(0,0,255,0.9",!1),this.game.debug.geom(this.topLeft,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topMiddle,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topRight,"rgba(255,255,255,0.9")},c.ScaleManager=function(a,b,d){this.game=a,this.dom=c.DOM,this.grid=null,this.width=0,this.height=0,this.minWidth=null,this.maxWidth=null,this.minHeight=null,this.maxHeight=null,this.offset=new c.Point,this.forceLandscape=!1,this.forcePortrait=!1,this.incorrectOrientation=!1,this._pageAlignHorizontally=!1,this._pageAlignVertically=!1,this.onOrientationChange=new c.Signal,this.enterIncorrectOrientation=new c.Signal,this.leaveIncorrectOrientation=new c.Signal,this.fullScreenTarget=null,this._createdFullScreenTarget=null,this.onFullScreenInit=new c.Signal,this.onFullScreenChange=new c.Signal,this.onFullScreenError=new c.Signal,this.screenOrientation=this.dom.getScreenOrientation(),this.scaleFactor=new c.Point(1,1),this.scaleFactorInversed=new c.Point(1,1),this.margin={left:0,top:0,right:0,bottom:0,x:0,y:0},this.bounds=new c.Rectangle,this.aspectRatio=0,this.sourceAspectRatio=0,this.event=null,this.windowConstraints={right:"layout",bottom:""},this.compatibility={supportsFullScreen:!1,orientationFallback:null,noMargins:!1,scrollTo:null,forceMinimumDocumentHeight:!1,canExpandParent:!0,clickTrampoline:""},this._scaleMode=c.ScaleManager.NO_SCALE,this._fullScreenScaleMode=c.ScaleManager.NO_SCALE,this.parentIsWindow=!1,this.parentNode=null,this.parentScaleFactor=new c.Point(1,1),this.trackParentInterval=2e3,this.onSizeChange=new c.Signal,this.onResize=null,this.onResizeContext=null,this._pendingScaleMode=null,this._fullScreenRestore=null,this._gameSize=new c.Rectangle,this._userScaleFactor=new c.Point(1,1),this._userScaleTrim=new c.Point(0,0),this._lastUpdate=0,this._updateThrottle=0,this._updateThrottleReset=100,this._parentBounds=new c.Rectangle,this._tempBounds=new c.Rectangle,this._lastReportedCanvasSize=new c.Rectangle,this._lastReportedGameSize=new c.Rectangle,this._booted=!1,a.config&&this.parseConfig(a.config),this.setupScale(b,d)},c.ScaleManager.EXACT_FIT=0,c.ScaleManager.NO_SCALE=1,c.ScaleManager.SHOW_ALL=2,c.ScaleManager.RESIZE=3,c.ScaleManager.USER_SCALE=4,c.ScaleManager.prototype={boot:function(){var a=this.compatibility;a.supportsFullScreen=this.game.device.fullscreen&&!this.game.device.cocoonJS,this.game.device.iPad||this.game.device.webApp||this.game.device.desktop||(a.scrollTo=this.game.device.android&&!this.game.device.chrome?new c.Point(0,1):new c.Point(0,0)),this.game.device.desktop?(a.orientationFallback="screen",a.clickTrampoline="when-not-mouse"):(a.orientationFallback="",a.clickTrampoline="");var b=this;this._orientationChange=function(a){return b.orientationChange(a)},this._windowResize=function(a){return b.windowResize(a)},window.addEventListener("orientationchange",this._orientationChange,!1),window.addEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(this._fullScreenChange=function(a){return b.fullScreenChange(a)},this._fullScreenError=function(a){return b.fullScreenError(a)},document.addEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.addEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.addEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.addEventListener("fullscreenchange",this._fullScreenChange,!1),document.addEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.addEventListener("mozfullscreenerror",this._fullScreenError,!1),document.addEventListener("MSFullscreenError",this._fullScreenError,!1),document.addEventListener("fullscreenerror",this._fullScreenError,!1)),this.game.onResume.add(this._gameResumed,this),this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.setGameSize(this.game.width,this.game.height),this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.grid=new c.FlexGrid(this,this.width,this.height),this._booted=!0,this._pendingScaleMode&&(this.scaleMode=this._pendingScaleMode,this._pendingScaleMode=null)},parseConfig:function(a){a.scaleMode&&(this._booted?this.scaleMode=a.scaleMode:this._pendingScaleMode=a.scaleMode),a.fullScreenScaleMode&&(this.fullScreenScaleMode=a.fullScreenScaleMode),a.fullScreenTarget&&(this.fullScreenTarget=a.fullScreenTarget)},setupScale:function(a,b){var d,e=new c.Rectangle;""!==this.game.parent&&("string"==typeof this.game.parent?d=document.getElementById(this.game.parent):this.game.parent&&1===this.game.parent.nodeType&&(d=this.game.parent)),d?(this.parentNode=d,this.parentIsWindow=!1,this.getParentBounds(this._parentBounds),e.width=this._parentBounds.width,e.height=this._parentBounds.height,this.offset.set(this._parentBounds.x,this._parentBounds.y)):(this.parentNode=null,this.parentIsWindow=!0,e.width=this.dom.visualBounds.width,e.height=this.dom.visualBounds.height,this.offset.set(0,0));var f=0,g=0;"number"==typeof a?f=a:(this.parentScaleFactor.x=parseInt(a,10)/100,f=e.width*this.parentScaleFactor.x),"number"==typeof b?g=b:(this.parentScaleFactor.y=parseInt(b,10)/100,g=e.height*this.parentScaleFactor.y),this._gameSize.setTo(0,0,f,g),this.updateDimensions(f,g,!1)},_gameResumed:function(){this.queueUpdate(!0)},setGameSize:function(a,b){this._gameSize.setTo(0,0,a,b),this.currentScaleMode!==c.ScaleManager.RESIZE&&this.updateDimensions(a,b,!0),this.queueUpdate(!0)},setUserScale:function(a,b,c,d){this._userScaleFactor.setTo(a,b),this._userScaleTrim.setTo(0|c,0|d),this.queueUpdate(!0)},setResizeCallback:function(a,b){this.onResize=a,this.onResizeContext=b},signalSizeChange:function(){if(!c.Rectangle.sameDimensions(this,this._lastReportedCanvasSize)||!c.Rectangle.sameDimensions(this.game,this._lastReportedGameSize)){var a=this.width,b=this.height;this._lastReportedCanvasSize.setTo(0,0,a,b),this._lastReportedGameSize.setTo(0,0,this.game.width,this.game.height),this.grid.onResize(a,b),this.onSizeChange.dispatch(this,a,b),this.currentScaleMode===c.ScaleManager.RESIZE&&(this.game.state.resize(a,b),this.game.load.resize(a,b))}},setMinMax:function(a,b,c,d){this.minWidth=a,this.minHeight=b,"undefined"!=typeof c&&(this.maxWidth=c),"undefined"!=typeof d&&(this.maxHeight=d)},preUpdate:function(){if(!(this.game.time.time<this._lastUpdate+this._updateThrottle)){var a=this._updateThrottle;this._updateThrottleReset=a>=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var b=this._parentBounds.width,d=this._parentBounds.height,e=this.getParentBounds(this._parentBounds),f=e.width!==b||e.height!==d,g=this.updateOrientationState();(f||g)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,e),this.updateLayout(),this.signalSizeChange());var h=2*this._updateThrottle;this._updateThrottle<a&&(h=Math.min(a,this._updateThrottleReset)),this._updateThrottle=c.Math.clamp(h,25,this.trackParentInterval),this._lastUpdate=this.game.time.time}},pauseUpdate:function(){this.preUpdate(),this._updateThrottle=this.trackParentInterval},updateDimensions:function(a,b,c){this.width=a*this.parentScaleFactor.x,this.height=b*this.parentScaleFactor.y,this.game.width=this.width,this.game.height=this.height,this.sourceAspectRatio=this.width/this.height,this.updateScalingAndBounds(),c&&(this.game.renderer.resize(this.width,this.height),this.game.camera.setSize(this.width,this.height),this.game.world.resize(this.width,this.height))},updateScalingAndBounds:function(){this.scaleFactor.x=this.game.width/this.width,this.scaleFactor.y=this.game.height/this.height,this.scaleFactorInversed.x=this.width/this.game.width,this.scaleFactorInversed.y=this.height/this.game.height,this.aspectRatio=this.width/this.height,this.game.canvas&&this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.game.input&&this.game.input.scale&&this.game.input.scale.setTo(this.scaleFactor.x,this.scaleFactor.y)},forceOrientation:function(a,b){void 0===b&&(b=!1),this.forceLandscape=a,this.forcePortrait=b,this.queueUpdate(!0)},classifyOrientation:function(a){return"portrait-primary"===a||"portrait-secondary"===a?"portrait":"landscape-primary"===a||"landscape-secondary"===a?"landscape":null},updateOrientationState:function(){var a=this.screenOrientation,b=this.incorrectOrientation;this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.incorrectOrientation=this.forceLandscape&&!this.isLandscape||this.forcePortrait&&!this.isPortrait;var c=a!==this.screenOrientation,d=b!==this.incorrectOrientation;return d&&(this.incorrectOrientation?this.enterIncorrectOrientation.dispatch():this.leaveIncorrectOrientation.dispatch()),(c||d)&&this.onOrientationChange.dispatch(this,a,b),c||d},orientationChange:function(a){this.event=a,this.queueUpdate(!0)},windowResize:function(a){this.event=a,this.queueUpdate(!0)},scrollTop:function(){var a=this.compatibility.scrollTo;a&&window.scrollTo(a.x,a.y)},refresh:function(){this.scrollTop(),this.queueUpdate(!0)},updateLayout:function(){var a=this.currentScaleMode;if(a===c.ScaleManager.RESIZE)return void this.reflowGame();if(this.scrollTop(),this.compatibility.forceMinimumDocumentHeight&&(document.documentElement.style.minHeight=window.innerHeight+"px"),this.incorrectOrientation?this.setMaximum():a===c.ScaleManager.EXACT_FIT?this.setExactFit():a===c.ScaleManager.SHOW_ALL?!this.isFullScreen&&this.boundingParent&&this.compatibility.canExpandParent?(this.setShowAll(!0),this.resetCanvas(),this.setShowAll()):this.setShowAll():a===c.ScaleManager.NO_SCALE?(this.width=this.game.width,this.height=this.game.height):a===c.ScaleManager.USER_SCALE&&(this.width=this.game.width*this._userScaleFactor.x-this._userScaleTrim.x,this.height=this.game.height*this._userScaleFactor.y-this._userScaleTrim.y),!this.compatibility.canExpandParent&&(a===c.ScaleManager.SHOW_ALL||a===c.ScaleManager.USER_SCALE)){var b=this.getParentBounds(this._tempBounds);this.width=Math.min(this.width,b.width),this.height=Math.min(this.height,b.height)}this.width=0|this.width,this.height=0|this.height,this.reflowCanvas()},getParentBounds:function(a){var b=a||new c.Rectangle,d=this.boundingParent,e=this.dom.visualBounds,f=this.dom.layoutBounds;if(d){var g=d.getBoundingClientRect();b.setTo(g.left,g.top,g.width,g.height);var h=this.windowConstraints;if(h.right){var i="layout"===h.right?f:e;b.right=Math.min(b.right,i.width)}if(h.bottom){var i="layout"===h.bottom?f:e;b.bottom=Math.min(b.bottom,i.height)}}else b.setTo(0,0,e.width,e.height);return b.setTo(Math.round(b.x),Math.round(b.y),Math.round(b.width),Math.round(b.height)),b},alignCanvas:function(a,b){var c=this.getParentBounds(this._tempBounds),d=this.game.canvas,e=this.margin;if(a){e.left=e.right=0;var f=d.getBoundingClientRect();if(this.width<c.width&&!this.incorrectOrientation){var g=f.left-c.x,h=c.width/2-this.width/2;h=Math.max(h,0);var i=h-g;e.left=Math.round(i)}d.style.marginLeft=e.left+"px",0!==e.left&&(e.right=-(c.width-f.width-e.left),d.style.marginRight=e.right+"px")}if(b){e.top=e.bottom=0;var f=d.getBoundingClientRect();if(this.height<c.height&&!this.incorrectOrientation){var g=f.top-c.y,h=c.height/2-this.height/2;h=Math.max(h,0);var i=h-g;e.top=Math.round(i)}d.style.marginTop=e.top+"px",0!==e.top&&(e.bottom=-(c.height-f.height-e.top),d.style.marginBottom=e.bottom+"px")}e.x=e.left,e.y=e.top},reflowGame:function(){this.resetCanvas("","");var a=this.getParentBounds(this._tempBounds);this.updateDimensions(a.width,a.height,!0)},reflowCanvas:function(){this.incorrectOrientation||(this.width=c.Math.clamp(this.width,this.minWidth||0,this.maxWidth||this.width),this.height=c.Math.clamp(this.height,this.minHeight||0,this.maxHeight||this.height)),this.resetCanvas(),this.compatibility.noMargins||(this.isFullScreen&&this._createdFullScreenTarget?this.alignCanvas(!0,!0):this.alignCanvas(this.pageAlignHorizontally,this.pageAlignVertically)),this.updateScalingAndBounds()},resetCanvas:function(a,b){void 0===a&&(a=this.width+"px"),void 0===b&&(b=this.height+"px");var c=this.game.canvas;this.compatibility.noMargins||(c.style.marginLeft="",c.style.marginTop="",c.style.marginRight="",c.style.marginBottom=""),c.style.width=a,c.style.height=b},queueUpdate:function(a){a&&(this._parentBounds.width=0,this._parentBounds.height=0),this._updateThrottle=this._updateThrottleReset},reset:function(a){a&&this.grid.reset()},setMaximum:function(){this.width=this.dom.visualBounds.width,this.height=this.dom.visualBounds.height},setShowAll:function(a){var b,c=this.getParentBounds(this._tempBounds),d=c.width,e=c.height;b=a?Math.max(e/this.game.height,d/this.game.width):Math.min(e/this.game.height,d/this.game.width),this.width=Math.round(this.game.width*b),this.height=Math.round(this.game.height*b)},setExactFit:function(){var a=this.getParentBounds(this._tempBounds);this.width=a.width,this.height=a.height,this.isFullScreen||(this.maxWidth&&(this.width=Math.min(this.width,this.maxWidth)),this.maxHeight&&(this.height=Math.min(this.height,this.maxHeight)))},createFullScreenTarget:function(){var a=document.createElement("div");return a.style.margin="0",a.style.padding="0",a.style.background="#000",a},startFullScreen:function(a,b){if(this.isFullScreen)return!1;if(!this.compatibility.supportsFullScreen){var d=this;return void setTimeout(function(){d.fullScreenError()},10)}if("when-not-mouse"===this.compatibility.clickTrampoline){var e=this.game.input;if(e.activePointer&&e.activePointer!==e.mousePointer&&(b||b!==!1))return void e.activePointer.addClickTrampoline("startFullScreen",this.startFullScreen,this,[a,!1])}"undefined"!=typeof a&&this.game.renderType===c.CANVAS&&(this.game.stage.smoothed=a);var f=this.fullScreenTarget;f||(this.cleanupCreatedTarget(),this._createdFullScreenTarget=this.createFullScreenTarget(),f=this._createdFullScreenTarget);var g={targetElement:f};if(this.onFullScreenInit.dispatch(this,g),this._createdFullScreenTarget){var h=this.game.canvas,i=h.parentNode;i.insertBefore(f,h),f.appendChild(h)}return this.game.device.fullscreenKeyboard?f[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT):f[this.game.device.requestFullscreen](),!0},stopFullScreen:function(){return this.isFullScreen&&this.compatibility.supportsFullScreen?(document[this.game.device.cancelFullscreen](),!0):!1},cleanupCreatedTarget:function(){var a=this._createdFullScreenTarget;if(a&&a.parentNode){var b=a.parentNode;b.insertBefore(this.game.canvas,a),b.removeChild(a)}this._createdFullScreenTarget=null},prepScreenMode:function(a){var b=!!this._createdFullScreenTarget,d=this._createdFullScreenTarget||this.fullScreenTarget;a?(b||this.fullScreenScaleMode===c.ScaleManager.EXACT_FIT)&&d!==this.game.canvas&&(this._fullScreenRestore={targetWidth:d.style.width,targetHeight:d.style.height},d.style.width="100%",d.style.height="100%"):(this._fullScreenRestore&&(d.style.width=this._fullScreenRestore.targetWidth,d.style.height=this._fullScreenRestore.targetHeight,this._fullScreenRestore=null),this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.resetCanvas())},fullScreenChange:function(a){this.event=a,this.isFullScreen?(this.prepScreenMode(!0),this.updateLayout(),this.queueUpdate(!0),this.enterFullScreen.dispatch(this.width,this.height)):(this.prepScreenMode(!1),this.cleanupCreatedTarget(),this.updateLayout(),this.queueUpdate(!0),this.leaveFullScreen.dispatch(this.width,this.height)),this.onFullScreenChange.dispatch(this)},fullScreenError:function(a){this.event=a,this.cleanupCreatedTarget(),console.warn("Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API"),this.onFullScreenError.dispatch(this)},scaleSprite:function(a,b,c,d){if(void 0===b&&(b=this.width),void 0===c&&(c=this.height),void 0===d&&(d=!1),!a||!a.scale)return a;if(a.scale.x=1,a.scale.y=1,a.width<=0||a.height<=0||0>=b||0>=c)return a;var e=b,f=a.height*b/a.width,g=a.width*c/a.height,h=c,i=g>b;return i=i?d:!d,i?(a.width=Math.floor(e),a.height=Math.floor(f)):(a.width=Math.floor(g),a.height=Math.floor(h)),a},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},c.ScaleManager.prototype.constructor=c.ScaleManager,Object.defineProperty(c.ScaleManager.prototype,"boundingParent",{get:function(){if(this.parentIsWindow||this.isFullScreen&&!this._createdFullScreenTarget)return null;var a=this.game.canvas&&this.game.canvas.parentNode;return a||null}}),Object.defineProperty(c.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(a){return a!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=a),this._scaleMode}}),Object.defineProperty(c.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(a){return a!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=a,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=a),this._fullScreenScaleMode}}),Object.defineProperty(c.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(c.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(a){a!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=a,this.queueUpdate(!0))}}),Object.defineProperty(c.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(a){a!==this._pageAlignVertically&&(this._pageAlignVertically=a,this.queueUpdate(!0))}}),Object.defineProperty(c.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(c.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(c.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(c.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(c.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),c.Game=function(a,b,d,e,f,g,h,i){return this.id=c.GAMES.push(this)-1,this.config=null,this.physicsConfig=i,this.parent="",this.width=800,this.height=600,this.resolution=1,this._width=800,this._height=600,this.transparent=!1,this.antialias=!0,this.preserveDrawingBuffer=!1,this.renderer=null,this.renderType=c.AUTO,this.state=null,this.isBooted=!1,this.isRunning=!1,this.raf=null,this.add=null,this.make=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.net=null,this.scale=null,this.sound=null,this.stage=null,this.time=null,this.tweens=null,this.world=null,this.physics=null,this.plugins=null,this.rnd=null,this.device=c.Device,this.camera=null,this.canvas=null,this.context=null,this.debug=null,this.particles=null,this.create=null,this.lockRender=!1,this.stepping=!1,this.pendingStep=!1,this.stepCount=0,this.onPause=null,this.onResume=null,this.onBlur=null,this.onFocus=null,this._paused=!1,this._codePaused=!1,this.currentUpdateID=0,this.updatesThisFrame=1,this._deltaTime=0,this._lastCount=0,this._spiraling=0,this._kickstart=!0,this.fpsProblemNotifier=new c.Signal,this.forceSingleUpdate=!1,this._nextFpsNotification=0,1===arguments.length&&"object"==typeof arguments[0]?this.parseConfig(arguments[0]):(this.config={enableDebug:!0},"undefined"!=typeof a&&(this._width=a),"undefined"!=typeof b&&(this._height=b),"undefined"!=typeof d&&(this.renderType=d),"undefined"!=typeof e&&(this.parent=e),"undefined"!=typeof g&&(this.transparent=g),"undefined"!=typeof h&&(this.antialias=h),this.rnd=new c.RandomDataGenerator([(Date.now()*Math.random()).toString()]),this.state=new c.StateManager(this,f)),this.device.whenReady(this.boot,this),this},c.Game.prototype={parseConfig:function(a){this.config=a,void 0===a.enableDebug&&(this.config.enableDebug=!0),a.width&&(this._width=a.width),a.height&&(this._height=a.height),a.renderer&&(this.renderType=a.renderer),a.parent&&(this.parent=a.parent),a.transparent&&(this.transparent=a.transparent),a.antialias&&(this.antialias=a.antialias),a.resolution&&(this.resolution=a.resolution),a.preserveDrawingBuffer&&(this.preserveDrawingBuffer=a.preserveDrawingBuffer),a.physicsConfig&&(this.physicsConfig=a.physicsConfig);var b=[(Date.now()*Math.random()).toString()];a.seed&&(b=a.seed),this.rnd=new c.RandomDataGenerator(b);var d=null;a.state&&(d=a.state),this.state=new c.StateManager(this,d)},boot:function(){this.isBooted||(this.onPause=new c.Signal,this.onResume=new c.Signal,this.onBlur=new c.Signal,this.onFocus=new c.Signal,this.isBooted=!0,this.math=c.Math,this.scale=new c.ScaleManager(this,this._width,this._height),this.stage=new c.Stage(this),this.setUpRenderer(),this.world=new c.World(this),this.add=new c.GameObjectFactory(this),this.make=new c.GameObjectCreator(this),this.cache=new c.Cache(this),this.load=new c.Loader(this),this.time=new c.Time(this),this.tweens=new c.TweenManager(this),this.input=new c.Input(this),this.sound=new c.SoundManager(this),this.physics=new c.Physics(this,this.physicsConfig),this.particles=new c.Particles(this),this.create=new c.Create(this),this.plugins=new c.PluginManager(this),this.net=new c.Net(this),this.time.boot(),this.stage.boot(),this.world.boot(),this.scale.boot(),this.input.boot(),this.sound.boot(),this.state.boot(),this.config.enableDebug?(this.debug=new c.Utils.Debug(this),this.debug.boot()):this.debug={preUpdate:function(){},update:function(){},reset:function(){}},this.showDebugHeader(),this.isRunning=!0,this.raf=this.config&&this.config.forceSetTimeOut?new c.RequestAnimationFrame(this,this.config.forceSetTimeOut):new c.RequestAnimationFrame(this,!1),this._kickstart=!0,window.focus&&(!window.PhaserGlobal||window.PhaserGlobal&&!window.PhaserGlobal.stopFocus)&&window.focus(),this.raf.start())},showDebugHeader:function(){if(!window.PhaserGlobal||!window.PhaserGlobal.hideBanner){var a=c.VERSION,b="Canvas",d="HTML Audio",e=1;if(this.renderType===c.WEBGL?(b="WebGL",e++):this.renderType==c.HEADLESS&&(b="Headless"),this.device.webAudio&&(d="WebAudio",e++),this.device.chrome){for(var f=["%c %c %c Phaser v"+a+" | Pixi.js "+PIXI.VERSION+" | "+b+" | "+d+"  %c %c %c http://phaser.io %c♥%c♥%c♥","background: #9854d8","background: #6c2ca7","color: #ffffff; background: #450f78;","background: #6c2ca7","background: #9854d8","background: #ffffff"],g=0;3>g;g++)f.push(e>g?"color: #ff2424; background: #fff":"color: #959595; background: #fff");console.log.apply(console,f)}else window.console&&console.log("Phaser v"+a+" | Pixi.js "+PIXI.VERSION+" | "+b+" | "+d+" | http://phaser.io")}},setUpRenderer:function(){if(this.canvas=this.config.canvasID?c.Canvas.create(this.width,this.height,this.config.canvasID):c.Canvas.create(this.width,this.height),this.config.canvasStyle?this.canvas.style=this.config.canvasStyle:this.canvas.style["-webkit-full-screen"]="width: 100%; height: 100%",this.device.cocoonJS&&(this.canvas.screencanvas=this.renderType===c.CANVAS?!0:!1),this.renderType===c.HEADLESS||this.renderType===c.CANVAS||this.renderType===c.AUTO&&this.device.webGL===!1){if(!this.device.canvas)throw new Error("Phaser.Game - cannot create Canvas or WebGL context, aborting.");this.renderType===c.AUTO&&(this.renderType=c.CANVAS),this.renderer=new PIXI.CanvasRenderer(this.width,this.height,{view:this.canvas,transparent:this.transparent,resolution:this.resolution,clearBeforeRender:!0}),this.context=this.renderer.context}else this.renderType=c.WEBGL,this.renderer=new PIXI.WebGLRenderer(this.width,this.height,{view:this.canvas,transparent:this.transparent,resolution:this.resolution,antialias:this.antialias,preserveDrawingBuffer:this.preserveDrawingBuffer}),this.context=null,this.canvas.addEventListener("webglcontextlost",this.contextLost.bind(this),!1),this.canvas.addEventListener("webglcontextrestored",this.contextRestored.bind(this),!1);this.renderType!==c.HEADLESS&&(this.stage.smoothed=this.antialias,c.Canvas.addToDOM(this.canvas,this.parent,!1),c.Canvas.setTouchAction(this.canvas))},contextLost:function(a){a.preventDefault(),this.renderer.contextLost=!0},contextRestored:function(){this.renderer.initContext(),this.cache.clearGLTextures(),this.renderer.contextLost=!1
-},update:function(a){if(this.time.update(a),this._kickstart)return this.updateLogic(1/this.time.desiredFps),this.stage.updateTransform(),this.updateRender(this.time.slowMotion*this.time.desiredFps),void(this._kickstart=!1);if(this._spiraling>1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.updateRender(this.time.slowMotion*this.time.desiredFps);else{var b=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*b,this.time.elapsed),0);var c=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/b),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame));this._deltaTime>=b&&(this._deltaTime-=b,this.currentUpdateID=c,this.updateLogic(1/this.time.desiredFps),this.stage.updateTransform(),c++,!this.forceSingleUpdate||1!==c););c>this._lastCount?this._spiraling++:c<this._lastCount&&(this._spiraling=0),this._lastCount=c,this.updateRender(this._deltaTime/b)}},updateLogic:function(a){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(),this.debug.preUpdate()):(this.stepping&&(this.pendingStep=!0),this.scale.preUpdate(),this.debug.preUpdate(),this.world.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(a),this.plugins.preUpdate(a),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(a),this.sound.update(),this.input.update(),this.physics.update(),this.particles.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate())},updateRender:function(a){this.lockRender||(this.state.preRender(a),this.renderer.render(this.stage),this.plugins.render(a),this.state.render(a),this.plugins.postRender(a))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.state=null,this.cache=null,this.input=null,this.load=null,this.sound=null,this.stage=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),c.Canvas.removeFromDOM(this.canvas),c.GAMES[this.id]=null},gamePaused:function(a){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.setMute(),this.onPause.dispatch(a),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(a){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.unsetMute(),this.onResume.dispatch(a),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(a){this.onBlur.dispatch(a),this.stage.disableVisibilityChange||this.gamePaused(a)},focusGain:function(a){this.onFocus.dispatch(a),this.stage.disableVisibilityChange||this.gameResumed(a)}},c.Game.prototype.constructor=c.Game,Object.defineProperty(c.Game.prototype,"paused",{get:function(){return this._paused},set:function(a){a===!0?(this._paused===!1&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),c.Input=function(a){this.game=a,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.pollRate=0,this.enabled=!0,this.multiInputOverride=c.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new c.ArraySet,this._localPoint=new c.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},c.Input.MOUSE_OVERRIDES_TOUCH=0,c.Input.TOUCH_OVERRIDES_MOUSE=1,c.Input.MOUSE_TOUCH_COMBINE=2,c.Input.MAX_POINTERS=10,c.Input.prototype={boot:function(){this.mousePointer=new c.Pointer(this.game,0),this.addPointer(),this.addPointer(),this.mouse=new c.Mouse(this.game),this.touch=new c.Touch(this.game),this.mspointer=new c.MSPointer(this.game),c.Keyboard&&(this.keyboard=new c.Keyboard(this.game)),c.Gamepad&&(this.gamepad=new c.Gamepad(this.game)),this.onDown=new c.Signal,this.onUp=new c.Signal,this.onTap=new c.Signal,this.onHold=new c.Signal,this.scale=new c.Point(1,1),this.speed=new c.Point,this.position=new c.Point,this._oldPosition=new c.Point,this.circle=new c.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=document.createElement("canvas"),this.hitCanvas.width=1,this.hitCanvas.height=1,this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var a=this;this._onClickTrampoline=function(b){a.onClickTrampoline(b)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],this.game.canvas.removeEventListener("click",this._onClickTrampoline)},addMoveCallback:function(a,b){this.moveCallbacks.push({callback:a,context:b})},deleteMoveCallback:function(a,b){for(var c=this.moveCallbacks.length;c--;)if(this.moveCallbacks[c].callback===a&&this.moveCallbacks[c].context===b)return void this.moveCallbacks.splice(c,1)},addPointer:function(){if(this.pointers.length>=c.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+c.Input.MAX_POINTERS+" pointers reached."),null;var a=this.pointers.length+1,b=new c.Pointer(this.game,a);return this.pointers.push(b),this["pointer"+a]=b,b},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter<this.pollRate)return void this._pollCounter++;this.speed.x=this.position.x-this._oldPosition.x,this.speed.y=this.position.y-this._oldPosition.y,this._oldPosition.copyFrom(this.position),this.mousePointer.update(),this.gamepad&&this.gamepad.active&&this.gamepad.update();for(var a=0;a<this.pointers.length;a++)this.pointers[a].update();this._pollCounter=0},reset:function(a){if(this.game.isBooted&&!this.resetLocked){void 0===a&&(a=!1),this.mousePointer.reset(),this.keyboard&&this.keyboard.reset(a),this.gamepad&&this.gamepad.reset();for(var b=0;b<this.pointers.length;b++)this.pointers[b].reset();"none"!==this.game.canvas.style.cursor&&(this.game.canvas.style.cursor="inherit"),a&&(this.onDown.dispose(),this.onUp.dispose(),this.onTap.dispose(),this.onHold.dispose(),this.onDown=new c.Signal,this.onUp=new c.Signal,this.onTap=new c.Signal,this.onHold=new c.Signal,this.moveCallbacks=[]),this._pollCounter=0}},resetSpeed:function(a,b){this._oldPosition.setTo(a,b),this.speed.setTo(0,0)},startPointer:function(a){if(this.maxPointers>=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(a);if(!this.pointer2.active)return this.pointer2.start(a);for(var b=2;b<this.pointers.length;b++){var c=this.pointers[b];if(!c.active)return c.start(a)}return null},updatePointer:function(a){if(this.pointer1.active&&this.pointer1.identifier===a.identifier)return this.pointer1.move(a);if(this.pointer2.active&&this.pointer2.identifier===a.identifier)return this.pointer2.move(a);for(var b=2;b<this.pointers.length;b++){var c=this.pointers[b];if(c.active&&c.identifier===a.identifier)return c.move(a)}return null},stopPointer:function(a){if(this.pointer1.active&&this.pointer1.identifier===a.identifier)return this.pointer1.stop(a);if(this.pointer2.active&&this.pointer2.identifier===a.identifier)return this.pointer2.stop(a);for(var b=2;b<this.pointers.length;b++){var c=this.pointers[b];if(c.active&&c.identifier===a.identifier)return c.stop(a)}return null},countActivePointers:function(a){void 0===a&&(a=this.pointers.length);for(var b=a,c=0;c<this.pointers.length&&b>0;c++){var d=this.pointers[c];d.active&&b--}return a-b},getPointer:function(a){void 0===a&&(a=!1);for(var b=0;b<this.pointers.length;b++){var c=this.pointers[b];if(c.active===a)return c}return null},getPointerFromIdentifier:function(a){for(var b=0;b<this.pointers.length;b++){var c=this.pointers[b];if(c.identifier===a)return c}return null},getPointerFromId:function(a){for(var b=0;b<this.pointers.length;b++){var c=this.pointers[b];if(c.pointerId===a)return c}return null},getLocalPosition:function(a,b,d){void 0===d&&(d=new c.Point);var e=a.worldTransform,f=1/(e.a*e.d+e.c*-e.b);return d.setTo(e.d*f*b.x+-e.c*f*b.y+(e.ty*e.c-e.tx*e.d)*f,e.a*f*b.y+-e.b*f*b.x+(-e.ty*e.a+e.tx*e.b)*f)},hitTest:function(a,b,d){if(!a.worldVisible)return!1;if(this.getLocalPosition(a,b,this._localPoint),d.copyFrom(this._localPoint),a.hitArea&&a.hitArea.contains)return a.hitArea.contains(this._localPoint.x,this._localPoint.y);if(a instanceof c.TileSprite){var e=a.width,f=a.height,g=-e*a.anchor.x;if(this._localPoint.x>=g&&this._localPoint.x<g+e){var h=-f*a.anchor.y;if(this._localPoint.y>=h&&this._localPoint.y<h+f)return!0}}else if(a instanceof PIXI.Sprite){var e=a.texture.frame.width,f=a.texture.frame.height,g=-e*a.anchor.x;if(this._localPoint.x>=g&&this._localPoint.x<g+e){var h=-f*a.anchor.y;if(this._localPoint.y>=h&&this._localPoint.y<h+f)return!0}}else if(a instanceof c.Graphics)for(var i=0;i<a.graphicsData.length;i++){var j=a.graphicsData[i];if(j.fill&&j.shape&&j.shape.contains(this._localPoint.x,this._localPoint.y))return!0}for(var i=0,k=a.children.length;k>i;i++)if(this.hitTest(a.children[i],b,d))return!0;return!1},onClickTrampoline:function(){this.activePointer.processClickTrampolines()}},c.Input.prototype.constructor=c.Input,Object.defineProperty(c.Input.prototype,"x",{get:function(){return this._x},set:function(a){this._x=Math.floor(a)}}),Object.defineProperty(c.Input.prototype,"y",{get:function(){return this._y},set:function(a){this._y=Math.floor(a)}}),Object.defineProperty(c.Input.prototype,"pollLocked",{get:function(){return this.pollRate>0&&this._pollCounter<this.pollRate}}),Object.defineProperty(c.Input.prototype,"totalInactivePointers",{get:function(){return this.pointers.length-this.countActivePointers()}}),Object.defineProperty(c.Input.prototype,"totalActivePointers",{get:function(){return this.countActivePointers()}}),Object.defineProperty(c.Input.prototype,"worldX",{get:function(){return this.game.camera.view.x+this.x}}),Object.defineProperty(c.Input.prototype,"worldY",{get:function(){return this.game.camera.view.y+this.y}}),c.Mouse=function(a){this.game=a,this.input=a.input,this.callbackContext=this.game,this.mouseDownCallback=null,this.mouseUpCallback=null,this.mouseOutCallback=null,this.mouseOverCallback=null,this.mouseWheelCallback=null,this.capture=!1,this.button=-1,this.wheelDelta=0,this.enabled=!0,this.locked=!1,this.stopOnGameOut=!1,this.pointerLock=new c.Signal,this.event=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null,this._onMouseOut=null,this._onMouseOver=null,this._onMouseWheel=null,this._wheelEvent=null},c.Mouse.NO_BUTTON=-1,c.Mouse.LEFT_BUTTON=0,c.Mouse.MIDDLE_BUTTON=1,c.Mouse.RIGHT_BUTTON=2,c.Mouse.BACK_BUTTON=3,c.Mouse.FORWARD_BUTTON=4,c.Mouse.WHEEL_UP=1,c.Mouse.WHEEL_DOWN=-1,c.Mouse.prototype={start:function(){if((!this.game.device.android||this.game.device.chrome!==!1)&&null===this._onMouseDown){var b=this;this._onMouseDown=function(a){return b.onMouseDown(a)},this._onMouseMove=function(a){return b.onMouseMove(a)},this._onMouseUp=function(a){return b.onMouseUp(a)},this._onMouseUpGlobal=function(a){return b.onMouseUpGlobal(a)},this._onMouseOut=function(a){return b.onMouseOut(a)},this._onMouseOver=function(a){return b.onMouseOver(a)},this._onMouseWheel=function(a){return b.onMouseWheel(a)};var c=this.game.canvas;c.addEventListener("mousedown",this._onMouseDown,!0),c.addEventListener("mousemove",this._onMouseMove,!0),c.addEventListener("mouseup",this._onMouseUp,!0),this.game.device.cocoonJS||(window.addEventListener("mouseup",this._onMouseUpGlobal,!0),c.addEventListener("mouseover",this._onMouseOver,!0),c.addEventListener("mouseout",this._onMouseOut,!0));var d=this.game.device.wheelEvent;d&&(c.addEventListener(d,this._onMouseWheel,!0),"mousewheel"===d?this._wheelEvent=new a(-1/40,1):"DOMMouseScroll"===d&&(this._wheelEvent=new a(1,1)))}},onMouseDown:function(a){this.event=a,this.capture&&a.preventDefault(),this.mouseDownCallback&&this.mouseDownCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=0,this.input.mousePointer.start(a))},onMouseMove:function(a){this.event=a,this.capture&&a.preventDefault(),this.mouseMoveCallback&&this.mouseMoveCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=0,this.input.mousePointer.move(a))},onMouseUp:function(a){this.event=a,this.capture&&a.preventDefault(),this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=0,this.input.mousePointer.stop(a))},onMouseUpGlobal:function(a){this.input.mousePointer.withinGame||(this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,a),a.identifier=0,this.input.mousePointer.stop(a))},onMouseOut:function(a){this.event=a,this.capture&&a.preventDefault(),this.input.mousePointer.withinGame=!1,this.mouseOutCallback&&this.mouseOutCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&this.stopOnGameOut&&(a.identifier=0,this.input.mousePointer.stop(a))},onMouseWheel:function(a){this._wheelEvent&&(a=this._wheelEvent.bindEvent(a)),this.event=a,this.capture&&a.preventDefault(),this.wheelDelta=c.Math.clamp(-a.deltaY,-1,1),this.mouseWheelCallback&&this.mouseWheelCallback.call(this.callbackContext,a)},onMouseOver:function(a){this.event=a,this.capture&&a.preventDefault(),this.input.mousePointer.withinGame=!0,this.mouseOverCallback&&this.mouseOverCallback.call(this.callbackContext,a),!this.input.enabled||!this.enabled},requestPointerLock:function(){if(this.game.device.pointerLock){var a=this.game.canvas;a.requestPointerLock=a.requestPointerLock||a.mozRequestPointerLock||a.webkitRequestPointerLock,a.requestPointerLock();var b=this;this._pointerLockChange=function(a){return b.pointerLockChange(a)},document.addEventListener("pointerlockchange",this._pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},pointerLockChange:function(a){var b=this.game.canvas;document.pointerLockElement===b||document.mozPointerLockElement===b||document.webkitPointerLockElement===b?(this.locked=!0,this.pointerLock.dispatch(!0,a)):(this.locked=!1,this.pointerLock.dispatch(!1,a))},releasePointerLock:function(){document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock(),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)},stop:function(){var a=this.game.canvas;a.removeEventListener("mousedown",this._onMouseDown,!0),a.removeEventListener("mousemove",this._onMouseMove,!0),a.removeEventListener("mouseup",this._onMouseUp,!0),a.removeEventListener("mouseover",this._onMouseOver,!0),a.removeEventListener("mouseout",this._onMouseOut,!0);var b=this.game.device.wheelEvent;b&&a.removeEventListener(b,this._onMouseWheel,!0),window.removeEventListener("mouseup",this._onMouseUpGlobal,!0),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},c.Mouse.prototype.constructor=c.Mouse,a.prototype={},a.prototype.constructor=a,a.prototype.bindEvent=function(b){if(!a._stubsGenerated&&b){var c=function(a){return function(){var b=this.originalEvent[a];return"function"!=typeof b?b:b.bind(this.originalEvent)}};for(var d in b)d in a.prototype||Object.defineProperty(a.prototype,d,{get:c(d)});a._stubsGenerated=!0}return this.originalEvent=b,this},Object.defineProperties(a.prototype,{type:{value:"wheel"},deltaMode:{get:function(){return this._deltaMode}},deltaY:{get:function(){return this._scaleFactor*(this.originalEvent.wheelDelta||this.originalEvent.detail)||0}},deltaX:{get:function(){return this._scaleFactor*this.originalEvent.wheelDeltaX||0}},deltaZ:{value:0}}),c.MSPointer=function(a){this.game=a,this.input=a.input,this.callbackContext=this.game,this.pointerDownCallback=null,this.pointerMoveCallback=null,this.pointerUpCallback=null,this.capture=!0,this.button=-1,this.event=null,this.enabled=!0,this._onMSPointerDown=null,this._onMSPointerMove=null,this._onMSPointerUp=null},c.MSPointer.prototype={start:function(){if(null===this._onMSPointerDown){var a=this;if(this.game.device.mspointer){this._onMSPointerDown=function(b){return a.onPointerDown(b)},this._onMSPointerMove=function(b){return a.onPointerMove(b)},this._onMSPointerUp=function(b){return a.onPointerUp(b)};var b=this.game.canvas;b.addEventListener("MSPointerDown",this._onMSPointerDown,!1),b.addEventListener("MSPointerMove",this._onMSPointerMove,!1),b.addEventListener("MSPointerUp",this._onMSPointerUp,!1),b.addEventListener("pointerDown",this._onMSPointerDown,!1),b.addEventListener("pointerMove",this._onMSPointerMove,!1),b.addEventListener("pointerUp",this._onMSPointerUp,!1),b.style["-ms-content-zooming"]="none",b.style["-ms-touch-action"]="none"}}},onPointerDown:function(a){this.event=a,this.capture&&a.preventDefault(),this.pointerDownCallback&&this.pointerDownCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=a.pointerId,"mouse"===a.pointerType||4===a.pointerType?this.input.mousePointer.start(a):this.input.startPointer(a))},onPointerMove:function(a){this.event=a,this.capture&&a.preventDefault(),this.pointerMoveCallback&&this.pointerMoveCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=a.pointerId,"mouse"===a.pointerType||4===a.pointerType?this.input.mousePointer.move(a):this.input.updatePointer(a))},onPointerUp:function(a){this.event=a,this.capture&&a.preventDefault(),this.pointerUpCallback&&this.pointerUpCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=a.pointerId,"mouse"===a.pointerType||4===a.pointerType?this.input.mousePointer.stop(a):this.input.stopPointer(a))},stop:function(){var a=this.game.canvas;a.removeEventListener("MSPointerDown",this._onMSPointerDown),a.removeEventListener("MSPointerMove",this._onMSPointerMove),a.removeEventListener("MSPointerUp",this._onMSPointerUp),a.removeEventListener("pointerDown",this._onMSPointerDown),a.removeEventListener("pointerMove",this._onMSPointerMove),a.removeEventListener("pointerUp",this._onMSPointerUp)}},c.MSPointer.prototype.constructor=c.MSPointer,c.DeviceButton=function(a,b){this.parent=a,this.game=a.game,this.event=null,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.duration=0,this.timeUp=0,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1,this.value=0,this.buttonCode=b,this.onDown=new c.Signal,this.onUp=new c.Signal,this.onFloat=new c.Signal},c.DeviceButton.prototype={start:function(a,b){this.isDown||(this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this.event=a,this.value=b,a&&(this.altKey=a.altKey,this.shiftKey=a.shiftKey,this.ctrlKey=a.ctrlKey),this.onDown.dispatch(this,b))},stop:function(a,b){this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.event=a,this.value=b,a&&(this.altKey=a.altKey,this.shiftKey=a.shiftKey,this.ctrlKey=a.ctrlKey),this.onUp.dispatch(this,b))},padFloat:function(a){this.value=a,this.onFloat.dispatch(this,a)},justPressed:function(a){return a=a||250,this.isDown&&this.timeDown+a>this.game.time.time},justReleased:function(a){return a=a||250,this.isUp&&this.timeUp+a>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},c.DeviceButton.prototype.constructor=c.DeviceButton,Object.defineProperty(c.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),c.Pointer=function(a,b){this.game=a,this.id=b,this.type=c.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.target=null,this.button=null,this.leftButton=new c.DeviceButton(this,c.Pointer.LEFT_BUTTON),this.middleButton=new c.DeviceButton(this,c.Pointer.MIDDLE_BUTTON),this.rightButton=new c.DeviceButton(this,c.Pointer.RIGHT_BUTTON),this.backButton=new c.DeviceButton(this,c.Pointer.BACK_BUTTON),this.forwardButton=new c.DeviceButton(this,c.Pointer.FORWARD_BUTTON),this.eraserButton=new c.DeviceButton(this,c.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===b,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.active=!1,this.dirty=!1,this.position=new c.Point,this.positionDown=new c.Point,this.positionUp=new c.Point,this.circle=new c.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},c.Pointer.NO_BUTTON=0,c.Pointer.LEFT_BUTTON=1,c.Pointer.RIGHT_BUTTON=2,c.Pointer.MIDDLE_BUTTON=4,c.Pointer.BACK_BUTTON=8,c.Pointer.FORWARD_BUTTON=16,c.Pointer.ERASER_BUTTON=32,c.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(a,b){c.Pointer.LEFT_BUTTON&a&&this.leftButton.start(b),c.Pointer.RIGHT_BUTTON&a&&this.rightButton.start(b),c.Pointer.MIDDLE_BUTTON&a&&this.middleButton.start(b),c.Pointer.BACK_BUTTON&a&&this.backButton.start(b),c.Pointer.FORWARD_BUTTON&a&&this.forwardButton.start(b),c.Pointer.ERASER_BUTTON&a&&this.eraserButton.start(b)},processButtonsUp:function(a,b){a===c.Mouse.LEFT_BUTTON&&this.leftButton.stop(b),a===c.Mouse.RIGHT_BUTTON&&this.rightButton.stop(b),a===c.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(b),a===c.Mouse.BACK_BUTTON&&this.backButton.stop(b),a===c.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(b),5===a&&this.eraserButton.stop(b)},updateButtons:function(a){this.button=a.button;var b="down"===a.type.toLowerCase().substr(-4);void 0!==a.buttons?b?this.processButtonsDown(a.buttons,a):this.processButtonsUp(a.button,a):b?this.leftButton.start(a):(this.leftButton.stop(a),this.rightButton.stop(a)),a.ctrlKey&&this.leftButton.isDown&&this.rightButton.start(a),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(a){return a.pointerId&&(this.pointerId=a.pointerId),this.identifier=a.identifier,this.target=a.target,this.isMouse?this.updateButtons(a):(this.isDown=!0,this.isUp=!1),this._history=[],this.active=!0,this.withinGame=!0,this.dirty=!1,this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(a,!0),this.positionDown.setTo(this.x,this.y),(this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&(this.game.input.x=this.x,this.game.input.y=this.y,this.game.input.position.setTo(this.x,this.y),this.game.input.onDown.dispatch(this,a),this.game.input.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){this.active&&(this.dirty&&(this.game.input.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),this._holdSent===!1&&this.duration>=this.game.input.holdRate&&((this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&this.game.input.onHold.dispatch(this),this._holdSent=!0),this.game.input.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+this.game.input.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>this.game.input.recordLimit&&this._history.shift()))},move:function(a,b){if(!this.game.input.pollLocked){if(void 0===b&&(b=!1),void 0!==a.button&&(this.button=a.button),b&&this.isMouse&&this.updateButtons(a),this.clientX=a.clientX,this.clientY=a.clientY,this.pageX=a.pageX,this.pageY=a.pageY,this.screenX=a.screenX,this.screenY=a.screenY,this.isMouse&&this.game.input.mouse.locked&&!b&&(this.rawMovementX=a.movementX||a.mozMovementX||a.webkitMovementX||0,this.rawMovementY=a.movementY||a.mozMovementY||a.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*this.game.input.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*this.game.input.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&(this.game.input.activePointer=this,this.game.input.x=this.x,this.game.input.y=this.y,this.game.input.position.setTo(this.game.input.x,this.game.input.y),this.game.input.circle.x=this.game.input.x,this.game.input.circle.y=this.game.input.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY),this.game.paused)return this;for(var d=this.game.input.moveCallbacks.length;d--;)this.game.input.moveCallbacks[d].callback.call(this.game.input.moveCallbacks[d].context,this,this.x,this.y,b);return null!==this.targetObject&&this.targetObject.isDragged===!0?this.targetObject.update(this)===!1&&(this.targetObject=null):this.game.input.interactiveItems.total>0&&this.processInteractiveObjects(b),this}},processInteractiveObjects:function(a){for(var b=Number.MAX_VALUE,c=-1,d=null,e=this.game.input.interactiveItems.first;e;)e.checked=!1,e.validForInput(c,b,!1)&&(e.checked=!0,(a&&e.checkPointerDown(this,!0)||!a&&e.checkPointerOver(this,!0))&&(b=e.sprite.renderOrderID,c=e.priorityID,d=e)),e=this.game.input.interactiveItems.next;for(var e=this.game.input.interactiveItems.first;e;)!e.checked&&e.validForInput(c,b,!0)&&(a&&e.checkPointerDown(this,!1)||!a&&e.checkPointerOver(this,!1))&&(b=e.sprite.renderOrderID,c=e.priorityID,d=e),e=this.game.input.interactiveItems.next;return null===d?this.targetObject&&(this.targetObject._pointerOutHandler(this),this.targetObject=null):null===this.targetObject?(this.targetObject=d,d._pointerOverHandler(this)):this.targetObject===d?d.update(this)===!1&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this),this.targetObject=d,this.targetObject._pointerOverHandler(this)),null!==this.targetObject},leave:function(a){this.withinGame=!1,this.move(a,!1)},stop:function(a){return this._stateReset&&this.withinGame?void a.preventDefault():(this.isMouse?this.updateButtons(a):(this.isDown=!1,this.isUp=!0),this.timeUp=this.game.time.time,(this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&(this.game.input.onUp.dispatch(this,a),this.duration>=0&&this.duration<=this.game.input.tapRate&&(this.timeUp-this.previousTapTime<this.game.input.doubleTapRate?this.game.input.onTap.dispatch(this,!0):this.game.input.onTap.dispatch(this,!1),this.previousTapTime=this.timeUp)),this.id>0&&(this.active=!1),this.withinGame=!1,this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),this.isMouse===!1&&this.game.input.currentPointers--,this.game.input.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this)},justPressed:function(a){return a=a||this.game.input.justPressedRate,this.isDown===!0&&this.timeDown+a>this.game.time.time},justReleased:function(a){return a=a||this.game.input.justReleasedRate,this.isUp&&this.timeUp+a>this.game.time.time},addClickTrampoline:function(a,b,c,d){if(this.isDown){for(var e=this._clickTrampolines=this._clickTrampolines||[],f=0;f<e.length;f++)if(e[f].name===a){e.splice(f,1);break}e.push({name:a,targetObject:this.targetObject,callback:b,callbackContext:c,callbackArgs:d})}},processClickTrampolines:function(){var a=this._clickTrampolines;if(a){for(var b=0;b<a.length;b++){var c=a[b];c.targetObject===this._trampolineTargetObject&&c.callback.apply(c.callbackContext,c.callbackArgs)}this._clickTrampolines=null,this._trampolineTargetObject=null}},reset:function(){this.isMouse===!1&&(this.active=!1),this.pointerId=null,this.identifier=null,this.dirty=!1,this.totalTouches=0,this._holdSent=!1,this._history.length=0,this._stateReset=!0,this.resetButtons(),this.targetObject&&this.targetObject._releasedHandler(this),this.targetObject=null},resetMovement:function(){this.movementX=0,this.movementY=0}},c.Pointer.prototype.constructor=c.Pointer,Object.defineProperty(c.Pointer.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),Object.defineProperty(c.Pointer.prototype,"worldX",{get:function(){return this.game.world.camera.x+this.x}}),Object.defineProperty(c.Pointer.prototype,"worldY",{get:function(){return this.game.world.camera.y+this.y}}),c.Touch=function(a){this.game=a,this.enabled=!0,this.touchLockCallbacks=[],this.callbackContext=this.game,this.touchStartCallback=null,this.touchMoveCallback=null,this.touchEndCallback=null,this.touchEnterCallback=null,this.touchLeaveCallback=null,this.touchCancelCallback=null,this.preventDefault=!0,this.event=null,this._onTouchStart=null,this._onTouchMove=null,this._onTouchEnd=null,this._onTouchEnter=null,this._onTouchLeave=null,this._onTouchCancel=null,this._onTouchMove=null},c.Touch.prototype={start:function(){if(null===this._onTouchStart){var a=this;this.game.device.touch&&(this._onTouchStart=function(b){return a.onTouchStart(b)},this._onTouchMove=function(b){return a.onTouchMove(b)},this._onTouchEnd=function(b){return a.onTouchEnd(b)},this._onTouchEnter=function(b){return a.onTouchEnter(b)},this._onTouchLeave=function(b){return a.onTouchLeave(b)},this._onTouchCancel=function(b){return a.onTouchCancel(b)},this.game.canvas.addEventListener("touchstart",this._onTouchStart,!1),this.game.canvas.addEventListener("touchmove",this._onTouchMove,!1),this.game.canvas.addEventListener("touchend",this._onTouchEnd,!1),this.game.canvas.addEventListener("touchcancel",this._onTouchCancel,!1),this.game.device.cocoonJS||(this.game.canvas.addEventListener("touchenter",this._onTouchEnter,!1),this.game.canvas.addEventListener("touchleave",this._onTouchLeave,!1)))
-}},consumeDocumentTouches:function(){this._documentTouchMove=function(a){a.preventDefault()},document.addEventListener("touchmove",this._documentTouchMove,!1)},addTouchLockCallback:function(a,b){this.touchLockCallbacks.push({callback:a,context:b})},removeTouchLockCallback:function(a,b){for(var c=this.touchLockCallbacks.length;c--;)if(this.touchLockCallbacks[c].callback===a&&this.touchLockCallbacks[c].context===b)return this.touchLockCallbacks.splice(c,1),!0;return!1},onTouchStart:function(a){for(var b=this.touchLockCallbacks.length;b--;)this.touchLockCallbacks[b].callback.call(this.touchLockCallbacks[b].context,this,a)&&this.touchLockCallbacks.splice(b,1);if(this.event=a,this.game.input.enabled&&this.enabled){this.touchStartCallback&&this.touchStartCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.startPointer(a.changedTouches[b])}},onTouchCancel:function(a){if(this.event=a,this.touchCancelCallback&&this.touchCancelCallback.call(this.callbackContext,a),this.game.input.enabled&&this.enabled){this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.stopPointer(a.changedTouches[b])}},onTouchEnter:function(a){this.event=a,this.touchEnterCallback&&this.touchEnterCallback.call(this.callbackContext,a),this.game.input.enabled&&this.enabled&&this.preventDefault&&a.preventDefault()},onTouchLeave:function(a){this.event=a,this.touchLeaveCallback&&this.touchLeaveCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault()},onTouchMove:function(a){this.event=a,this.touchMoveCallback&&this.touchMoveCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.updatePointer(a.changedTouches[b])},onTouchEnd:function(a){this.event=a,this.touchEndCallback&&this.touchEndCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.stopPointer(a.changedTouches[b])},stop:function(){this.game.device.touch&&(this.game.canvas.removeEventListener("touchstart",this._onTouchStart),this.game.canvas.removeEventListener("touchmove",this._onTouchMove),this.game.canvas.removeEventListener("touchend",this._onTouchEnd),this.game.canvas.removeEventListener("touchenter",this._onTouchEnter),this.game.canvas.removeEventListener("touchleave",this._onTouchLeave),this.game.canvas.removeEventListener("touchcancel",this._onTouchCancel))}},c.Touch.prototype.constructor=c.Touch,c.InputHandler=function(a){this.sprite=a,this.game=a.game,this.enabled=!1,this.checked=!1,this.priorityID=0,this.useHandCursor=!1,this._setHandCursor=!1,this.isDragged=!1,this.allowHorizontalDrag=!0,this.allowVerticalDrag=!0,this.bringToTop=!1,this.snapOffset=null,this.snapOnDrag=!1,this.snapOnRelease=!1,this.snapX=0,this.snapY=0,this.snapOffsetX=0,this.snapOffsetY=0,this.pixelPerfectOver=!1,this.pixelPerfectClick=!1,this.pixelPerfectAlpha=255,this.draggable=!1,this.boundsRect=null,this.boundsSprite=null,this.consumePointerEvent=!1,this.scaleLayer=!1,this.dragOffset=new c.Point,this.dragFromCenter=!1,this.dragStartPoint=new c.Point,this.snapPoint=new c.Point,this._dragPoint=new c.Point,this._dragPhase=!1,this._wasEnabled=!1,this._tempPoint=new c.Point,this._pointerData=[],this._pointerData.push({id:0,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1})},c.InputHandler.prototype={start:function(a,b){if(a=a||0,void 0===b&&(b=!1),this.enabled===!1){this.game.input.interactiveItems.add(this),this.useHandCursor=b,this.priorityID=a;for(var d=0;10>d;d++)this._pointerData[d]={id:d,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1};this.snapOffset=new c.Point,this.enabled=!0,this._wasEnabled=!0}return this.sprite.events.onAddedToGroup.add(this.addedToGroup,this),this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup,this),this.flagged=!1,this.sprite},addedToGroup:function(){this._dragPhase||this._wasEnabled&&!this.enabled&&this.start()},removedFromGroup:function(){this._dragPhase||(this.enabled?(this._wasEnabled=!0,this.stop()):this._wasEnabled=!1)},reset:function(){this.enabled=!1,this.flagged=!1;for(var a=0;10>a;a++)this._pointerData[a]={id:a,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1}},stop:function(){this.enabled!==!1&&(this.enabled=!1,this.game.input.interactiveItems.remove(this))},destroy:function(){this.sprite&&(this._setHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),this.enabled=!1,this.game.input.interactiveItems.remove(this),this._pointerData.length=0,this.boundsRect=null,this.boundsSprite=null,this.sprite=null)},validForInput:function(a,b,c){return void 0===c&&(c=!0),0===this.sprite.scale.x||0===this.sprite.scale.y||this.priorityID<this.game.input.minPriorityID?!1:(c||!this.pixelPerfectClick&&!this.pixelPerfectOver)&&(this.priorityID>a||this.priorityID===a&&this.sprite.renderOrderID<b)?!0:!1},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(a){return a=a||0,this._pointerData[a].x},pointerY:function(a){return a=a||0,this._pointerData[a].y},pointerDown:function(a){return a=a||0,this._pointerData[a].isDown},pointerUp:function(a){return a=a||0,this._pointerData[a].isUp},pointerTimeDown:function(a){return a=a||0,this._pointerData[a].timeDown},pointerTimeUp:function(a){return a=a||0,this._pointerData[a].timeUp},pointerOver:function(a){if(this.enabled){if(void 0!==a)return this._pointerData[a].isOver;for(var b=0;10>b;b++)if(this._pointerData[b].isOver)return!0}return!1},pointerOut:function(a){if(this.enabled){if(void 0!==a)return this._pointerData[a].isOut;for(var b=0;10>b;b++)if(this._pointerData[b].isOut)return!0}return!1},pointerTimeOver:function(a){return a=a||0,this._pointerData[a].timeOver},pointerTimeOut:function(a){return a=a||0,this._pointerData[a].timeOut},pointerDragged:function(a){return a=a||0,this._pointerData[a].isDragged},checkPointerDown:function(a,b){return a.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&this.game.input.hitTest(this.sprite,a,this._tempPoint)?(void 0===b&&(b=!1),!b&&this.pixelPerfectClick?this.checkPixel(this._tempPoint.x,this._tempPoint.y):!0):!1},checkPointerOver:function(a,b){return this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&this.game.input.hitTest(this.sprite,a,this._tempPoint)?(void 0===b&&(b=!1),!b&&this.pixelPerfectOver?this.checkPixel(this._tempPoint.x,this._tempPoint.y):!0):!1},checkPixel:function(a,b,c){if(this.sprite.texture.baseTexture.source){if(null===a&&null===b){this.game.input.getLocalPosition(this.sprite,c,this._tempPoint);var a=this._tempPoint.x,b=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(a-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(b-=-this.sprite.texture.frame.height*this.sprite.anchor.y),a+=this.sprite.texture.frame.x,b+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(a-=this.sprite.texture.trim.x,b-=this.sprite.texture.trim.y,a<this.sprite.texture.crop.x||a>this.sprite.texture.crop.right||b<this.sprite.texture.crop.y||b>this.sprite.texture.crop.bottom))return this._dx=a,this._dy=b,!1;this._dx=a,this._dy=b,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,a,b,1,1,0,0,1,1);var d=this.game.input.hitContext.getImageData(0,0,1,1);if(d.data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(a){return null!==this.sprite&&void 0!==this.sprite.parent?this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this.draggable&&this._draggedPointerID===a.id?this.updateDrag(a):this._pointerData[a.id].isOver?this.checkPointerOver(a)?(this._pointerData[a.id].x=a.x-this.sprite.x,this._pointerData[a.id].y=a.y-this.sprite.y,!0):(this._pointerOutHandler(a),!1):void 0:(this._pointerOutHandler(a),!1):void 0},_pointerOverHandler:function(a){null!==this.sprite&&(this._pointerData[a.id].isOver===!1||a.dirty)&&(this._pointerData[a.id].isOver=!0,this._pointerData[a.id].isOut=!1,this._pointerData[a.id].timeOver=this.game.time.time,this._pointerData[a.id].x=a.x-this.sprite.x,this._pointerData[a.id].y=a.y-this.sprite.y,this.useHandCursor&&this._pointerData[a.id].isDragged===!1&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,a))},_pointerOutHandler:function(a){null!==this.sprite&&(this._pointerData[a.id].isOver=!1,this._pointerData[a.id].isOut=!0,this._pointerData[a.id].timeOut=this.game.time.time,this.useHandCursor&&this._pointerData[a.id].isDragged===!1&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),this.sprite&&this.sprite.events&&this.sprite.events.onInputOut$dispatch(this.sprite,a))},_touchedHandler:function(a){if(null!==this.sprite){if(!this._pointerData[a.id].isDown&&this._pointerData[a.id].isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,a))return;this._pointerData[a.id].isDown=!0,this._pointerData[a.id].isUp=!1,this._pointerData[a.id].timeDown=this.game.time.time,this.sprite&&this.sprite.events&&this.sprite.events.onInputDown$dispatch(this.sprite,a),a.dirty=!0,this.draggable&&this.isDragged===!1&&this.startDrag(a),this.bringToTop&&this.sprite.bringToTop()}return this.consumePointerEvent}},_releasedHandler:function(a){null!==this.sprite&&this._pointerData[a.id].isDown&&a.isUp&&(this._pointerData[a.id].isDown=!1,this._pointerData[a.id].isUp=!0,this._pointerData[a.id].timeUp=this.game.time.time,this._pointerData[a.id].downDuration=this._pointerData[a.id].timeUp-this._pointerData[a.id].timeDown,this.checkPointerOver(a)?this.sprite&&this.sprite.events&&this.sprite.events.onInputUp$dispatch(this.sprite,a,!0):(this.sprite&&this.sprite.events&&this.sprite.events.onInputUp$dispatch(this.sprite,a,!1),this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1)),a.dirty=!0,this.draggable&&this.isDragged&&this._draggedPointerID===a.id&&this.stopDrag(a))},updateDrag:function(a){if(a.isUp)return this.stopDrag(a),!1;var b=this.globalToLocalX(a.x)+this._dragPoint.x+this.dragOffset.x,c=this.globalToLocalY(a.y)+this._dragPoint.y+this.dragOffset.y;return this.sprite.fixedToCamera?(this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=b),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=c),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y))):(this.allowHorizontalDrag&&(this.sprite.x=b),this.allowVerticalDrag&&(this.sprite.y=c),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.x,this.sprite.y))),this.sprite.events.onDragUpdate.dispatch(this.sprite,a,b,c,this.snapPoint),!0},justOver:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isOver&&this.overDuration(a)<b},justOut:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isOut&&this.game.time.time-this._pointerData[a].timeOut<b},justPressed:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isDown&&this.downDuration(a)<b},justReleased:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isUp&&this.game.time.time-this._pointerData[a].timeUp<b},overDuration:function(a){return a=a||0,this._pointerData[a].isOver?this.game.time.time-this._pointerData[a].timeOver:-1},downDuration:function(a){return a=a||0,this._pointerData[a].isDown?this.game.time.time-this._pointerData[a].timeDown:-1},enableDrag:function(a,b,d,e,f,g){void 0===a&&(a=!1),void 0===b&&(b=!1),void 0===d&&(d=!1),void 0===e&&(e=255),void 0===f&&(f=null),void 0===g&&(g=null),this._dragPoint=new c.Point,this.draggable=!0,this.bringToTop=b,this.dragOffset=new c.Point,this.dragFromCenter=a,this.pixelPerfectClick=d,this.pixelPerfectAlpha=e,f&&(this.boundsRect=f),g&&(this.boundsSprite=g)},disableDrag:function(){if(this._pointerData)for(var a=0;10>a;a++)this._pointerData[a].isDragged=!1;this.draggable=!1,this.isDragged=!1,this._draggedPointerID=-1},startDrag:function(a){var b=this.sprite.x,c=this.sprite.y;if(this.isDragged=!0,this._draggedPointerID=a.id,this._pointerData[a.id].isDragged=!0,this.sprite.fixedToCamera)this.dragFromCenter?(this.sprite.centerOn(a.x,a.y),this._dragPoint.setTo(this.sprite.cameraOffset.x-a.x,this.sprite.cameraOffset.y-a.y)):this._dragPoint.setTo(this.sprite.cameraOffset.x-a.x,this.sprite.cameraOffset.y-a.y);else{if(this.dragFromCenter){var d=this.sprite.getBounds();this.sprite.x=this.globalToLocalX(a.x)+(this.sprite.x-d.centerX),this.sprite.y=this.globalToLocalY(a.y)+(this.sprite.y-d.centerY)}this._dragPoint.setTo(this.sprite.x-this.globalToLocalX(a.x),this.sprite.y-this.globalToLocalY(a.y))}this.updateDrag(a),this.bringToTop&&(this._dragPhase=!0,this.sprite.bringToTop()),this.dragStartPoint.set(b,c),this.sprite.events.onDragStart$dispatch(this.sprite,a,b,c)},globalToLocalX:function(a){return this.scaleLayer&&(a-=this.game.scale.grid.boundsFluid.x,a*=this.game.scale.grid.scaleFluidInversed.x),a},globalToLocalY:function(a){return this.scaleLayer&&(a-=this.game.scale.grid.boundsFluid.y,a*=this.game.scale.grid.scaleFluidInversed.y),a},stopDrag:function(a){this.isDragged=!1,this._draggedPointerID=-1,this._pointerData[a.id].isDragged=!1,this._dragPhase=!1,this.snapOnRelease&&(this.sprite.fixedToCamera?(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY):(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY)),this.sprite.events.onDragStop$dispatch(this.sprite,a),this.checkPointerOver(a)===!1&&this._pointerOutHandler(a)},setDragLock:function(a,b){void 0===a&&(a=!0),void 0===b&&(b=!0),this.allowHorizontalDrag=a,this.allowVerticalDrag=b},enableSnap:function(a,b,c,d,e,f){void 0===c&&(c=!0),void 0===d&&(d=!1),void 0===e&&(e=0),void 0===f&&(f=0),this.snapX=a,this.snapY=b,this.snapOffsetX=e,this.snapOffsetY=f,this.snapOnDrag=c,this.snapOnRelease=d},disableSnap:function(){this.snapOnDrag=!1,this.snapOnRelease=!1},checkBoundsRect:function(){this.sprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsRect.left?this.sprite.cameraOffset.x=this.boundsRect.left:this.sprite.cameraOffset.x+this.sprite.width>this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.y<this.boundsRect.top?this.sprite.cameraOffset.y=this.boundsRect.top:this.sprite.cameraOffset.y+this.sprite.height>this.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.left<this.boundsRect.left?this.sprite.x=this.boundsRect.x+this.sprite.offsetX:this.sprite.right>this.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsRect.top?this.sprite.y=this.boundsRect.top+this.sprite.offsetY:this.sprite.bottom>this.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsSprite.cameraOffset.x?this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x:this.sprite.cameraOffset.x+this.sprite.width>this.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.y<this.boundsSprite.cameraOffset.y?this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y:this.sprite.cameraOffset.y+this.sprite.height>this.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.left<this.boundsSprite.left?this.sprite.x=this.boundsSprite.left+this.sprite.offsetX:this.sprite.right>this.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsSprite.top?this.sprite.y=this.boundsSprite.top+this.sprite.offsetY:this.sprite.bottom>this.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},c.InputHandler.prototype.constructor=c.InputHandler,c.Gamepad=function(a){this.game=a,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!=navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new c.SinglePad(a,this),new c.SinglePad(a,this),new c.SinglePad(a,this),new c.SinglePad(a,this)]},c.Gamepad.prototype={addCallbacks:function(a,b){"undefined"!=typeof b&&(this.onConnectCallback="function"==typeof b.onConnect?b.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof b.onDisconnect?b.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof b.onDown?b.onDown:this.onDownCallback,this.onUpCallback="function"==typeof b.onUp?b.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof b.onAxis?b.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof b.onFloat?b.onFloat:this.onFloatCallback,this.callbackContext=a)},start:function(){if(!this._active){this._active=!0;var a=this;this._onGamepadConnected=function(b){return a.onGamepadConnected(b)},this._onGamepadDisconnected=function(b){return a.onGamepadDisconnected(b)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(a){var b=a.gamepad;this._rawPads.push(b),this._gamepads[b.index].connect(b)},onGamepadDisconnected:function(a){var b=a.gamepad;for(var c in this._rawPads)this._rawPads[c].index===b.index&&this._rawPads.splice(c,1);this._gamepads[b.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(navigator.getGamepads)var a=navigator.getGamepads();else if(navigator.webkitGetGamepads)var a=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var a=navigator.webkitGamepads();if(a){this._rawPads=[];for(var b=!1,c=0;c<a.length&&(typeof a[c]!==this._prevRawGamepadTypes[c]&&(b=!0,this._prevRawGamepadTypes[c]=typeof a[c]),a[c]&&this._rawPads.push(a[c]),3!==c);c++);if(b){for(var d,e={rawIndices:{},padIndices:{}},f=0;f<this._gamepads.length;f++)if(d=this._gamepads[f],d.connected)for(var g=0;g<this._rawPads.length;g++)this._rawPads[g].index===d.index&&(e.rawIndices[d.index]=!0,e.padIndices[f]=!0);for(var h=0;h<this._gamepads.length;h++)if(d=this._gamepads[h],!e.padIndices[h]){this._rawPads.length<1&&d.disconnect();for(var i=0;i<this._rawPads.length&&!e.padIndices[h];i++){var j=this._rawPads[i];if(j){if(e.rawIndices[j.index]){d.disconnect();continue}d.connect(j),e.rawIndices[j.index]=!0,e.padIndices[h]=!0}else d.disconnect()}}}}},setDeadZones:function(a){for(var b=0;b<this._gamepads.length;b++)this._gamepads[b].deadZone=a},stop:function(){this._active=!1,window.removeEventListener("gamepadconnected",this._onGamepadConnected),window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnected)},reset:function(){this.update();for(var a=0;a<this._gamepads.length;a++)this._gamepads[a].reset()},justPressed:function(a,b){for(var c=0;c<this._gamepads.length;c++)if(this._gamepads[c].justPressed(a,b)===!0)return!0;return!1},justReleased:function(a,b){for(var c=0;c<this._gamepads.length;c++)if(this._gamepads[c].justReleased(a,b)===!0)return!0;return!1},isDown:function(a){for(var b=0;b<this._gamepads.length;b++)if(this._gamepads[b].isDown(a)===!0)return!0;return!1},destroy:function(){this.stop();for(var a=0;a<this._gamepads.length;a++)this._gamepads[a].destroy()}},c.Gamepad.prototype.constructor=c.Gamepad,Object.defineProperty(c.Gamepad.prototype,"active",{get:function(){return this._active}}),Object.defineProperty(c.Gamepad.prototype,"supported",{get:function(){return this._gamepadSupportAvailable}}),Object.defineProperty(c.Gamepad.prototype,"padsConnected",{get:function(){return this._rawPads.length}}),Object.defineProperty(c.Gamepad.prototype,"pad1",{get:function(){return this._gamepads[0]}}),Object.defineProperty(c.Gamepad.prototype,"pad2",{get:function(){return this._gamepads[1]}}),Object.defineProperty(c.Gamepad.prototype,"pad3",{get:function(){return this._gamepads[2]}}),Object.defineProperty(c.Gamepad.prototype,"pad4",{get:function(){return this._gamepads[3]}}),c.Gamepad.BUTTON_0=0,c.Gamepad.BUTTON_1=1,c.Gamepad.BUTTON_2=2,c.Gamepad.BUTTON_3=3,c.Gamepad.BUTTON_4=4,c.Gamepad.BUTTON_5=5,c.Gamepad.BUTTON_6=6,c.Gamepad.BUTTON_7=7,c.Gamepad.BUTTON_8=8,c.Gamepad.BUTTON_9=9,c.Gamepad.BUTTON_10=10,c.Gamepad.BUTTON_11=11,c.Gamepad.BUTTON_12=12,c.Gamepad.BUTTON_13=13,c.Gamepad.BUTTON_14=14,c.Gamepad.BUTTON_15=15,c.Gamepad.AXIS_0=0,c.Gamepad.AXIS_1=1,c.Gamepad.AXIS_2=2,c.Gamepad.AXIS_3=3,c.Gamepad.AXIS_4=4,c.Gamepad.AXIS_5=5,c.Gamepad.AXIS_6=6,c.Gamepad.AXIS_7=7,c.Gamepad.AXIS_8=8,c.Gamepad.AXIS_9=9,c.Gamepad.XBOX360_A=0,c.Gamepad.XBOX360_B=1,c.Gamepad.XBOX360_X=2,c.Gamepad.XBOX360_Y=3,c.Gamepad.XBOX360_LEFT_BUMPER=4,c.Gamepad.XBOX360_RIGHT_BUMPER=5,c.Gamepad.XBOX360_LEFT_TRIGGER=6,c.Gamepad.XBOX360_RIGHT_TRIGGER=7,c.Gamepad.XBOX360_BACK=8,c.Gamepad.XBOX360_START=9,c.Gamepad.XBOX360_STICK_LEFT_BUTTON=10,c.Gamepad.XBOX360_STICK_RIGHT_BUTTON=11,c.Gamepad.XBOX360_DPAD_LEFT=14,c.Gamepad.XBOX360_DPAD_RIGHT=15,c.Gamepad.XBOX360_DPAD_UP=12,c.Gamepad.XBOX360_DPAD_DOWN=13,c.Gamepad.XBOX360_STICK_LEFT_X=0,c.Gamepad.XBOX360_STICK_LEFT_Y=1,c.Gamepad.XBOX360_STICK_RIGHT_X=2,c.Gamepad.XBOX360_STICK_RIGHT_Y=3,c.Gamepad.PS3XC_X=0,c.Gamepad.PS3XC_CIRCLE=1,c.Gamepad.PS3XC_SQUARE=2,c.Gamepad.PS3XC_TRIANGLE=3,c.Gamepad.PS3XC_L1=4,c.Gamepad.PS3XC_R1=5,c.Gamepad.PS3XC_L2=6,c.Gamepad.PS3XC_R2=7,c.Gamepad.PS3XC_SELECT=8,c.Gamepad.PS3XC_START=9,c.Gamepad.PS3XC_STICK_LEFT_BUTTON=10,c.Gamepad.PS3XC_STICK_RIGHT_BUTTON=11,c.Gamepad.PS3XC_DPAD_UP=12,c.Gamepad.PS3XC_DPAD_DOWN=13,c.Gamepad.PS3XC_DPAD_LEFT=14,c.Gamepad.PS3XC_DPAD_RIGHT=15,c.Gamepad.PS3XC_STICK_LEFT_X=0,c.Gamepad.PS3XC_STICK_LEFT_Y=1,c.Gamepad.PS3XC_STICK_RIGHT_X=2,c.Gamepad.PS3XC_STICK_RIGHT_Y=3,c.SinglePad=function(a,b){this.game=a,this.index=null,this.connected=!1,this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this.deadZone=.26,this._padParent=b,this._rawPad=null,this._prevTimestamp=null,this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0},c.SinglePad.prototype={addCallbacks:function(a,b){"undefined"!=typeof b&&(this.onConnectCallback="function"==typeof b.onConnect?b.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof b.onDisconnect?b.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof b.onDown?b.onDown:this.onDownCallback,this.onUpCallback="function"==typeof b.onUp?b.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof b.onAxis?b.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof b.onFloat?b.onFloat:this.onFloatCallback)},getButton:function(a){return this._buttons[a]?this._buttons[a]:null},pollStatus:function(){if(this.connected&&this.game.input.enabled&&this.game.input.gamepad.enabled&&(!this._rawPad.timestamp||this._rawPad.timestamp!==this._prevTimestamp)){for(var a=0;a<this._buttonsLen;a++){var b=isNaN(this._rawPad.buttons[a])?this._rawPad.buttons[a].value:this._rawPad.buttons[a];b!==this._buttons[a].value&&(1===b?this.processButtonDown(a,b):0===b?this.processButtonUp(a,b):this.processButtonFloat(a,b))}for(var c=0;c<this._axesLen;c++){var d=this._rawPad.axes[c];d>0&&d>this.deadZone||0>d&&d<-this.deadZone?this.processAxisChange(c,d):this.processAxisChange(c,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(a){var b=!this.connected;this.connected=!0,this.index=a.index,this._rawPad=a,this._buttons=[],this._buttonsLen=a.buttons.length,this._axes=[],this._axesLen=a.axes.length;for(var d=0;d<this._axesLen;d++)this._axes[d]=a.axes[d];for(var e in a.buttons)e=parseInt(e,10),this._buttons[e]=new c.DeviceButton(this,e);b&&this._padParent.onConnectCallback&&this._padParent.onConnectCallback.call(this._padParent.callbackContext,this.index),b&&this.onConnectCallback&&this.onConnectCallback.call(this.callbackContext)},disconnect:function(){var a=this.connected,b=this.index;this.connected=!1,this.index=null,this._rawPad=void 0;for(var c=0;c<this._buttonsLen;c++)this._buttons[c].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,a&&this._padParent.onDisconnectCallback&&this._padParent.onDisconnectCallback.call(this._padParent.callbackContext,b),a&&this.onDisconnectCallback&&this.onDisconnectCallback.call(this.callbackContext)},destroy:function(){this._rawPad=void 0;for(var a=0;a<this._buttonsLen;a++)this._buttons[a].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null},processAxisChange:function(a,b){this._axes[a]!==b&&(this._axes[a]=b,this._padParent.onAxisCallback&&this._padParent.onAxisCallback.call(this._padParent.callbackContext,this,a,b),this.onAxisCallback&&this.onAxisCallback.call(this.callbackContext,this,a,b))},processButtonDown:function(a,b){this._padParent.onDownCallback&&this._padParent.onDownCallback.call(this._padParent.callbackContext,a,b,this.index),this.onDownCallback&&this.onDownCallback.call(this.callbackContext,a,b),this._buttons[a]&&this._buttons[a].start(null,b)},processButtonUp:function(a,b){this._padParent.onUpCallback&&this._padParent.onUpCallback.call(this._padParent.callbackContext,a,b,this.index),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,a,b),this._buttons[a]&&this._buttons[a].stop(null,b)},processButtonFloat:function(a,b){this._padParent.onFloatCallback&&this._padParent.onFloatCallback.call(this._padParent.callbackContext,a,b,this.index),this.onFloatCallback&&this.onFloatCallback.call(this.callbackContext,a,b),this._buttons[a]&&this._buttons[a].padFloat(b)},axis:function(a){return this._axes[a]?this._axes[a]:!1},isDown:function(a){return this._buttons[a]?this._buttons[a].isDown:!1},isUp:function(a){return this._buttons[a]?this._buttons[a].isUp:!1},justReleased:function(a,b){return this._buttons[a]?this._buttons[a].justReleased(b):void 0},justPressed:function(a,b){return this._buttons[a]?this._buttons[a].justPressed(b):void 0},buttonValue:function(a){return this._buttons[a]?this._buttons[a].value:null},reset:function(){for(var a=0;a<this._axes.length;a++)this._axes[a]=0}},c.SinglePad.prototype.constructor=c.SinglePad,c.Key=function(a,b){this.game=a,this._enabled=!0,this.event=null,this.isDown=!1,this.isUp=!0,this.altKey=!1,this.ctrlKey=!1,this.shiftKey=!1,this.timeDown=0,this.duration=0,this.timeUp=-2500,this.repeats=0,this.keyCode=b,this.onDown=new c.Signal,this.onHoldCallback=null,this.onHoldContext=null,this.onUp=new c.Signal,this._justDown=!1,this._justUp=!1},c.Key.prototype={update:function(){this._enabled&&this.isDown&&(this.duration=this.game.time.time-this.timeDown,this.repeats++,this.onHoldCallback&&this.onHoldCallback.call(this.onHoldContext,this))},processKeyDown:function(a){this._enabled&&(this.event=a,this.isDown||(this.altKey=a.altKey,this.ctrlKey=a.ctrlKey,this.shiftKey=a.shiftKey,this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this._justDown=!0,this.onDown.dispatch(this)))},processKeyUp:function(a){this._enabled&&(this.event=a,this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=this.game.time.time-this.timeDown,this._justUp=!0,this.onUp.dispatch(this)))},reset:function(a){void 0===a&&(a=!0),this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=0,this._enabled=!0,this._justDown=!1,this._justUp=!1,a&&(this.onDown.removeAll(),this.onUp.removeAll(),this.onHoldCallback=null,this.onHoldContext=null)},downDuration:function(a){return void 0===a&&(a=50),this.isDown&&this.duration<a},upDuration:function(a){return void 0===a&&(a=50),!this.isDown&&this.game.time.time-this.timeUp<a}},Object.defineProperty(c.Key.prototype,"justDown",{get:function(){var a=this._justDown;return this._justDown=!1,a}}),Object.defineProperty(c.Key.prototype,"justUp",{get:function(){var a=this._justUp;return this._justUp=!1,a}}),Object.defineProperty(c.Key.prototype,"enabled",{get:function(){return this._enabled},set:function(a){a=!!a,a!==this._enabled&&(a||this.reset(!1),this._enabled=a)}}),c.Key.prototype.constructor=c.Key,c.Keyboard=function(a){this.game=a,this.enabled=!0,this.event=null,this.pressEvent=null,this.callbackContext=this,this.onDownCallback=null,this.onPressCallback=null,this.onUpCallback=null,this._keys=[],this._capture=[],this._onKeyDown=null,this._onKeyPress=null,this._onKeyUp=null,this._i=0,this._k=0},c.Keyboard.prototype={addCallbacks:function(a,b,c,d){this.callbackContext=a,"undefined"!=typeof b&&(this.onDownCallback=b),"undefined"!=typeof c&&(this.onUpCallback=c),"undefined"!=typeof d&&(this.onPressCallback=d)},addKey:function(a){return this._keys[a]||(this._keys[a]=new c.Key(this.game,a),this.addKeyCapture(a)),this._keys[a]},addKeys:function(a){var b={};for(var c in a)b[c]=this.addKey(a[c]);return b},removeKey:function(a){this._keys[a]&&(this._keys[a]=null,this.removeKeyCapture(a))},createCursorKeys:function(){return this.addKeys({up:c.Keyboard.UP,down:c.Keyboard.DOWN,left:c.Keyboard.LEFT,right:c.Keyboard.RIGHT})},start:function(){if(!this.game.device.cocoonJS&&null===this._onKeyDown){var a=this;this._onKeyDown=function(b){return a.processKeyDown(b)},this._onKeyUp=function(b){return a.processKeyUp(b)},this._onKeyPress=function(b){return a.processKeyPress(b)},window.addEventListener("keydown",this._onKeyDown,!1),window.addEventListener("keyup",this._onKeyUp,!1),window.addEventListener("keypress",this._onKeyPress,!1)}},stop:function(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("keypress",this._onKeyPress),this._onKeyDown=null,this._onKeyUp=null,this._onKeyPress=null},destroy:function(){this.stop(),this.clearCaptures(),this._keys.length=0,this._i=0},addKeyCapture:function(a){if("object"==typeof a)for(var b in a)this._capture[a[b]]=!0;else this._capture[a]=!0},removeKeyCapture:function(a){delete this._capture[a]
-},clearCaptures:function(){this._capture={}},update:function(){for(this._i=this._keys.length;this._i--;)this._keys[this._i]&&this._keys[this._i].update()},processKeyDown:function(a){this.event=a,this.game.input.enabled&&this.enabled&&(this._capture[a.keyCode]&&a.preventDefault(),this._keys[a.keyCode]||(this._keys[a.keyCode]=new c.Key(this.game,a.keyCode)),this._keys[a.keyCode].processKeyDown(a),this._k=a.keyCode,this.onDownCallback&&this.onDownCallback.call(this.callbackContext,a))},processKeyPress:function(a){this.pressEvent=a,this.game.input.enabled&&this.enabled&&this.onPressCallback&&this.onPressCallback.call(this.callbackContext,String.fromCharCode(a.charCode),a)},processKeyUp:function(a){this.event=a,this.game.input.enabled&&this.enabled&&(this._capture[a.keyCode]&&a.preventDefault(),this._keys[a.keyCode]||(this._keys[a.keyCode]=new c.Key(this.game,a.keyCode)),this._keys[a.keyCode].processKeyUp(a),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,a))},reset:function(a){void 0===a&&(a=!0),this.event=null;for(var b=this._keys.length;b--;)this._keys[b]&&this._keys[b].reset(a)},downDuration:function(a,b){return this._keys[a]?this._keys[a].downDuration(b):null},upDuration:function(a,b){return this._keys[a]?this._keys[a].upDuration(b):null},isDown:function(a){return this._keys[a]?this._keys[a].isDown:null}},Object.defineProperty(c.Keyboard.prototype,"lastChar",{get:function(){return 32===this.event.charCode?"":String.fromCharCode(this.pressEvent.charCode)}}),Object.defineProperty(c.Keyboard.prototype,"lastKey",{get:function(){return this._keys[this._k]}}),c.Keyboard.prototype.constructor=c.Keyboard,c.Keyboard.A="A".charCodeAt(0),c.Keyboard.B="B".charCodeAt(0),c.Keyboard.C="C".charCodeAt(0),c.Keyboard.D="D".charCodeAt(0),c.Keyboard.E="E".charCodeAt(0),c.Keyboard.F="F".charCodeAt(0),c.Keyboard.G="G".charCodeAt(0),c.Keyboard.H="H".charCodeAt(0),c.Keyboard.I="I".charCodeAt(0),c.Keyboard.J="J".charCodeAt(0),c.Keyboard.K="K".charCodeAt(0),c.Keyboard.L="L".charCodeAt(0),c.Keyboard.M="M".charCodeAt(0),c.Keyboard.N="N".charCodeAt(0),c.Keyboard.O="O".charCodeAt(0),c.Keyboard.P="P".charCodeAt(0),c.Keyboard.Q="Q".charCodeAt(0),c.Keyboard.R="R".charCodeAt(0),c.Keyboard.S="S".charCodeAt(0),c.Keyboard.T="T".charCodeAt(0),c.Keyboard.U="U".charCodeAt(0),c.Keyboard.V="V".charCodeAt(0),c.Keyboard.W="W".charCodeAt(0),c.Keyboard.X="X".charCodeAt(0),c.Keyboard.Y="Y".charCodeAt(0),c.Keyboard.Z="Z".charCodeAt(0),c.Keyboard.ZERO="0".charCodeAt(0),c.Keyboard.ONE="1".charCodeAt(0),c.Keyboard.TWO="2".charCodeAt(0),c.Keyboard.THREE="3".charCodeAt(0),c.Keyboard.FOUR="4".charCodeAt(0),c.Keyboard.FIVE="5".charCodeAt(0),c.Keyboard.SIX="6".charCodeAt(0),c.Keyboard.SEVEN="7".charCodeAt(0),c.Keyboard.EIGHT="8".charCodeAt(0),c.Keyboard.NINE="9".charCodeAt(0),c.Keyboard.NUMPAD_0=96,c.Keyboard.NUMPAD_1=97,c.Keyboard.NUMPAD_2=98,c.Keyboard.NUMPAD_3=99,c.Keyboard.NUMPAD_4=100,c.Keyboard.NUMPAD_5=101,c.Keyboard.NUMPAD_6=102,c.Keyboard.NUMPAD_7=103,c.Keyboard.NUMPAD_8=104,c.Keyboard.NUMPAD_9=105,c.Keyboard.NUMPAD_MULTIPLY=106,c.Keyboard.NUMPAD_ADD=107,c.Keyboard.NUMPAD_ENTER=108,c.Keyboard.NUMPAD_SUBTRACT=109,c.Keyboard.NUMPAD_DECIMAL=110,c.Keyboard.NUMPAD_DIVIDE=111,c.Keyboard.F1=112,c.Keyboard.F2=113,c.Keyboard.F3=114,c.Keyboard.F4=115,c.Keyboard.F5=116,c.Keyboard.F6=117,c.Keyboard.F7=118,c.Keyboard.F8=119,c.Keyboard.F9=120,c.Keyboard.F10=121,c.Keyboard.F11=122,c.Keyboard.F12=123,c.Keyboard.F13=124,c.Keyboard.F14=125,c.Keyboard.F15=126,c.Keyboard.COLON=186,c.Keyboard.EQUALS=187,c.Keyboard.COMMA=188,c.Keyboard.UNDERSCORE=189,c.Keyboard.PERIOD=190,c.Keyboard.QUESTION_MARK=191,c.Keyboard.TILDE=192,c.Keyboard.OPEN_BRACKET=219,c.Keyboard.BACKWARD_SLASH=220,c.Keyboard.CLOSED_BRACKET=221,c.Keyboard.QUOTES=222,c.Keyboard.BACKSPACE=8,c.Keyboard.TAB=9,c.Keyboard.CLEAR=12,c.Keyboard.ENTER=13,c.Keyboard.SHIFT=16,c.Keyboard.CONTROL=17,c.Keyboard.ALT=18,c.Keyboard.CAPS_LOCK=20,c.Keyboard.ESC=27,c.Keyboard.SPACEBAR=32,c.Keyboard.PAGE_UP=33,c.Keyboard.PAGE_DOWN=34,c.Keyboard.END=35,c.Keyboard.HOME=36,c.Keyboard.LEFT=37,c.Keyboard.UP=38,c.Keyboard.RIGHT=39,c.Keyboard.DOWN=40,c.Keyboard.PLUS=43,c.Keyboard.MINUS=44,c.Keyboard.INSERT=45,c.Keyboard.DELETE=46,c.Keyboard.HELP=47,c.Keyboard.NUM_LOCK=144,c.Component=function(){},c.Component.Angle=function(){},c.Component.Angle.prototype={angle:{get:function(){return c.Math.wrapAngle(c.Math.radToDeg(this.rotation))},set:function(a){this.rotation=c.Math.degToRad(c.Math.wrapAngle(a))}}},c.Component.Animation=function(){},c.Component.Animation.prototype={play:function(a,b,c,d){return this.animations?this.animations.play(a,b,c,d):void 0}},c.Component.AutoCull=function(){},c.Component.AutoCull.prototype={autoCull:!1,inCamera:{get:function(){return this.autoCull||this.checkWorldBounds||(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y),this.game.world.camera.view.intersects(this._bounds)}}},c.Component.Bounds=function(){},c.Component.Bounds.prototype={offsetX:{get:function(){return this.anchor.x*this.width}},offsetY:{get:function(){return this.anchor.y*this.height}},left:{get:function(){return this.x-this.offsetX}},right:{get:function(){return this.x+this.width-this.offsetX}},top:{get:function(){return this.y-this.offsetY}},bottom:{get:function(){return this.y+this.height-this.offsetY}}},c.Component.BringToTop=function(){},c.Component.BringToTop.prototype.bringToTop=function(){return this.parent&&this.parent.bringToTop(this),this},c.Component.BringToTop.prototype.sendToBack=function(){return this.parent&&this.parent.sendToBack(this),this},c.Component.BringToTop.prototype.moveUp=function(){return this.parent&&this.parent.moveUp(this),this},c.Component.BringToTop.prototype.moveDown=function(){return this.parent&&this.parent.moveDown(this),this},c.Component.Core=function(){},c.Component.Core.install=function(a){c.Utils.mixinPrototype(this,c.Component.Core.prototype),this.components={};for(var b=0;b<a.length;b++){var d=a[b],e=!1;"Destroy"===d&&(e=!0),c.Utils.mixinPrototype(this,c.Component[d].prototype,e),this.components[d]=!0}},c.Component.Core.init=function(a,b,d,e,f){this.game=a,this.key=e,this.position.set(b,d),this.world=new c.Point(b,d),this.previousPosition=new c.Point(b,d),this.events=new c.Events(this),this._bounds=new c.Rectangle,this.components.PhysicsBody&&(this.body=this.body),this.components.Animation&&(this.animations=new c.AnimationManager(this)),this.components.LoadTexture&&null!==e&&this.loadTexture(e,f),this.components.FixedToCamera&&(this.cameraOffset=new c.Point(b,d))},c.Component.Core.preUpdate=function(){if(this.pendingDestroy)return void this.destroy();if(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;this.world.setTo(this.game.camera.x+this.worldTransform.tx,this.game.camera.y+this.worldTransform.ty),this.visible&&(this.renderOrderID=this.game.stage.currentRenderOrderID++),this.texture&&(this.texture.requiresReTint=!1),this.animations&&this.animations.update(),this.body&&this.body.preUpdate();for(var a=0;a<this.children.length;a++)this.children[a].preUpdate();return!0},c.Component.Core.prototype={game:null,name:"",components:{},z:0,events:void 0,animations:void 0,key:"",world:null,debug:!1,previousPosition:null,previousRotation:0,renderOrderID:0,fresh:!0,pendingDestroy:!1,_bounds:null,_exists:!0,exists:{get:function(){return this._exists},set:function(a){a?(this._exists=!0,this.body&&this.body.type===c.Physics.P2JS&&this.body.addToWorld(),this.visible=!0):(this._exists=!1,this.body&&this.body.type===c.Physics.P2JS&&this.body.removeFromWorld(),this.visible=!1)}},update:function(){},postUpdate:function(){this.customRender&&this.key.render(),this.components.PhysicsBody&&c.Component.PhysicsBody.postUpdate.call(this),this.components.FixedToCamera&&c.Component.FixedToCamera.postUpdate.call(this);for(var a=0;a<this.children.length;a++)this.children[a].postUpdate()}},c.Component.Crop=function(){},c.Component.Crop.prototype={cropRect:null,_crop:null,crop:function(a,b){void 0===b&&(b=!1),a?(b&&null!==this.cropRect?this.cropRect.setTo(a.x,a.y,a.width,a.height):this.cropRect=b&&null===this.cropRect?new c.Rectangle(a.x,a.y,a.width,a.height):a,this.updateCrop()):(this._crop=null,this.cropRect=null,this.resetFrame())},updateCrop:function(){if(this.cropRect){this._crop=c.Rectangle.clone(this.cropRect,this._crop),this._crop.x+=this._frame.x,this._crop.y+=this._frame.y;var a=Math.max(this._frame.x,this._crop.x),b=Math.max(this._frame.y,this._crop.y),d=Math.min(this._frame.right,this._crop.right)-a,e=Math.min(this._frame.bottom,this._crop.bottom)-b;this.texture.crop.x=a,this.texture.crop.y=b,this.texture.crop.width=d,this.texture.crop.height=e,this.texture.frame.width=Math.min(d,this.cropRect.width),this.texture.frame.height=Math.min(e,this.cropRect.height),this.texture.width=this.texture.frame.width,this.texture.height=this.texture.frame.height,this.texture._updateUvs()}}},c.Component.Delta=function(){},c.Component.Delta.prototype={deltaX:{get:function(){return this.world.x-this.previousPosition.x}},deltaY:{get:function(){return this.world.y-this.previousPosition.y}},deltaZ:{get:function(){return this.rotation-this.previousRotation}}},c.Component.Destroy=function(){},c.Component.Destroy.prototype={destroyPhase:!1,destroy:function(a){if(null!==this.game&&!this.destroyPhase){void 0===a&&(a=!0),this.destroyPhase=!0,this.events&&this.events.onDestroy$dispatch(this),this.parent&&(this.parent instanceof c.Group?this.parent.remove(this):this.parent.removeChild(this)),this.input&&this.input.destroy(),this.animations&&this.animations.destroy(),this.body&&this.body.destroy(),this.events&&this.events.destroy();var b=this.children.length;if(a)for(;b--;)this.children[b].destroy(a);else for(;b--;)this.removeChild(this.children[b]);this._crop&&(this._crop=null),this._frame&&(this._frame=null),c.Video&&this.key instanceof c.Video&&this.key.onChangeSource.remove(this.resizeFrame,this),c.BitmapText&&this._glyphs&&(this._glyphs=[]),this.alive=!1,this.exists=!1,this.visible=!1,this.filters=null,this.mask=null,this.game=null,this.renderable=!1,this.transformCallback=null,this.transformCallbackContext=null,this.hitArea=null,this.parent=null,this.stage=null,this.worldTransform=null,this.filterArea=null,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite(),this.destroyPhase=!1,this.pendingDestroy=!1}}},c.Events=function(a){this.parent=a},c.Events.prototype={destroy:function(){this._parent=null,this._onDestroy&&this._onDestroy.dispose(),this._onAddedToGroup&&this._onAddedToGroup.dispose(),this._onRemovedFromGroup&&this._onRemovedFromGroup.dispose(),this._onRemovedFromWorld&&this._onRemovedFromWorld.dispose(),this._onKilled&&this._onKilled.dispose(),this._onRevived&&this._onRevived.dispose(),this._onEnterBounds&&this._onEnterBounds.dispose(),this._onOutOfBounds&&this._onOutOfBounds.dispose(),this._onInputOver&&this._onInputOver.dispose(),this._onInputOut&&this._onInputOut.dispose(),this._onInputDown&&this._onInputDown.dispose(),this._onInputUp&&this._onInputUp.dispose(),this._onDragStart&&this._onDragStart.dispose(),this._onDragUpdate&&this._onDragUpdate.dispose(),this._onDragStop&&this._onDragStop.dispose(),this._onAnimationStart&&this._onAnimationStart.dispose(),this._onAnimationComplete&&this._onAnimationComplete.dispose(),this._onAnimationLoop&&this._onAnimationLoop.dispose()},onAddedToGroup:null,onRemovedFromGroup:null,onRemovedFromWorld:null,onDestroy:null,onKilled:null,onRevived:null,onOutOfBounds:null,onEnterBounds:null,onInputOver:null,onInputOut:null,onInputDown:null,onInputUp:null,onDragStart:null,onDragUpdate:null,onDragStop:null,onAnimationStart:null,onAnimationComplete:null,onAnimationLoop:null},c.Events.prototype.constructor=c.Events;for(var e in c.Events.prototype)c.Events.prototype.hasOwnProperty(e)&&0===e.indexOf("on")&&null===c.Events.prototype[e]&&!function(a,b){"use strict";Object.defineProperty(c.Events.prototype,a,{get:function(){return this[b]||(this[b]=new c.Signal)}}),c.Events.prototype[a+"$dispatch"]=function(){return this[b]?this[b].dispatch.apply(this[b],arguments):null}}(e,"_"+e);c.Component.FixedToCamera=function(){},c.Component.FixedToCamera.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y)},c.Component.FixedToCamera.prototype={_fixedToCamera:!1,fixedToCamera:{get:function(){return this._fixedToCamera},set:function(a){a?(this._fixedToCamera=!0,this.cameraOffset.set(this.x,this.y)):this._fixedToCamera=!1}},cameraOffset:new c.Point},c.Component.Health=function(){},c.Component.Health.prototype={health:1,maxHealth:100,damage:function(a){return this.alive&&(this.health-=a,this.health<=0&&this.kill()),this},heal:function(a){return this.alive&&(this.health+=a,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},c.Component.InCamera=function(){},c.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},c.Component.InputEnabled=function(){},c.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(a){a?null===this.input?(this.input=new c.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},c.Component.InWorld=function(){},c.Component.InWorld.preUpdate=function(){if((this.autoCull||this.checkWorldBounds)&&(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull&&(this.game.world.camera.view.intersects(this._bounds)?(this.renderable=!0,this.game.world.camera.totalInView++):this.renderable=!1),this.checkWorldBounds))if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1;return!0},c.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},c.Component.LifeSpan=function(){},c.Component.LifeSpan.preUpdate=function(){return this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0)?(this.kill(),!1):!0},c.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(a){return void 0===a&&(a=1),this.alive=!0,this.exists=!0,this.visible=!0,"number"==typeof this.health&&(this.health=a),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},c.Component.LoadTexture=function(){},c.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(a,b,d){b=b||0,(d||void 0===d)&&this.animations&&this.animations.stop(),this.key=a,this.customRender=!1;var e=this.game.cache,f=!0,g=!this.texture.baseTexture.scaleMode;if(c.RenderTexture&&a instanceof c.RenderTexture)this.key=a.key,this.setTexture(a);else if(c.BitmapData&&a instanceof c.BitmapData)this.customRender=!0,this.setTexture(a.texture),e.hasFrameData(a.key,c.Cache.BITMAPDATA)&&(f=!this.animations.loadFrameData(e.getFrameData(a.key,c.Cache.BITMAPDATA),b));else if(c.Video&&a instanceof c.Video){this.customRender=!0;var h=a.texture.valid;this.setTexture(a.texture),this.setFrame(a.texture.frame.clone()),a.onChangeSource.add(this.resizeFrame,this),this.texture.valid=h}else if(a instanceof PIXI.Texture)this.setTexture(a);else{var i=e.getImage(a,!0);this.key=i.key,this.setTexture(new PIXI.Texture(i.base)),f=!this.animations.loadFrameData(i.frameData,b)}f&&(this._frame=c.Rectangle.clone(this.texture.frame)),g||(this.texture.baseTexture.scaleMode=1)},setFrame:function(a){this._frame=a,this.texture.frame.x=a.x,this.texture.frame.y=a.y,this.texture.frame.width=a.width,this.texture.frame.height=a.height,this.texture.crop.x=a.x,this.texture.crop.y=a.y,this.texture.crop.width=a.width,this.texture.crop.height=a.height,a.trimmed?(this.texture.trim?(this.texture.trim.x=a.spriteSourceSizeX,this.texture.trim.y=a.spriteSourceSizeY,this.texture.trim.width=a.sourceSizeW,this.texture.trim.height=a.sourceSizeH):this.texture.trim={x:a.spriteSourceSizeX,y:a.spriteSourceSizeY,width:a.sourceSizeW,height:a.sourceSizeH},this.texture.width=a.sourceSizeW,this.texture.height=a.sourceSizeH,this.texture.frame.width=a.sourceSizeW,this.texture.frame.height=a.sourceSizeH):!a.trimmed&&this.texture.trim&&(this.texture.trim=null),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(a,b,c){this.texture.frame.resize(b,c),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(a){this.animations.frame=a}},frameName:{get:function(){return this.animations.frameName},set:function(a){this.animations.frameName=a}}},c.Component.Overlap=function(){},c.Component.Overlap.prototype={overlap:function(a){return c.Rectangle.intersects(this.getBounds(),a.getBounds())}},c.Component.PhysicsBody=function(){},c.Component.PhysicsBody.preUpdate=function(){return this.fresh&&this.exists?(this.world.setTo(this.parent.position.x+this.position.x,this.parent.position.y+this.position.y),this.worldTransform.tx=this.world.x,this.worldTransform.ty=this.world.y,this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this._exists&&this.parent.exists?!0:(this.renderOrderID=-1,!1))},c.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},c.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(a){this.position.x=a,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(a){this.position.y=a,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},c.Component.Reset=function(){},c.Component.Reset.prototype.reset=function(a,b,c){return void 0===c&&(c=1),this.world.set(a,b),this.position.set(a,b),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=c),this.components.PhysicsBody&&this.body&&this.body.reset(a,b,!1,!1),this},c.Component.ScaleMinMax=function(){},c.Component.ScaleMinMax.prototype={transformCallback:this.checkTransform,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(a){this.scaleMin&&(a.a<this.scaleMin.x&&(a.a=this.scaleMin.x),a.d<this.scaleMin.y&&(a.d=this.scaleMin.y)),this.scaleMax&&(a.a>this.scaleMax.x&&(a.a=this.scaleMax.x),a.d>this.scaleMax.y&&(a.d=this.scaleMax.y))},setScaleMinMax:function(a,b,d,e){void 0===b?b=d=e=a:void 0===d&&(d=e=b,b=a),null===a?this.scaleMin=null:this.scaleMin?this.scaleMin.set(a,b):this.scaleMin=new c.Point(a,b),null===d?this.scaleMax=null:this.scaleMax?this.scaleMax.set(d,e):this.scaleMax=new c.Point(d,e)}},c.Component.Smoothed=function(){},c.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(a){a?this.texture&&(this.texture.baseTexture.scaleMode=0):this.texture&&(this.texture.baseTexture.scaleMode=1)}}},c.GameObjectFactory=function(a){this.game=a,this.world=this.game.world},c.GameObjectFactory.prototype={existing:function(a){return this.world.add(a)},image:function(a,b,d,e,f){return void 0===f&&(f=this.world),f.add(new c.Image(this.game,a,b,d,e))},sprite:function(a,b,c,d,e){return void 0===e&&(e=this.world),e.create(a,b,c,d)},creature:function(a,b,d,e,f){void 0===f&&(f=this.world);var g=new c.Creature(this.game,a,b,d,e);return f.add(g),g},tween:function(a){return this.game.tweens.create(a)},group:function(a,b,d,e,f){return new c.Group(this.game,a,b,d,e,f)},physicsGroup:function(a,b,d,e){return new c.Group(this.game,b,d,e,!0,a)},spriteBatch:function(a,b,d){return void 0===a&&(a=null),void 0===b&&(b="group"),void 0===d&&(d=!1),new c.SpriteBatch(this.game,a,b,d)},audio:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},sound:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},audioSprite:function(a){return this.game.sound.addSprite(a)},tileSprite:function(a,b,d,e,f,g,h){return void 0===h&&(h=this.world),h.add(new c.TileSprite(this.game,a,b,d,e,f,g))},rope:function(a,b,d,e,f,g){return void 0===g&&(g=this.world),g.add(new c.Rope(this.game,a,b,d,e,f))},text:function(a,b,d,e,f){return void 0===f&&(f=this.world),f.add(new c.Text(this.game,a,b,d,e))},button:function(a,b,d,e,f,g,h,i,j,k){return void 0===k&&(k=this.world),k.add(new c.Button(this.game,a,b,d,e,f,g,h,i,j))},graphics:function(a,b,d){return void 0===d&&(d=this.world),d.add(new c.Graphics(this.game,a,b))},emitter:function(a,b,d){return this.game.particles.add(new c.Particles.Arcade.Emitter(this.game,a,b,d))},retroFont:function(a,b,d,e,f,g,h,i,j){return new c.RetroFont(this.game,a,b,d,e,f,g,h,i,j)},bitmapText:function(a,b,d,e,f,g){return void 0===g&&(g=this.world),g.add(new c.BitmapText(this.game,a,b,d,e,f))},tilemap:function(a,b,d,e,f){return new c.Tilemap(this.game,a,b,d,e,f)},renderTexture:function(a,b,d,e){(void 0===d||""===d)&&(d=this.game.rnd.uuid()),void 0===e&&(e=!1);var f=new c.RenderTexture(this.game,a,b,d);return e&&this.game.cache.addRenderTexture(d,f),f},video:function(a,b){return new c.Video(this.game,a,b)},bitmapData:function(a,b,d,e){void 0===e&&(e=!1),(void 0===d||""===d)&&(d=this.game.rnd.uuid());var f=new c.BitmapData(this.game,d,a,b);return e&&this.game.cache.addBitmapData(d,f),f},filter:function(a){var b=Array.prototype.splice.call(arguments,1),a=new c.Filter[a](this.game);return a.init.apply(a,b),a},plugin:function(a){return this.game.plugins.add(a)}},c.GameObjectFactory.prototype.constructor=c.GameObjectFactory,c.GameObjectCreator=function(a){this.game=a,this.world=this.game.world},c.GameObjectCreator.prototype={image:function(a,b,d,e){return new c.Image(this.game,a,b,d,e)},sprite:function(a,b,d,e){return new c.Sprite(this.game,a,b,d,e)},tween:function(a){return new c.Tween(a,this.game,this.game.tweens)},group:function(a,b,d,e,f){return new c.Group(this.game,a,b,d,e,f)},spriteBatch:function(a,b,d){return void 0===b&&(b="group"),void 0===d&&(d=!1),new c.SpriteBatch(this.game,a,b,d)},audio:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},audioSprite:function(a){return this.game.sound.addSprite(a)},sound:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},tileSprite:function(a,b,d,e,f,g){return new c.TileSprite(this.game,a,b,d,e,f,g)},rope:function(a,b,d,e,f){return new c.Rope(this.game,a,b,d,e,f)},text:function(a,b,d,e){return new c.Text(this.game,a,b,d,e)},button:function(a,b,d,e,f,g,h,i,j){return new c.Button(this.game,a,b,d,e,f,g,h,i,j)},graphics:function(a,b){return new c.Graphics(this.game,a,b)},emitter:function(a,b,d){return new c.Particles.Arcade.Emitter(this.game,a,b,d)},retroFont:function(a,b,d,e,f,g,h,i,j){return new c.RetroFont(this.game,a,b,d,e,f,g,h,i,j)},bitmapText:function(a,b,d,e,f,g){return new c.BitmapText(this.game,a,b,d,e,f,g)},tilemap:function(a,b,d,e,f){return new c.Tilemap(this.game,a,b,d,e,f)},renderTexture:function(a,b,d,e){(void 0===d||""===d)&&(d=this.game.rnd.uuid()),void 0===e&&(e=!1);var f=new c.RenderTexture(this.game,a,b,d);return e&&this.game.cache.addRenderTexture(d,f),f},bitmapData:function(a,b,d,e){void 0===e&&(e=!1),(void 0===d||""===d)&&(d=this.game.rnd.uuid());var f=new c.BitmapData(this.game,d,a,b);return e&&this.game.cache.addBitmapData(d,f),f},filter:function(a){var b=Array.prototype.splice.call(arguments,1),a=new c.Filter[a](this.game);return a.init.apply(a,b),a}},c.GameObjectCreator.prototype.constructor=c.GameObjectCreator,c.Sprite=function(a,b,d,e,f){b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.SPRITE,this.physicsType=c.SPRITE,PIXI.Sprite.call(this,PIXI.TextureCache.__default),c.Component.Core.init.call(this,a,b,d,e,f)},c.Sprite.prototype=Object.create(PIXI.Sprite.prototype),c.Sprite.prototype.constructor=c.Sprite,c.Component.Core.install.call(c.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),c.Sprite.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Sprite.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Sprite.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Sprite.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Sprite.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Image=function(a,b,d,e,f){b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.IMAGE,PIXI.Sprite.call(this,PIXI.TextureCache.__default),c.Component.Core.init.call(this,a,b,d,e,f)},c.Image.prototype=Object.create(PIXI.Sprite.prototype),c.Image.prototype.constructor=c.Image,c.Component.Core.install.call(c.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","Smoothed"]),c.Image.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Image.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Image.prototype.preUpdate=function(){return this.preUpdateInWorld()?this.preUpdateCore():!1},c.TileSprite=function(a,b,d,e,f,g,h){b=b||0,d=d||0,e=e||256,f=f||256,g=g||null,h=h||null,this.type=c.TILESPRITE,this.physicsType=c.SPRITE,this._scroll=new c.Point;var i=a.cache.getImage("__default",!0);PIXI.TilingSprite.call(this,new PIXI.Texture(i.base),e,f),c.Component.Core.init.call(this,a,b,d,g,h)},c.TileSprite.prototype=Object.create(PIXI.TilingSprite.prototype),c.TileSprite.prototype.constructor=c.TileSprite,c.Component.Core.install.call(c.TileSprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","Smoothed"]),c.TileSprite.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.TileSprite.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.TileSprite.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.TileSprite.prototype.preUpdateCore=c.Component.Core.preUpdate,c.TileSprite.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.TileSprite.prototype.autoScroll=function(a,b){this._scroll.set(a,b)},c.TileSprite.prototype.stopScroll=function(){this._scroll.set(0,0)},c.TileSprite.prototype.destroy=function(a){c.Component.Destroy.prototype.destroy.call(this,a),PIXI.TilingSprite.prototype.destroy.call(this)},c.TileSprite.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},c.Rope=function(a,b,d,e,f,g){this.points=[],this.points=g,this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.ROPE,this._scroll=new c.Point,PIXI.Rope.call(this,PIXI.TextureCache.__default,this.points),c.Component.Core.init.call(this,a,b,d,e,f)},c.Rope.prototype=Object.create(PIXI.Rope.prototype),c.Rope.prototype.constructor=c.Rope,c.Component.Core.install.call(c.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),c.Rope.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Rope.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Rope.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Rope.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Rope.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},c.Rope.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},Object.defineProperty(c.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(a){a&&"function"==typeof a?(this._hasUpdateAnimation=!0,this._updateAnimation=a):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(c.Rope.prototype,"segments",{get:function(){for(var a,b,d,e,f,g,h,i,j=[],k=0;k<this.points.length;k++)a=4*k,b=this.vertices[a]*this.scale.x,d=this.vertices[a+1]*this.scale.y,e=this.vertices[a+4]*this.scale.x,f=this.vertices[a+3]*this.scale.y,g=c.Math.difference(b,e),h=c.Math.difference(d,f),b+=this.world.x,d+=this.world.y,i=new c.Rectangle(b,d,g,h),j.push(i);return j}}),c.Button=function(a,b,d,e,f,g,h,i,j,k){b=b||0,d=d||0,e=e||null,f=f||null,g=g||this,c.Image.call(this,a,b,d,e,i),this.type=c.BUTTON,this.physicsType=c.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new c.Signal,this.onInputOut=new c.Signal,this.onInputDown=new c.Signal,this.onInputUp=new c.Signal,this.onOverMouseOnly=!1,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(h,i,j,k),null!==f&&this.onInputUp.add(f,g),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this),this.events.onRemovedFromWorld.add(this.removedFromWorld,this)},c.Button.prototype=Object.create(c.Image.prototype),c.Button.prototype.constructor=c.Button;var f="Over",g="Out",h="Down",i="Up";c.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},c.Button.prototype.removedFromWorld=function(){this.inputEnabled=!1},c.Button.prototype.setStateFrame=function(a,b,c){var d="_on"+a+"Frame";null!==b?(this[d]=b,c&&this.changeStateFrame(a)):this[d]=null},c.Button.prototype.changeStateFrame=function(a){if(this.freezeFrames)return!1;var b="_on"+a+"Frame",c=this[b];return"string"==typeof c?(this.frameName=c,!0):"number"==typeof c?(this.frame=c,!0):!1},c.Button.prototype.setFrames=function(a,b,c,d){this.setStateFrame(f,a,this.input.pointerOver()),this.setStateFrame(g,b,!this.input.pointerOver()),this.setStateFrame(h,c,this.input.pointerDown()),this.setStateFrame(i,d,this.input.pointerUp())},c.Button.prototype.setStateSound=function(a,b,d){var e="on"+a+"Sound",f="on"+a+"SoundMarker";b instanceof c.Sound||b instanceof c.AudioSprite?(this[e]=b,this[f]="string"==typeof d?d:""):(this[e]=null,this[f]="")},c.Button.prototype.playStateSound=function(a){var b="on"+a+"Sound",c=this[b];if(c){var d="on"+a+"SoundMarker",e=this[d];return c.play(e),!0}return!1},c.Button.prototype.setSounds=function(a,b,c,d,e,j,k,l){this.setStateSound(f,a,b),this.setStateSound(g,e,j),this.setStateSound(h,c,d),this.setStateSound(i,k,l)
-},c.Button.prototype.setOverSound=function(a,b){this.setStateSound(f,a,b)},c.Button.prototype.setOutSound=function(a,b){this.setStateSound(g,a,b)},c.Button.prototype.setDownSound=function(a,b){this.setStateSound(h,a,b)},c.Button.prototype.setUpSound=function(a,b){this.setStateSound(i,a,b)},c.Button.prototype.onInputOverHandler=function(a,b){b.justReleased()||(this.changeStateFrame(f),(!this.onOverMouseOnly||b.isMouse)&&(this.playStateSound(f),this.onInputOver&&this.onInputOver.dispatch(this,b)))},c.Button.prototype.onInputOutHandler=function(a,b){this.changeStateFrame(g),this.playStateSound(g),this.onInputOut&&this.onInputOut.dispatch(this,b)},c.Button.prototype.onInputDownHandler=function(a,b){this.changeStateFrame(h),this.playStateSound(h),this.onInputDown&&this.onInputDown.dispatch(this,b)},c.Button.prototype.onInputUpHandler=function(a,b,c){if(this.playStateSound(i),this.onInputUp&&this.onInputUp.dispatch(this,b,c),!this.freezeFrames)if(this.forceOut)this.changeStateFrame(g);else{var d=this.changeStateFrame(i);d||this.changeStateFrame(c?f:g)}},c.SpriteBatch=function(a,b,d,e){(void 0===b||null===b)&&(b=a.world),PIXI.SpriteBatch.call(this),c.Group.call(this,a,b,d,e),this.type=c.SPRITEBATCH},c.SpriteBatch.prototype=c.Utils.extend(!0,c.SpriteBatch.prototype,c.Group.prototype,PIXI.SpriteBatch.prototype),c.SpriteBatch.prototype.constructor=c.SpriteBatch,c.Particle=function(a,b,d,e,f){c.Sprite.call(this,a,b,d,e,f),this.autoScale=!1,this.scaleData=null,this._s=0,this.autoAlpha=!1,this.alphaData=null,this._a=0},c.Particle.prototype=Object.create(c.Sprite.prototype),c.Particle.prototype.constructor=c.Particle,c.Particle.prototype.update=function(){this.autoScale&&(this._s--,this._s?this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y):this.autoScale=!1),this.autoAlpha&&(this._a--,this._a?this.alpha=this.alphaData[this._a].v:this.autoAlpha=!1)},c.Particle.prototype.onEmit=function(){},c.Particle.prototype.setAlphaData=function(a){this.alphaData=a,this._a=a.length-1,this.alpha=this.alphaData[this._a].v,this.autoAlpha=!0},c.Particle.prototype.setScaleData=function(a){this.scaleData=a,this._s=a.length-1,this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y),this.autoScale=!0},c.Particle.prototype.reset=function(a,b,d){return c.Component.Reset.prototype.reset.call(this,a,b,d),this.alpha=1,this.scale.set(1),this.autoScale=!1,this.autoAlpha=!1,this},c.BitmapData=function(a,b,d,e){(void 0===d||0===d)&&(d=256),(void 0===e||0===e)&&(e=256),this.game=a,this.key=b,this.width=d,this.height=e,this.canvas=c.Canvas.create(d,e,"",!0),this.context=this.canvas.getContext("2d",{alpha:!0}),this.ctx=this.context,this.imageData=this.context.getImageData(0,0,d,e),this.data=null,this.imageData&&(this.data=this.imageData.data),this.pixels=null,this.data&&(this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data),this.baseTexture=new PIXI.BaseTexture(this.canvas),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new c.Frame(0,0,0,d,e,"bitmapData"),this.texture.frame=this.textureFrame,this.type=c.BITMAPDATA,this.disableTextureUpload=!1,this.dirty=!1,this.cls=this.clear,this._image=null,this._pos=new c.Point,this._size=new c.Point,this._scale=new c.Point,this._rotate=0,this._alpha={prev:1,current:1},this._anchor=new c.Point,this._tempR=0,this._tempG=0,this._tempB=0,this._circle=new c.Circle,this._swapCanvas=c.Canvas.create(d,e,"",!0)},c.BitmapData.prototype={move:function(a,b){return 0!==a&&this.moveH(a),0!==b&&this.moveV(b),this},moveH:function(a){var b=this._swapCanvas,c=b.getContext("2d"),d=this.height,e=this.canvas;if(c.clearRect(0,0,this.width,this.height),0>a){a=Math.abs(a);var f=this.width-a;c.drawImage(e,0,0,a,d,f,0,a,d),c.drawImage(e,a,0,f,d,0,0,f,d)}else{var f=this.width-a;c.drawImage(e,f,0,a,d,0,0,a,d),c.drawImage(e,0,0,f,d,a,0,f,d)}return this.clear(),this.copy(this._swapCanvas)},moveV:function(a){var b=this._swapCanvas,c=b.getContext("2d"),d=this.width,e=this.canvas;if(c.clearRect(0,0,this.width,this.height),0>a){a=Math.abs(a);var f=this.height-a;c.drawImage(e,0,0,d,a,0,f,d,a),c.drawImage(e,0,a,d,f,0,0,d,f)}else{var f=this.height-a;c.drawImage(e,0,f,d,a,0,0,d,a),c.drawImage(e,0,0,d,f,0,a,d,f)}return this.clear(),this.copy(this._swapCanvas)},add:function(a){if(Array.isArray(a))for(var b=0;b<a.length;b++)a[b].loadTexture&&a[b].loadTexture(this);else a.loadTexture(this);return this},load:function(a){return"string"==typeof a&&(a=this.game.cache.getImage(a)),a?(this.resize(a.width,a.height),this.cls(),this.draw(a),this.update(),this):void 0},clear:function(a,b,c,d){return void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c=this.width),void 0===d&&(d=this.height),this.context.clearRect(a,b,c,d),this.dirty=!0,this},fill:function(a,b,c,d){return void 0===d&&(d=1),this.context.fillStyle="rgba("+a+","+b+","+c+","+d+")",this.context.fillRect(0,0,this.width,this.height),this.dirty=!0,this},generateTexture:function(a){var b=new Image;b.src=this.canvas.toDataURL("image/png");var c=this.game.cache.addImage(a,"",b);return new PIXI.Texture(c.base)},resize:function(a,b){return(a!==this.width||b!==this.height)&&(this.width=a,this.height=b,this.canvas.width=a,this.canvas.height=b,this._swapCanvas.width=a,this._swapCanvas.height=b,this.baseTexture.width=a,this.baseTexture.height=b,this.textureFrame.width=a,this.textureFrame.height=b,this.texture.width=a,this.texture.height=b,this.texture.crop.width=a,this.texture.crop.height=b,this.update(),this.dirty=!0),this},update:function(a,b,c,d){return void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c=Math.max(1,this.width)),void 0===d&&(d=Math.max(1,this.height)),this.imageData=this.context.getImageData(a,b,c,d),this.data=this.imageData.data,this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data,this},processPixelRGB:function(a,b,d,e,f,g){void 0===d&&(d=0),void 0===e&&(e=0),void 0===f&&(f=this.width),void 0===g&&(g=this.height);for(var h=d+f,i=e+g,j=c.Color.createColor(),k={r:0,g:0,b:0,a:0},l=!1,m=e;i>m;m++)for(var n=d;h>n;n++)c.Color.unpackPixel(this.getPixel32(n,m),j),k=a.call(b,j,n,m),k!==!1&&null!==k&&void 0!==k&&(this.setPixel32(n,m,k.r,k.g,k.b,k.a,!1),l=!0);return l&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},processPixel:function(a,b,c,d,e,f){void 0===c&&(c=0),void 0===d&&(d=0),void 0===e&&(e=this.width),void 0===f&&(f=this.height);for(var g=c+e,h=d+f,i=0,j=0,k=!1,l=d;h>l;l++)for(var m=c;g>m;m++)i=this.getPixel32(m,l),j=a.call(b,i,m,l),j!==i&&(this.pixels[l*this.width+m]=j,k=!0);return k&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},replaceRGB:function(a,b,d,e,f,g,h,i,j){var k=0,l=0,m=this.width,n=this.height,o=c.Color.packPixel(a,b,d,e);void 0!==j&&j instanceof c.Rectangle&&(k=j.x,l=j.y,m=j.width,n=j.height);for(var p=0;n>p;p++)for(var q=0;m>q;q++)this.getPixel32(k+q,l+p)===o&&this.setPixel32(k+q,l+p,f,g,h,i,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this},setHSL:function(a,b,d,e){if((void 0===a||null===a)&&(a=!1),(void 0===b||null===b)&&(b=!1),(void 0===d||null===d)&&(d=!1),a||b||d){void 0===e&&(e=new c.Rectangle(0,0,this.width,this.height));for(var f=c.Color.createColor(),g=e.y;g<e.bottom;g++)for(var h=e.x;h<e.right;h++)c.Color.unpackPixel(this.getPixel32(h,g),f,!0),a&&(f.h=a),b&&(f.s=b),d&&(f.l=d),c.Color.HSLtoRGB(f.h,f.s,f.l,f),this.setPixel32(h,g,f.r,f.g,f.b,f.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},shiftHSL:function(a,b,d,e){if((void 0===a||null===a)&&(a=!1),(void 0===b||null===b)&&(b=!1),(void 0===d||null===d)&&(d=!1),a||b||d){void 0===e&&(e=new c.Rectangle(0,0,this.width,this.height));for(var f=c.Color.createColor(),g=e.y;g<e.bottom;g++)for(var h=e.x;h<e.right;h++)c.Color.unpackPixel(this.getPixel32(h,g),f,!0),a&&(f.h=this.game.math.wrap(f.h+a,0,1)),b&&(f.s=this.game.math.limitValue(f.s+b,0,1)),d&&(f.l=this.game.math.limitValue(f.l+d,0,1)),c.Color.HSLtoRGB(f.h,f.s,f.l,f),this.setPixel32(h,g,f.r,f.g,f.b,f.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},setPixel32:function(a,b,d,e,f,g,h){return void 0===h&&(h=!0),a>=0&&a<=this.width&&b>=0&&b<=this.height&&(this.pixels[b*this.width+a]=c.Device.LITTLE_ENDIAN?g<<24|f<<16|e<<8|d:d<<24|e<<16|f<<8|g,h&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(a,b,c,d,e,f){return this.setPixel32(a,b,c,d,e,255,f)},getPixel:function(a,b,d){d||(d=c.Color.createColor());var e=~~(a+b*this.width);return e*=4,d.r=this.data[e],d.g=this.data[++e],d.b=this.data[++e],d.a=this.data[++e],d},getPixel32:function(a,b){return a>=0&&a<=this.width&&b>=0&&b<=this.height?this.pixels[b*this.width+a]:void 0},getPixelRGB:function(a,b,d,e,f){return c.Color.unpackPixel(this.getPixel32(a,b),d,e,f)},getPixels:function(a){return this.context.getImageData(a.x,a.y,a.width,a.height)},getFirstPixel:function(a){void 0===a&&(a=0);var b=c.Color.createColor(),d=0,e=0,f=1,g=!1;1===a?(f=-1,e=this.height):3===a&&(f=-1,d=this.width);do c.Color.unpackPixel(this.getPixel32(d,e),b),0===a||1===a?(d++,d===this.width&&(d=0,e+=f,(e>=this.height||0>=e)&&(g=!0))):(2===a||3===a)&&(e++,e===this.height&&(e=0,d+=f,(d>=this.width||0>=d)&&(g=!0)));while(0===b.a&&!g);return b.x=d,b.y=e,b},getBounds:function(a){return void 0===a&&(a=new c.Rectangle),a.x=this.getFirstPixel(2).x,a.x===this.width?a.setTo(0,0,0,0):(a.y=this.getFirstPixel(0).y,a.width=this.getFirstPixel(3).x-a.x+1,a.height=this.getFirstPixel(1).y-a.y+1,a)},addToWorld:function(a,b,c,d,e,f){e=e||1,f=f||1;var g=this.game.add.image(a,b,this);return g.anchor.set(c,d),g.scale.set(e,f),g},copy:function(a,b,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){if((void 0===a||null===a)&&(a=this),this._image=a,a instanceof c.Sprite||a instanceof c.Image||a instanceof c.Text)this._pos.set(a.texture.crop.x,a.texture.crop.y),this._size.set(a.texture.crop.width,a.texture.crop.height),this._scale.set(a.scale.x,a.scale.y),this._anchor.set(a.anchor.x,a.anchor.y),this._rotate=a.rotation,this._alpha.current=a.alpha,this._image=a.texture.baseTexture.source,(void 0===g||null===g)&&(g=a.x),(void 0===h||null===h)&&(h=a.y),a.texture.trim&&(g+=a.texture.trim.x-a.anchor.x*a.texture.trim.width,h+=a.texture.trim.y-a.anchor.y*a.texture.trim.height),16777215!==a.tint&&(a.cachedTint!==a.tint&&(a.cachedTint=a.tint,a.tintedTexture=PIXI.CanvasTinter.getTintedTexture(a,a.tint)),this._image=a.tintedTexture);else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,a instanceof c.BitmapData)this._image=a.canvas;else if("string"==typeof a){if(a=this.game.cache.getImage(a),null===a)return;this._image=a}this._size.set(this._image.width,this._image.height)}return(void 0===b||null===b)&&(b=0),(void 0===d||null===d)&&(d=0),e&&(this._size.x=e),f&&(this._size.y=f),(void 0===g||null===g)&&(g=b),(void 0===h||null===h)&&(h=d),(void 0===i||null===i)&&(i=this._size.x),(void 0===j||null===j)&&(j=this._size.y),"number"==typeof k&&(this._rotate=k),"number"==typeof l&&(this._anchor.x=l),"number"==typeof m&&(this._anchor.y=m),"number"==typeof n&&(this._scale.x=n),"number"==typeof o&&(this._scale.y=o),"number"==typeof p&&(this._alpha.current=p),void 0===q&&(q=null),void 0===r&&(r=!1),this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y?void 0:(this._alpha.prev=this.context.globalAlpha,this.context.save(),this.context.globalAlpha=this._alpha.current,q&&(this.context.globalCompositeOperation=q),r&&(g|=0,h|=0),this.context.translate(g,h),this.context.scale(this._scale.x,this._scale.y),this.context.rotate(this._rotate),this.context.drawImage(this._image,this._pos.x+b,this._pos.y+d,this._size.x,this._size.y,-i*this._anchor.x,-j*this._anchor.y,i,j),this.context.restore(),this.context.globalAlpha=this._alpha.prev,this.dirty=!0,this)},copyRect:function(a,b,c,d,e,f,g){return this.copy(a,b.x,b.y,b.width,b.height,c,d,b.width,b.height,0,0,0,1,1,e,f,g)},draw:function(a,b,c,d,e,f,g){return this.copy(a,null,null,null,null,b,c,d,e,null,null,null,null,null,null,f,g)},drawGroup:function(a,b,c){return a.total>0&&a.forEachExists(this.copy,this,null,null,null,null,null,null,null,null,null,null,null,null,null,null,b,c),this},shadow:function(a,b,c,d){void 0===a||null===a?this.context.shadowColor="rgba(0,0,0,0)":(this.context.shadowColor=a,this.context.shadowBlur=b||5,this.context.shadowOffsetX=c||10,this.context.shadowOffsetY=d||10)},alphaMask:function(a,b,c,d){return void 0===d||null===d?this.draw(b).blendSourceAtop():this.draw(b,d.x,d.y,d.width,d.height).blendSourceAtop(),void 0===c||null===c?this.draw(a).blendReset():this.draw(a,c.x,c.y,c.width,c.height).blendReset(),this},extract:function(a,b,c,d,e,f,g,h,i){return void 0===e&&(e=255),void 0===f&&(f=!1),void 0===g&&(g=b),void 0===h&&(h=c),void 0===i&&(i=d),f&&a.resize(this.width,this.height),this.processPixelRGB(function(f,j,k){return f.r===b&&f.g===c&&f.b===d&&a.setPixel32(j,k,g,h,i,e,!1),!1},this),a.context.putImageData(a.imageData,0,0),a.dirty=!0,a},rect:function(a,b,c,d,e){return"undefined"!=typeof e&&(this.context.fillStyle=e),this.context.fillRect(a,b,c,d),this},text:function(a,b,c,d,e,f){void 0===b&&(b=0),void 0===c&&(c=0),void 0===d&&(d="14px Courier"),void 0===e&&(e="rgb(255,255,255)"),void 0===f&&(f=!0);var g=this.context.font;this.context.font=d,f&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(a,b+1,c+1)),this.context.fillStyle=e,this.context.fillText(a,b,c),this.context.font=g},circle:function(a,b,c,d){return"undefined"!=typeof d&&(this.context.fillStyle=d),this.context.beginPath(),this.context.arc(a,b,c,0,2*Math.PI,!1),this.context.closePath(),this.context.fill(),this},textureLine:function(a,b,d){if(void 0===d&&(d="repeat-x"),"string"!=typeof b||(b=this.game.cache.getImage(b))){var e=a.length;return"no-repeat"===d&&e>b.width&&(e=b.width),this.context.fillStyle=this.context.createPattern(b,d),this._circle=new c.Circle(a.start.x,a.start.y,b.height),this._circle.circumferencePoint(a.angle-1.5707963267948966,!1,this._pos),this.context.save(),this.context.translate(this._pos.x,this._pos.y),this.context.rotate(a.angle),this.context.fillRect(0,0,e,b.height),this.context.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},blendReset:function(){return this.context.globalCompositeOperation="source-over",this},blendSourceOver:function(){return this.context.globalCompositeOperation="source-over",this},blendSourceIn:function(){return this.context.globalCompositeOperation="source-in",this},blendSourceOut:function(){return this.context.globalCompositeOperation="source-out",this},blendSourceAtop:function(){return this.context.globalCompositeOperation="source-atop",this},blendDestinationOver:function(){return this.context.globalCompositeOperation="destination-over",this},blendDestinationIn:function(){return this.context.globalCompositeOperation="destination-in",this},blendDestinationOut:function(){return this.context.globalCompositeOperation="destination-out",this},blendDestinationAtop:function(){return this.context.globalCompositeOperation="destination-atop",this},blendXor:function(){return this.context.globalCompositeOperation="xor",this},blendAdd:function(){return this.context.globalCompositeOperation="lighter",this},blendMultiply:function(){return this.context.globalCompositeOperation="multiply",this},blendScreen:function(){return this.context.globalCompositeOperation="screen",this},blendOverlay:function(){return this.context.globalCompositeOperation="overlay",this},blendDarken:function(){return this.context.globalCompositeOperation="darken",this},blendLighten:function(){return this.context.globalCompositeOperation="lighten",this},blendColorDodge:function(){return this.context.globalCompositeOperation="color-dodge",this},blendColorBurn:function(){return this.context.globalCompositeOperation="color-burn",this},blendHardLight:function(){return this.context.globalCompositeOperation="hard-light",this},blendSoftLight:function(){return this.context.globalCompositeOperation="soft-light",this},blendDifference:function(){return this.context.globalCompositeOperation="difference",this},blendExclusion:function(){return this.context.globalCompositeOperation="exclusion",this},blendHue:function(){return this.context.globalCompositeOperation="hue",this},blendSaturation:function(){return this.context.globalCompositeOperation="saturation",this},blendColor:function(){return this.context.globalCompositeOperation="color",this},blendLuminosity:function(){return this.context.globalCompositeOperation="luminosity",this}},Object.defineProperty(c.BitmapData.prototype,"smoothed",{get:function(){c.Canvas.getSmoothingEnabled(this.context)},set:function(a){c.Canvas.setSmoothingEnabled(this.context,a)}}),c.BitmapData.getTransform=function(a,b,c,d,e,f){return"number"!=typeof a&&(a=0),"number"!=typeof b&&(b=0),"number"!=typeof c&&(c=1),"number"!=typeof d&&(d=1),"number"!=typeof e&&(e=0),"number"!=typeof f&&(f=0),{sx:c,sy:d,scaleX:c,scaleY:d,skewX:e,skewY:f,translateX:a,translateY:b,tx:a,ty:b}},c.BitmapData.prototype.constructor=c.BitmapData,PIXI.Graphics=function(){PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new PIXI.Rectangle(0,0,1,1),this.dirty=!0,this.webGLDirty=!1,this.cachedSpriteDirty=!1},PIXI.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),PIXI.Graphics.prototype.constructor=PIXI.Graphics,PIXI.Graphics.prototype.lineStyle=function(a,b,c){return this.lineWidth=a||0,this.lineColor=b||0,this.lineAlpha=void 0===c?1:c,this.currentPath&&(this.currentPath.shape.points.length?this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))):(this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha)),this},PIXI.Graphics.prototype.moveTo=function(a,b){return this.drawShape(new PIXI.Polygon([a,b])),this},PIXI.Graphics.prototype.lineTo=function(a,b){return this.currentPath||this.moveTo(0,0),this.currentPath.shape.points.push(a,b),this.dirty=!0,this},PIXI.Graphics.prototype.quadraticCurveTo=function(a,b,c,d){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var e,f,g=20,h=this.currentPath.shape.points;0===h.length&&this.moveTo(0,0);for(var i=h[h.length-2],j=h[h.length-1],k=0,l=1;g>=l;++l)k=l/g,e=i+(a-i)*k,f=j+(b-j)*k,h.push(e+(a+(c-a)*k-e)*k,f+(b+(d-b)*k-f)*k);return this.dirty=!0,this},PIXI.Graphics.prototype.bezierCurveTo=function(a,b,c,d,e,f){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);for(var g,h,i,j,k,l=20,m=this.currentPath.shape.points,n=m[m.length-2],o=m[m.length-1],p=0,q=1;l>=q;++q)p=q/l,g=1-p,h=g*g,i=h*g,j=p*p,k=j*p,m.push(i*n+3*h*p*a+3*g*j*c+k*e,i*o+3*h*p*b+3*g*j*d+k*f);return this.dirty=!0,this},PIXI.Graphics.prototype.arcTo=function(a,b,c,d,e){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(a,b):this.moveTo(a,b);var f=this.currentPath.shape.points,g=f[f.length-2],h=f[f.length-1],i=h-b,j=g-a,k=d-b,l=c-a,m=Math.abs(i*l-j*k);if(1e-8>m||0===e)(f[f.length-2]!==a||f[f.length-1]!==b)&&f.push(a,b);else{var n=i*i+j*j,o=k*k+l*l,p=i*k+j*l,q=e*Math.sqrt(n)/m,r=e*Math.sqrt(o)/m,s=q*p/n,t=r*p/o,u=q*l+r*j,v=q*k+r*i,w=j*(r+s),x=i*(r+s),y=l*(q+t),z=k*(q+t),A=Math.atan2(x-v,w-u),B=Math.atan2(z-v,y-u);this.arc(u+a,v+b,e,A,B,j*k>l*i)}return this.dirty=!0,this},PIXI.Graphics.prototype.arc=function(a,b,c,d,e,f){if(d===e)return this;void 0===f&&(f=!1),!f&&d>=e?e+=2*Math.PI:f&&e>=d&&(d+=2*Math.PI);var g=f?-1*(d-e):e-d,h=40*Math.ceil(Math.abs(g)/(2*Math.PI));if(0===g)return this;var i=a+Math.cos(d)*c,j=b+Math.sin(d)*c;f&&this.filling?this.moveTo(a,b):this.moveTo(i,j);for(var k=this.currentPath.shape.points,l=g/(2*h),m=2*l,n=Math.cos(l),o=Math.sin(l),p=h-1,q=p%1/p,r=0;p>=r;r++){var s=r+q*r,t=l+d+m*s,u=Math.cos(t),v=-Math.sin(t);k.push((n*u+o*v)*c+a,(n*-v+o*u)*c+b)}return this.dirty=!0,this},PIXI.Graphics.prototype.beginFill=function(a,b){return this.filling=!0,this.fillColor=a||0,this.fillAlpha=void 0===b?1:b,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},PIXI.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},PIXI.Graphics.prototype.drawRect=function(a,b,c,d){return this.drawShape(new PIXI.Rectangle(a,b,c,d)),this},PIXI.Graphics.prototype.drawRoundedRect=function(a,b,c,d,e){return this.drawShape(new PIXI.RoundedRectangle(a,b,c,d,e)),this},PIXI.Graphics.prototype.drawCircle=function(a,b,c){return this.drawShape(new PIXI.Circle(a,b,c)),this},PIXI.Graphics.prototype.drawEllipse=function(a,b,c,d){return this.drawShape(new PIXI.Ellipse(a,b,c,d)),this},PIXI.Graphics.prototype.drawPolygon=function(a){(a instanceof c.Polygon||a instanceof PIXI.Polygon)&&(a=a.points);var b=a;if(!Array.isArray(b)){b=new Array(arguments.length);for(var d=0;d<b.length;++d)b[d]=arguments[d]}return this.drawShape(new c.Polygon(b)),this},PIXI.Graphics.prototype.clear=function(){return this.lineWidth=0,this.filling=!1,this.dirty=!0,this.clearDirty=!0,this.graphicsData=[],this},PIXI.Graphics.prototype.generateTexture=function(a,b){a=a||1;var c=this.getBounds(),d=new PIXI.CanvasBuffer(c.width*a,c.height*a),e=PIXI.Texture.fromCanvas(d.canvas,b);return e.baseTexture.resolution=a,d.context.scale(a,a),d.context.translate(-c.x,-c.y),PIXI.CanvasGraphics.renderGraphics(this,d.context),e},PIXI.Graphics.prototype._renderWebGL=function(a){if(this.visible!==!1&&0!==this.alpha&&this.isMask!==!0){if(this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.worldAlpha=this.worldAlpha,void PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite,a);if(a.spriteBatch.stop(),a.blendModeManager.setBlendMode(this.blendMode),this._mask&&a.maskManager.pushMask(this._mask,a),this._filters&&a.filterManager.pushFilter(this._filterBlock),this.blendMode!==a.spriteBatch.currentBlendMode){a.spriteBatch.currentBlendMode=this.blendMode;var b=PIXI.blendModesWebGL[a.spriteBatch.currentBlendMode];a.spriteBatch.gl.blendFunc(b[0],b[1])}if(this.webGLDirty&&(this.dirty=!0,this.webGLDirty=!1),PIXI.WebGLGraphics.renderGraphics(this,a),this.children.length){a.spriteBatch.start();for(var c=0;c<this.children.length;c++)this.children[c]._renderWebGL(a);a.spriteBatch.stop()}this._filters&&a.filterManager.popFilter(),this._mask&&a.maskManager.popMask(this.mask,a),a.drawCount++,a.spriteBatch.start()}},PIXI.Graphics.prototype._renderCanvas=function(a){if(this.visible!==!1&&0!==this.alpha&&this.isMask!==!0){if(this._prevTint!==this.tint&&(this.dirty=!0,this._prevTint=this.tint),this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.alpha=this.alpha,void PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite,a);var b=a.context,c=this.worldTransform;this.blendMode!==a.currentBlendMode&&(a.currentBlendMode=this.blendMode,b.globalCompositeOperation=PIXI.blendModesCanvas[a.currentBlendMode]),this._mask&&a.maskManager.pushMask(this._mask,a);var d=a.resolution;b.setTransform(c.a*d,c.b*d,c.c*d,c.d*d,c.tx*d,c.ty*d),PIXI.CanvasGraphics.renderGraphics(this,b);for(var e=0;e<this.children.length;e++)this.children[e]._renderCanvas(a);this._mask&&a.maskManager.popMask(a)}},PIXI.Graphics.prototype.getBounds=function(a){if(!this._currentBounds){if(!this.renderable)return PIXI.EmptyRectangle;this.dirty&&(this.updateLocalBounds(),this.webGLDirty=!0,this.cachedSpriteDirty=!0,this.dirty=!1);var b=this._localBounds,c=b.x,d=b.width+b.x,e=b.y,f=b.height+b.y,g=a||this.worldTransform,h=g.a,i=g.b,j=g.c,k=g.d,l=g.tx,m=g.ty,n=h*d+j*f+l,o=k*f+i*d+m,p=h*c+j*f+l,q=k*f+i*c+m,r=h*c+j*e+l,s=k*e+i*c+m,t=h*d+j*e+l,u=k*e+i*d+m,v=n,w=o,x=n,y=o;x=x>p?p:x,x=x>r?r:x,x=x>t?t:x,y=y>q?q:y,y=y>s?s:y,y=y>u?u:y,v=p>v?p:v,v=r>v?r:v,v=t>v?t:v,w=q>w?q:w,w=s>w?s:w,w=u>w?u:w,this._bounds.x=x,this._bounds.width=v-x,this._bounds.y=y,this._bounds.height=w-y,this._currentBounds=this._bounds}return this._currentBounds},PIXI.Graphics.prototype.containsPoint=function(a){this.worldTransform.applyInverse(a,tempPoint);for(var b=this.graphicsData,c=0;c<b.length;c++){var d=b[c];if(d.fill&&d.shape&&d.shape.contains(tempPoint.x,tempPoint.y))return!0}return!1},PIXI.Graphics.prototype.updateLocalBounds=function(){var a=1/0,b=-1/0,d=1/0,e=-1/0;if(this.graphicsData.length)for(var f,g,h,i,j,k,l=0;l<this.graphicsData.length;l++){var m=this.graphicsData[l],n=m.type,o=m.lineWidth;if(f=m.shape,n===PIXI.Graphics.RECT||n===PIXI.Graphics.RREC)h=f.x-o/2,i=f.y-o/2,j=f.width+o,k=f.height+o,a=a>h?h:a,b=h+j>b?h+j:b,d=d>i?i:d,e=i+k>e?i+k:e;else if(n===PIXI.Graphics.CIRC)h=f.x,i=f.y,j=f.radius+o/2,k=f.radius+o/2,a=a>h-j?h-j:a,b=h+j>b?h+j:b,d=d>i-k?i-k:d,e=i+k>e?i+k:e;else if(n===PIXI.Graphics.ELIP)h=f.x,i=f.y,j=f.width+o/2,k=f.height+o/2,a=a>h-j?h-j:a,b=h+j>b?h+j:b,d=d>i-k?i-k:d,e=i+k>e?i+k:e;else{g=f.points;for(var p=0;p<g.length;p++)g[p]instanceof c.Point?(h=g[p].x,i=g[p].y):(h=g[p],i=g[p+1],p<g.length-1&&p++),a=a>h-o?h-o:a,b=h+o>b?h+o:b,d=d>i-o?i-o:d,e=i+o>e?i+o:e}}else a=0,b=0,d=0,e=0;var q=this.boundsPadding;this._localBounds.x=a-q,this._localBounds.width=b-a+2*q,this._localBounds.y=d-q,this._localBounds.height=e-d+2*q},PIXI.Graphics.prototype._generateCachedSprite=function(){var a=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(a.width,a.height);else{var b=new PIXI.CanvasBuffer(a.width,a.height),c=PIXI.Texture.fromCanvas(b.canvas);this._cachedSprite=new PIXI.Sprite(c),this._cachedSprite.buffer=b,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-(a.x/a.width),this._cachedSprite.anchor.y=-(a.y/a.height),this._cachedSprite.buffer.context.translate(-a.x,-a.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},PIXI.Graphics.prototype.updateCachedSpriteTexture=function(){var a=this._cachedSprite,b=a.texture,c=a.buffer.canvas;b.baseTexture.width=c.width,b.baseTexture.height=c.height,b.crop.width=b.frame.width=c.width,b.crop.height=b.frame.height=c.height,a._width=c.width,a._height=c.height,b.baseTexture.dirty()},PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},PIXI.Graphics.prototype.drawShape=function(a){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,a instanceof c.Polygon&&(a=a.clone(),a.flatten());var b=new PIXI.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,a);return this.graphicsData.push(b),b.type===PIXI.Graphics.POLY&&(b.shape.closed=this.filling,this.currentPath=b),this.dirty=!0,b},Object.defineProperty(PIXI.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(a){this._cacheAsBitmap=a,this._cacheAsBitmap?this._generateCachedSprite():(this.destroyCachedSprite(),this.dirty=!0)}}),PIXI.GraphicsData=function(a,b,c,d,e,f,g){this.lineWidth=a,this.lineColor=b,this.lineAlpha=c,this._lineTint=b,this.fillColor=d,this.fillAlpha=e,this._fillTint=d,this.fill=f,this.shape=g,this.type=g.type},PIXI.GraphicsData.prototype.constructor=PIXI.GraphicsData,PIXI.GraphicsData.prototype.clone=function(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},c.Graphics=function(a,b,d){void 0===b&&(b=0),void 0===d&&(d=0),this.type=c.GRAPHICS,this.physicsType=c.SPRITE,PIXI.Graphics.call(this),c.Component.Core.init.call(this,a,b,d,"",null)},c.Graphics.prototype=Object.create(PIXI.Graphics.prototype),c.Graphics.prototype.constructor=c.Graphics,c.Component.Core.install.call(c.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),c.Graphics.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Graphics.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Graphics.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Graphics.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Graphics.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Graphics.prototype.destroy=function(a){this.clear(),c.Component.Destroy.prototype.destroy.call(this,a)},c.Graphics.prototype.drawTriangle=function(a,b){void 0===b&&(b=!1);var d=new c.Polygon(a);if(b){var e=new c.Point(this.game.camera.x-a[0].x,this.game.camera.y-a[0].y),f=new c.Point(a[1].x-a[0].x,a[1].y-a[0].y),g=new c.Point(a[1].x-a[2].x,a[1].y-a[2].y),h=g.cross(f);e.dot(h)>0&&this.drawPolygon(d)}else this.drawPolygon(d)},c.Graphics.prototype.drawTriangles=function(a,b,d){void 0===d&&(d=!1);var e,f=new c.Point,g=new c.Point,h=new c.Point,i=[];if(b)if(a[0]instanceof c.Point)for(e=0;e<b.length/3;e++)i.push(a[b[3*e]]),i.push(a[b[3*e+1]]),i.push(a[b[3*e+2]]),3===i.length&&(this.drawTriangle(i,d),i=[]);else for(e=0;e<b.length;e++)f.x=a[2*b[e]],f.y=a[2*b[e]+1],i.push(f.copyTo({})),3===i.length&&(this.drawTriangle(i,d),i=[]);else if(a[0]instanceof c.Point)for(e=0;e<a.length/3;e++)this.drawTriangle([a[3*e],a[3*e+1],a[3*e+2]],d);else for(e=0;e<a.length/6;e++)f.x=a[6*e+0],f.y=a[6*e+1],g.x=a[6*e+2],g.y=a[6*e+3],h.x=a[6*e+4],h.y=a[6*e+5],this.drawTriangle([f,g,h],d)},c.RenderTexture=function(a,b,d,e,f,g){void 0===e&&(e=""),void 0===f&&(f=c.scaleModes.DEFAULT),void 0===g&&(g=1),this.game=a,this.key=e,this.type=c.RENDERTEXTURE,this._tempMatrix=new PIXI.Matrix,PIXI.RenderTexture.call(this,b,d,this.game.renderer,f,g),this.render=c.RenderTexture.prototype.render},c.RenderTexture.prototype=Object.create(PIXI.RenderTexture.prototype),c.RenderTexture.prototype.constructor=c.RenderTexture,c.RenderTexture.prototype.renderXY=function(a,b,c,d){a.updateTransform(),this._tempMatrix.copyFrom(a.worldTransform),this._tempMatrix.tx=b,this._tempMatrix.ty=c,this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(a,this._tempMatrix,d):this.renderCanvas(a,this._tempMatrix,d)},c.RenderTexture.prototype.renderRawXY=function(a,b,c,d){this._tempMatrix.identity().translate(b,c),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(a,this._tempMatrix,d):this.renderCanvas(a,this._tempMatrix,d)},c.RenderTexture.prototype.render=function(a,b,c){this._tempMatrix.copyFrom(void 0===b||null===b?a.worldTransform:b),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(a,this._tempMatrix,c):this.renderCanvas(a,this._tempMatrix,c)},c.Text=function(a,b,d,e,f){b=b||0,d=d||0,e=e.toString()||"",f=f||{},this.type=c.TEXT,this.physicsType=c.SPRITE,this.padding=new c.Point,this.textBounds=null,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.colors=[],this.strokeColors=[],this.autoRound=!1,this._res=a.renderer.resolution,this._text=e,this._fontComponents=null,this._lineSpacing=0,this._charCount=0,this._width=0,this._height=0,c.Sprite.call(this,a,b,d,PIXI.Texture.fromCanvas(this.canvas)),this.setStyle(f),""!==e&&this.updateText()},c.Text.prototype=Object.create(c.Sprite.prototype),c.Text.prototype.constructor=c.Text,c.Text.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1
-},c.Text.prototype.update=function(){},c.Text.prototype.destroy=function(a){this.texture.destroy(!0),this.canvas&&this.canvas.parentNode?this.canvas.parentNode.removeChild(this.canvas):(this.canvas=null,this.context=null),c.Component.Destroy.prototype.destroy.call(this,a)},c.Text.prototype.setShadow=function(a,b,c,d,e,f){return void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c="rgba(0, 0, 0, 1)"),void 0===d&&(d=0),void 0===e&&(e=!0),void 0===f&&(f=!0),this.style.shadowOffsetX=a,this.style.shadowOffsetY=b,this.style.shadowColor=c,this.style.shadowBlur=d,this.style.shadowStroke=e,this.style.shadowFill=f,this.dirty=!0,this},c.Text.prototype.setStyle=function(a){a=a||{},a.font=a.font||"bold 20pt Arial",a.backgroundColor=a.backgroundColor||null,a.fill=a.fill||"black",a.align=a.align||"left",a.boundsAlignH=a.boundsAlignH||"left",a.boundsAlignV=a.boundsAlignV||"top",a.stroke=a.stroke||"black",a.strokeThickness=a.strokeThickness||0,a.wordWrap=a.wordWrap||!1,a.wordWrapWidth=a.wordWrapWidth||100,a.shadowOffsetX=a.shadowOffsetX||0,a.shadowOffsetY=a.shadowOffsetY||0,a.shadowColor=a.shadowColor||"rgba(0,0,0,0)",a.shadowBlur=a.shadowBlur||0,a.tabs=a.tabs||0;var b=this.fontToComponents(a.font);return a.fontStyle&&(b.fontStyle=a.fontStyle),a.fontVariant&&(b.fontVariant=a.fontVariant),a.fontWeight&&(b.fontWeight=a.fontWeight),a.fontSize&&("number"==typeof a.fontSize&&(a.fontSize=a.fontSize+"px"),b.fontSize=a.fontSize),this._fontComponents=b,a.font=this.componentsToFont(this._fontComponents),this.style=a,this.dirty=!0,this},c.Text.prototype.updateText=function(){this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font;var a=this.text;this.style.wordWrap&&(a=this.runWordWrap(this.text));for(var b=a.split(/(?:\r\n|\r|\n)/),c=this.style.tabs,d=[],e=0,f=this.determineFontProperties(this.style.font),g=0;g<b.length;g++){if(0===c)var h=this.context.measureText(b[g]).width+this.style.strokeThickness+this.padding.x;else{var i=b[g].split(/(?:\t)/),h=this.padding.x+this.style.strokeThickness;if(Array.isArray(c))for(var j=0,k=0;k<i.length;k++){var l=Math.ceil(this.context.measureText(i[k]).width);k>0&&(j+=c[k-1]),h=j+l}else for(var k=0;k<i.length;k++){h+=Math.ceil(this.context.measureText(i[k]).width);var m=this.game.math.snapToCeil(h,c)-h;h+=m}}d[g]=Math.ceil(h),e=Math.max(e,d[g])}var n=e+this.style.strokeThickness;this.canvas.width=n*this._res;var o=f.fontSize+this.style.strokeThickness+this.padding.y,p=o*b.length,q=this._lineSpacing;if(0>q&&Math.abs(q)>o&&(q=-o),0!==q){var m=q*(b.length-1);p+=m}this.canvas.height=p*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var r,s;for(this._charCount=0,g=0;g<b.length;g++)r=this.style.strokeThickness/2,s=this.style.strokeThickness/2+g*o+f.ascent,g>0&&(s+=q*g),"right"===this.style.align?r+=e-d[g]:"center"===this.style.align&&(r+=(e-d[g])/2),this.autoRound&&(r=Math.round(r),s=Math.round(s)),this.colors.length>0||this.strokeColors.length>0?this.updateLine(b[g],r,s):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===c?this.context.strokeText(b[g],r,s):this.renderTabLine(b[g],r,s,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===c?this.context.fillText(b[g],r,s):this.renderTabLine(b[g],r,s,!0)));this.updateTexture()},c.Text.prototype.renderTabLine=function(a,b,c,d){var e=a.split(/(?:\t)/),f=this.style.tabs,g=0;if(Array.isArray(f))for(var h=0,i=0;i<e.length;i++)i>0&&(h+=f[i-1]),g=b+h,d?this.context.fillText(e[i],g,c):this.context.strokeText(e[i],g,c);else for(var i=0;i<e.length;i++){var j=Math.ceil(this.context.measureText(e[i]).width);g=this.game.math.snapToCeil(b,f),d?this.context.fillText(e[i],g,c):this.context.strokeText(e[i],g,c),b=g+j}},c.Text.prototype.updateShadow=function(a){a?(this.context.shadowOffsetX=this.style.shadowOffsetX,this.context.shadowOffsetY=this.style.shadowOffsetY,this.context.shadowColor=this.style.shadowColor,this.context.shadowBlur=this.style.shadowBlur):(this.context.shadowOffsetX=0,this.context.shadowOffsetY=0,this.context.shadowColor=0,this.context.shadowBlur=0)},c.Text.prototype.updateLine=function(a,b,c){for(var d=0;d<a.length;d++){var e=a[d];this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(e,b,c)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(e,b,c)),b+=this.context.measureText(e).width,this._charCount++}},c.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},c.Text.prototype.addColor=function(a,b){return this.colors[b]=a,this.dirty=!0,this},c.Text.prototype.addStrokeColor=function(a,b){return this.strokeColors[b]=a,this.dirty=!0,this},c.Text.prototype.runWordWrap=function(a){for(var b="",c=a.split("\n"),d=0;d<c.length;d++){for(var e=this.style.wordWrapWidth,f=c[d].split(" "),g=0;g<f.length;g++){var h=this.context.measureText(f[g]).width,i=h+this.context.measureText(" ").width;i>e?(g>0&&(b+="\n"),b+=f[g]+" ",e=this.style.wordWrapWidth-h):(e-=i,b+=f[g]+" ")}d<c.length-1&&(b+="\n")}return b},c.Text.prototype.updateFont=function(a){var b=this.componentsToFont(a);this.style.font!==b&&(this.style.font=b,this.dirty=!0,this.parent&&this.updateTransform())},c.Text.prototype.fontToComponents=function(a){var b=a.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);return b?{font:a,fontStyle:b[1]||"normal",fontVariant:b[2]||"normal",fontWeight:b[3]||"normal",fontSize:b[4]||"medium",fontFamily:b[5]}:(console.warn("Phaser.Text - unparsable CSS font: "+a),{font:a})},c.Text.prototype.componentsToFont=function(a){var b,c=[];return b=a.fontStyle,b&&"normal"!==b&&c.push(b),b=a.fontVariant,b&&"normal"!==b&&c.push(b),b=a.fontWeight,b&&"normal"!==b&&c.push(b),b=a.fontSize,b&&"medium"!==b&&c.push(b),b=a.fontFamily,b&&c.push(b),c.length||c.push(a.font),c.join(" ")},c.Text.prototype.setText=function(a){return this.text=a.toString()||"",this.dirty=!0,this},c.Text.prototype.parseList=function(a){if(!Array.isArray(a))return this;for(var b="",c=0;c<a.length;c++)Array.isArray(a[c])?(b+=a[c].join("	"),c<a.length-1&&(b+="\n")):(b+=a[c],c<a.length-1&&(b+="	"));return this.text=b,this.dirty=!0,this},c.Text.prototype.setTextBounds=function(a,b,d,e){return void 0===a?this.textBounds=null:(this.textBounds?this.textBounds.setTo(a,b,d,e):this.textBounds=new c.Rectangle(a,b,d,e),this.style.wordWrapWidth>d&&(this.style.wordWrapWidth=d)),this.updateTexture(),this},c.Text.prototype.updateTexture=function(){var a=this.texture.baseTexture,b=this.texture.crop,c=this.texture.frame,d=this.canvas.width,e=this.canvas.height;if(a.width=d,a.height=e,b.width=d,b.height=e,c.width=d,c.height=e,this.texture.width=d,this.texture.height=e,this._width=d,this._height=e,this.textBounds){var f=this.textBounds.x,g=this.textBounds.y;"right"===this.style.boundsAlignH?f=this.textBounds.width-this.canvas.width:"center"===this.style.boundsAlignH&&(f=this.textBounds.halfWidth-this.canvas.width/2),"bottom"===this.style.boundsAlignV?g=this.textBounds.height-this.canvas.height:"middle"===this.style.boundsAlignV&&(g=this.textBounds.halfHeight-this.canvas.height/2),this.pivot.x=-f,this.pivot.y=-g}this.renderable=0!==d&&0!==e,this.texture.baseTexture.dirty()},c.Text.prototype._renderWebGL=function(a){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,a)},c.Text.prototype._renderCanvas=function(a){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,a)},c.Text.prototype.determineFontProperties=function(a){var b=c.Text.fontPropertiesCache[a];if(!b){b={};var d=c.Text.fontPropertiesCanvas,e=c.Text.fontPropertiesContext;e.font=a;var f=Math.ceil(e.measureText("|MÉq").width),g=Math.ceil(e.measureText("|MÉq").width),h=2*g;if(g=1.4*g|0,d.width=f,d.height=h,e.fillStyle="#f00",e.fillRect(0,0,f,h),e.font=a,e.textBaseline="alphabetic",e.fillStyle="#000",e.fillText("|MÉq",0,g),!e.getImageData(0,0,f,h))return b.ascent=g,b.descent=g+6,b.fontSize=b.ascent+b.descent,c.Text.fontPropertiesCache[a]=b,b;var i,j,k=e.getImageData(0,0,f,h).data,l=k.length,m=4*f,n=0,o=!1;for(i=0;g>i;i++){for(j=0;m>j;j+=4)if(255!==k[n+j]){o=!0;break}if(o)break;n+=m}for(b.ascent=g-i,n=l-m,o=!1,i=h;i>g;i--){for(j=0;m>j;j+=4)if(255!==k[n+j]){o=!0;break}if(o)break;n-=m}b.descent=i-g,b.descent+=6,b.fontSize=b.ascent+b.descent,c.Text.fontPropertiesCache[a]=b}return b},c.Text.prototype.getBounds=function(a){return this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype.getBounds.call(this,a)},Object.defineProperty(c.Text.prototype,"text",{get:function(){return this._text},set:function(a){a!==this._text&&(this._text=a.toString()||"",this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(c.Text.prototype,"cssFont",{get:function(){return this.componentsToFont(this._fontComponents)},set:function(a){a=a||"bold 20pt Arial",this._fontComponents=this.fontToComponents(a),this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"font",{get:function(){return this._fontComponents.fontFamily},set:function(a){a=a||"Arial",a=a.trim(),/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(a)||/['",]/.exec(a)||(a="'"+a+"'"),this._fontComponents.fontFamily=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontSize",{get:function(){var a=this._fontComponents.fontSize;return a&&/(?:^0$|px$)/.exec(a)?parseInt(a,10):a},set:function(a){a=a||"0","number"==typeof a&&(a+="px"),this._fontComponents.fontSize=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontWeight",{get:function(){return this._fontComponents.fontWeight||"normal"},set:function(a){a=a||"normal",this._fontComponents.fontWeight=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontStyle",{get:function(){return this._fontComponents.fontStyle||"normal"},set:function(a){a=a||"normal",this._fontComponents.fontStyle=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontVariant",{get:function(){return this._fontComponents.fontVariant||"normal"},set:function(a){a=a||"normal",this._fontComponents.fontVariant=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fill",{get:function(){return this.style.fill},set:function(a){a!==this.style.fill&&(this.style.fill=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"align",{get:function(){return this.style.align},set:function(a){a!==this.style.align&&(this.style.align=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"resolution",{get:function(){return this._res},set:function(a){a!==this._res&&(this._res=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"tabs",{get:function(){return this.style.tabs},set:function(a){a!==this.style.tabs&&(this.style.tabs=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"boundsAlignH",{get:function(){return this.style.boundsAlignH},set:function(a){a!==this.style.boundsAlignH&&(this.style.boundsAlignH=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"boundsAlignV",{get:function(){return this.style.boundsAlignV},set:function(a){a!==this.style.boundsAlignV&&(this.style.boundsAlignV=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"stroke",{get:function(){return this.style.stroke},set:function(a){a!==this.style.stroke&&(this.style.stroke=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"strokeThickness",{get:function(){return this.style.strokeThickness},set:function(a){a!==this.style.strokeThickness&&(this.style.strokeThickness=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"wordWrap",{get:function(){return this.style.wordWrap},set:function(a){a!==this.style.wordWrap&&(this.style.wordWrap=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"wordWrapWidth",{get:function(){return this.style.wordWrapWidth},set:function(a){a!==this.style.wordWrapWidth&&(this.style.wordWrapWidth=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"lineSpacing",{get:function(){return this._lineSpacing},set:function(a){a!==this._lineSpacing&&(this._lineSpacing=parseFloat(a),this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(c.Text.prototype,"shadowOffsetX",{get:function(){return this.style.shadowOffsetX},set:function(a){a!==this.style.shadowOffsetX&&(this.style.shadowOffsetX=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowOffsetY",{get:function(){return this.style.shadowOffsetY},set:function(a){a!==this.style.shadowOffsetY&&(this.style.shadowOffsetY=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowColor",{get:function(){return this.style.shadowColor},set:function(a){a!==this.style.shadowColor&&(this.style.shadowColor=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowBlur",{get:function(){return this.style.shadowBlur},set:function(a){a!==this.style.shadowBlur&&(this.style.shadowBlur=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowStroke",{get:function(){return this.style.shadowStroke},set:function(a){a!==this.style.shadowStroke&&(this.style.shadowStroke=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowFill",{get:function(){return this.style.shadowFill},set:function(a){a!==this.style.shadowFill&&(this.style.shadowFill=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"width",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.x*this.texture.frame.width},set:function(a){this.scale.x=a/this.texture.frame.width,this._width=a}}),Object.defineProperty(c.Text.prototype,"height",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.y*this.texture.frame.height},set:function(a){this.scale.y=a/this.texture.frame.height,this._height=a}}),c.Text.fontPropertiesCache={},c.Text.fontPropertiesCanvas=document.createElement("canvas"),c.Text.fontPropertiesContext=c.Text.fontPropertiesCanvas.getContext("2d"),c.BitmapText=function(a,b,d,e,f,g,h){b=b||0,d=d||0,e=e||"",f=f||"",g=g||32,h=h||"left",PIXI.DisplayObjectContainer.call(this),this.type=c.BITMAPTEXT,this.physicsType=c.SPRITE,this.textWidth=0,this.textHeight=0,this.anchor=new c.Point,this._prevAnchor=new c.Point,this._glyphs=[],this._maxWidth=0,this._text=f,this._data=a.cache.getBitmapFont(e),this._font=e,this._fontSize=g,this._align=h,this._tint=16777215,this.updateText(),this.dirty=!1,c.Component.Core.init.call(this,a,b,d,"",null)},c.BitmapText.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),c.BitmapText.prototype.constructor=c.BitmapText,c.Component.Core.install.call(c.BitmapText.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),c.BitmapText.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.BitmapText.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.BitmapText.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.BitmapText.prototype.preUpdateCore=c.Component.Core.preUpdate,c.BitmapText.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.BitmapText.prototype.postUpdate=function(){c.Component.PhysicsBody.postUpdate.call(this),c.Component.FixedToCamera.postUpdate.call(this),this.body&&this.body.type===c.Physics.ARCADE&&(this.textWidth!==this.body.sourceWidth||this.textHeight!==this.body.sourceHeight)&&this.body.setSize(this.textWidth,this.textHeight)},c.BitmapText.prototype.setText=function(a){this.text=a},c.BitmapText.prototype.scanLine=function(a,b,c){for(var d=0,e=0,f=-1,g=null,h=this._maxWidth>0?this._maxWidth:null,i=[],j=0;j<c.length;j++){var k=j===c.length-1?!0:!1;if(/(?:\r\n|\r|\n)/.test(c.charAt(j)))return{width:e,text:c.substr(0,j),end:k,chars:i};var l=c.charCodeAt(j),m=a.chars[l],n=0;if(m){var o=g&&m.kerning[g]?m.kerning[g]:0;if(f=/(\s)/.test(c.charAt(j))?j:f,n=(o+m.texture.width+m.xOffset)*b,h&&e+n>=h&&f>-1)return{width:e,text:c.substr(0,j-(j-f)),end:k,chars:i};e+=m.xAdvance*b,i.push(d+m.xOffset*b),d+=m.xAdvance*b,g=l}}return{width:e,text:c,end:k,chars:i}},c.BitmapText.prototype.updateText=function(){var a=this._data.font;if(a){var b=this.text,c=this._fontSize/a.size,d=[],e=0;this.textWidth=0;do{var f=this.scanLine(a,c,b);f.y=e,d.push(f),f.width>this.textWidth&&(this.textWidth=f.width),e+=a.lineHeight*c,b=b.substr(f.text.length+1)}while(f.end===!1);this.textHeight=e;for(var g=0,h=0,i=this.textWidth*this.anchor.x,j=this.textHeight*this.anchor.y,k=0;k<d.length;k++){var f=d[k];"right"===this._align?h=this.textWidth-f.width:"center"===this._align&&(h=(this.textWidth-f.width)/2);for(var l=0;l<f.text.length;l++){var m=f.text.charCodeAt(l),n=a.chars[m],o=this._glyphs[g];o?o.texture=n.texture:(o=new PIXI.Sprite(n.texture),o.name=f.text[l],this._glyphs.push(o)),o.position.x=f.chars[l]+h-i,o.position.y=f.y+n.yOffset*c-j,o.scale.set(c),o.tint=this.tint,o.parent||this.addChild(o),g++}}for(k=g;k<this._glyphs.length;k++)this.removeChild(this._glyphs[k])}},c.BitmapText.prototype.purgeGlyphs=function(){for(var a=this._glyphs.length,b=[],c=0;c<this._glyphs.length;c++)this._glyphs[c].parent!==this?this._glyphs[c].destroy():b.push(this._glyphs[c]);return this._glyphs=[],this._glyphs=b,this.updateText(),a-b.length},c.BitmapText.prototype.updateTransform=function(){(this.dirty||!this.anchor.equals(this._prevAnchor))&&(this.updateText(),this.dirty=!1,this._prevAnchor.copyFrom(this.anchor)),PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)},Object.defineProperty(c.BitmapText.prototype,"align",{get:function(){return this._align},set:function(a){a===this._align||"left"!==a&&"center"!==a&&"right"!==a||(this._align=a,this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"tint",{get:function(){return this._tint},set:function(a){a!==this._tint&&(this._tint=a,this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"font",{get:function(){return this._font},set:function(a){a!==this._font&&(this._font=a.trim(),this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"fontSize",{get:function(){return this._fontSize},set:function(a){a=parseInt(a,10),a!==this._fontSize&&a>0&&(this._fontSize=a,this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"text",{get:function(){return this._text},set:function(a){a!==this._text&&(this._text=a.toString()||"",this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(a){a!==this._maxWidth&&(this._maxWidth=a,this.updateText())}}),c.RetroFont=function(a,b,d,e,f,g,h,i,j,k){if(!a.cache.checkImageKey(b))return!1;(void 0===g||null===g)&&(g=a.cache.getImage(b).width/d),this.characterWidth=d,this.characterHeight=e,this.characterSpacingX=h||0,this.characterSpacingY=i||0,this.characterPerRow=g,this.offsetX=j||0,this.offsetY=k||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=a.cache.getImage(b),this._text="",this.grabData=[],this.frameData=new c.FrameData;for(var l=this.offsetX,m=this.offsetY,n=0,o=0;o<f.length;o++){var p=this.frameData.addFrame(new c.Frame(o,l,m,this.characterWidth,this.characterHeight));this.grabData[f.charCodeAt(o)]=p.index,n++,n===this.characterPerRow?(n=0,l=this.offsetX,m+=this.characterHeight+this.characterSpacingY):l+=this.characterWidth+this.characterSpacingX}a.cache.updateFrameData(b,this.frameData),this.stamp=new c.Image(a,0,0,b,0),c.RenderTexture.call(this,a,100,100,"",c.scaleModes.NEAREST),this.type=c.RETROFONT},c.RetroFont.prototype=Object.create(c.RenderTexture.prototype),c.RetroFont.prototype.constructor=c.RetroFont,c.RetroFont.ALIGN_LEFT="left",c.RetroFont.ALIGN_RIGHT="right",c.RetroFont.ALIGN_CENTER="center",c.RetroFont.TEXT_SET1=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",c.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",c.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",c.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",c.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",c.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",c.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",c.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",c.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",c.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",c.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",c.RetroFont.prototype.setFixedWidth=function(a,b){void 0===b&&(b="left"),this.fixedWidth=a,this.align=b},c.RetroFont.prototype.setText=function(a,b,c,d,e,f){this.multiLine=b||!1,this.customSpacingX=c||0,this.customSpacingY=d||0,this.align=e||"left",this.autoUpperCase=f?!1:!0,a.length>0&&(this.text=a)},c.RetroFont.prototype.buildRetroFontText=function(){var a=0,b=0;if(this.clear(),this.multiLine){var d=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,d.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),d.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var e=0;e<d.length;e++)a=0,this.align===c.RetroFont.ALIGN_RIGHT?a=this.width-d[e].length*(this.characterWidth+this.customSpacingX):this.align===c.RetroFont.ALIGN_CENTER&&(a=this.width/2-d[e].length*(this.characterWidth+this.customSpacingX)/2,a+=this.customSpacingX/2),0>a&&(a=0),this.pasteLine(d[e],a,b,this.customSpacingX),b+=this.characterHeight+this.customSpacingY}else this.fixedWidth>0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),a=0,this.align===c.RetroFont.ALIGN_RIGHT?a=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===c.RetroFont.ALIGN_CENTER&&(a=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,a+=this.customSpacingX/2),0>a&&(a=0),this.pasteLine(this._text,a,0,this.customSpacingX);this.requiresReTint=!0},c.RetroFont.prototype.pasteLine=function(a,b,c,d){for(var e=0;e<a.length;e++)if(" "===a.charAt(e))b+=this.characterWidth+d;else if(this.grabData[a.charCodeAt(e)]>=0&&(this.stamp.frame=this.grabData[a.charCodeAt(e)],this.renderXY(this.stamp,b,c,!1),b+=this.characterWidth+d,b>this.width))break},c.RetroFont.prototype.getLongestLine=function(){var a=0;if(this._text.length>0)for(var b=this._text.split("\n"),c=0;c<b.length;c++)b[c].length>a&&(a=b[c].length);return a},c.RetroFont.prototype.removeUnsupportedCharacters=function(a){for(var b="",c=0;c<this._text.length;c++){var d=this._text[c],e=d.charCodeAt(0);(this.grabData[e]>=0||!a&&"\n"===d)&&(b=b.concat(d))}return b},c.RetroFont.prototype.updateOffset=function(a,b){if(this.offsetX!==a||this.offsetY!==b){for(var c=a-this.offsetX,d=b-this.offsetY,e=this.game.cache.getFrameData(this.stamp.key).getFrames(),f=e.length;f--;)e[f].x+=c,e[f].y+=d;this.buildRetroFontText()}},Object.defineProperty(c.RetroFont.prototype,"text",{get:function(){return this._text},set:function(a){var b;b=this.autoUpperCase?a.toUpperCase():a,b!==this._text&&(this._text=b,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(c.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(a){this.stamp.smoothed=a,this.buildRetroFontText()}}),c.Rope=function(a,b,d,e,f,g){this.points=[],this.points=g,this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.ROPE,this._scroll=new c.Point,PIXI.Rope.call(this,PIXI.TextureCache.__default,this.points),c.Component.Core.init.call(this,a,b,d,e,f)},c.Rope.prototype=Object.create(PIXI.Rope.prototype),c.Rope.prototype.constructor=c.Rope,c.Component.Core.install.call(c.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),c.Rope.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Rope.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Rope.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Rope.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Rope.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},c.Rope.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},Object.defineProperty(c.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(a){a&&"function"==typeof a?(this._hasUpdateAnimation=!0,this._updateAnimation=a):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(c.Rope.prototype,"segments",{get:function(){for(var a,b,d,e,f,g,h,i,j=[],k=0;k<this.points.length;k++)a=4*k,b=this.vertices[a]*this.scale.x,d=this.vertices[a+1]*this.scale.y,e=this.vertices[a+4]*this.scale.x,f=this.vertices[a+3]*this.scale.y,g=c.Math.difference(b,e),h=c.Math.difference(d,f),b+=this.world.x,d+=this.world.y,i=new c.Rectangle(b,d,g,h),j.push(i);return j}}),c.TileSprite=function(a,b,d,e,f,g,h){b=b||0,d=d||0,e=e||256,f=f||256,g=g||null,h=h||null,this.type=c.TILESPRITE,this.physicsType=c.SPRITE,this._scroll=new c.Point;var i=a.cache.getImage("__default",!0);PIXI.TilingSprite.call(this,new PIXI.Texture(i.base),e,f),c.Component.Core.init.call(this,a,b,d,g,h)},c.TileSprite.prototype=Object.create(PIXI.TilingSprite.prototype),c.TileSprite.prototype.constructor=c.TileSprite,c.Component.Core.install.call(c.TileSprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","Smoothed"]),c.TileSprite.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.TileSprite.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.TileSprite.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.TileSprite.prototype.preUpdateCore=c.Component.Core.preUpdate,c.TileSprite.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.TileSprite.prototype.autoScroll=function(a,b){this._scroll.set(a,b)},c.TileSprite.prototype.stopScroll=function(){this._scroll.set(0,0)},c.TileSprite.prototype.destroy=function(a){c.Component.Destroy.prototype.destroy.call(this,a),PIXI.TilingSprite.prototype.destroy.call(this)},c.TileSprite.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},c.Device=function(){this.deviceReadyAt=0,this.initialized=!1,this.desktop=!1,this.iOS=!1,this.cocoonJS=!1,this.cocoonJSApp=!1,this.cordova=!1,this.node=!1,this.nodeWebkit=!1,this.electron=!1,this.ejecta=!1,this.crosswalk=!1,this.android=!1,this.chromeOS=!1,this.linux=!1,this.macOS=!1,this.windows=!1,this.windowsPhone=!1,this.canvas=!1,this.canvasBitBltShift=null,this.webGL=!1,this.file=!1,this.fileSystem=!1,this.localStorage=!1,this.worker=!1,this.css3D=!1,this.pointerLock=!1,this.typedArray=!1,this.vibration=!1,this.getUserMedia=!0,this.quirksMode=!1,this.touch=!1,this.mspointer=!1,this.wheelEvent=null,this.arora=!1,this.chrome=!1,this.chromeVersion=0,this.epiphany=!1,this.firefox=!1,this.firefoxVersion=0,this.ie=!1,this.ieVersion=0,this.trident=!1,this.tridentVersion=0,this.mobileSafari=!1,this.midori=!1,this.opera=!1,this.safari=!1,this.webApp=!1,this.silk=!1,this.audioData=!1,this.webAudio=!1,this.ogg=!1,this.opus=!1,this.mp3=!1,this.wav=!1,this.m4a=!1,this.webm=!1,this.oggVideo=!1,this.h264Video=!1,this.mp4Video=!1,this.webmVideo=!1,this.vp9Video=!1,this.hlsVideo=!1,this.iPhone=!1,this.iPhone4=!1,this.iPad=!1,this.pixelRatio=0,this.littleEndian=!1,this.LITTLE_ENDIAN=!1,this.support32bit=!1,this.fullscreen=!1,this.requestFullscreen="",this.cancelFullscreen="",this.fullscreenKeyboard=!1},c.Device=new c.Device,c.Device.onInitialized=new c.Signal,c.Device.whenReady=function(a,b,c){var d=this._readyCheck;if(this.deviceReadyAt||!d)a.call(b,this);else if(d._monitor||c)d._queue=d._queue||[],d._queue.push([a,b]);else{d._monitor=d.bind(this),d._queue=d._queue||[],d._queue.push([a,b]);var e="undefined"!=typeof window.cordova,f=navigator.isCocoonJS;"complete"===document.readyState||"interactive"===document.readyState?window.setTimeout(d._monitor,0):e&&!f?document.addEventListener("deviceready",d._monitor,!1):(document.addEventListener("DOMContentLoaded",d._monitor,!1),window.addEventListener("load",d._monitor,!1))}},c.Device._readyCheck=function(){var a=this._readyCheck;if(document.body){if(!this.deviceReadyAt){this.deviceReadyAt=Date.now(),document.removeEventListener("deviceready",a._monitor),document.removeEventListener("DOMContentLoaded",a._monitor),window.removeEventListener("load",a._monitor),this._initialize(),this.initialized=!0,this.onInitialized.dispatch(this);for(var b;b=a._queue.shift();){var c=b[0],d=b[1];c.call(d,this)}this._readyCheck=null,this._initialize=null,this.onInitialized=null}}else window.setTimeout(a._monitor,20)},c.Device._initialize=function(){function a(){var a=navigator.userAgent;/Playstation Vita/.test(a)?l.vita=!0:/Kindle/.test(a)||/\bKF[A-Z][A-Z]+/.test(a)||/Silk.*Mobile Safari/.test(a)?l.kindle=!0:/Android/.test(a)?l.android=!0:/CrOS/.test(a)?l.chromeOS=!0:/iP[ao]d|iPhone/i.test(a)?l.iOS=!0:/Linux/.test(a)?l.linux=!0:/Mac OS/.test(a)?l.macOS=!0:/Windows/.test(a)&&(l.windows=!0),(/Windows Phone/i.test(a)||/IEMobile/i.test(a))&&(l.android=!1,l.iOS=!1,l.macOS=!1,l.windows=!0,l.windowsPhone=!0);var b=/Silk/.test(a);(l.windows||l.macOS||l.linux&&!b||l.chromeOS)&&(l.desktop=!0),(l.windowsPhone||/Windows NT/i.test(a)&&/Touch/i.test(a))&&(l.desktop=!1)}function b(){l.canvas=!!window.CanvasRenderingContext2D||l.cocoonJS;try{l.localStorage=!!localStorage.getItem}catch(a){l.localStorage=!1}l.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),l.fileSystem=!!window.requestFileSystem,l.webGL=function(){try{var a=document.createElement("canvas");return a.screencanvas=!1,!!window.WebGLRenderingContext&&(a.getContext("webgl")||a.getContext("experimental-webgl"))}catch(b){return!1}}(),l.webGL=!!l.webGL,l.worker=!!window.Worker,l.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,l.quirksMode="CSS1Compat"===document.compatMode?!1:!0,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,l.getUserMedia=l.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,l.firefox&&l.firefoxVersion<21&&(l.getUserMedia=!1),!l.iOS&&(l.ie||l.firefox||l.chrome)&&(l.canvasBitBltShift=!0),(l.safari||l.mobileSafari)&&(l.canvasBitBltShift=!1)
-}function c(){("ontouchstart"in document.documentElement||window.navigator.maxTouchPoints&&window.navigator.maxTouchPoints>=1)&&(l.touch=!0),(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(l.mspointer=!0),l.cocoonJS||("onwheel"in window||l.ie&&"WheelEvent"in window?l.wheelEvent="wheel":"onmousewheel"in window?l.wheelEvent="mousewheel":l.firefox&&"MouseScrollEvent"in window&&(l.wheelEvent="DOMMouseScroll"))}function d(){for(var a=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],b=document.createElement("div"),c=0;c<a.length;c++)if(b[a[c]]){l.fullscreen=!0,l.requestFullscreen=a[c];break}var d=["cancelFullScreen","exitFullscreen","webkitCancelFullScreen","webkitExitFullscreen","msCancelFullScreen","msExitFullscreen","mozCancelFullScreen","mozExitFullscreen"];if(l.fullscreen)for(var c=0;c<d.length;c++)if(document[d[c]]){l.cancelFullscreen=d[c];break}window.Element&&Element.ALLOW_KEYBOARD_INPUT&&(l.fullscreenKeyboard=!0)}function e(){var a=navigator.userAgent;if(/Arora/.test(a)?l.arora=!0:/Chrome\/(\d+)/.test(a)&&!l.windowsPhone?(l.chrome=!0,l.chromeVersion=parseInt(RegExp.$1,10)):/Epiphany/.test(a)?l.epiphany=!0:/Firefox\D+(\d+)/.test(a)?(l.firefox=!0,l.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(a)&&l.iOS?l.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(a)?(l.ie=!0,l.ieVersion=parseInt(RegExp.$1,10)):/Midori/.test(a)?l.midori=!0:/Opera/.test(a)?l.opera=!0:/Safari/.test(a)&&!l.windowsPhone?l.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(a)&&(l.ie=!0,l.trident=!0,l.tridentVersion=parseInt(RegExp.$1,10),l.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(a)&&(l.silk=!0),navigator.standalone&&(l.webApp=!0),"undefined"!=typeof window.cordova&&(l.cordova=!0),"undefined"!=typeof process&&"undefined"!=typeof require&&(l.node=!0),l.node&&"object"==typeof process.versions&&(l.nodeWebkit=!!process.versions["node-webkit"],l.electron=!!process.versions.electron),navigator.isCocoonJS&&(l.cocoonJS=!0),l.cocoonJS)try{l.cocoonJSApp="undefined"!=typeof CocoonJS}catch(b){l.cocoonJSApp=!1}"undefined"!=typeof window.ejecta&&(l.ejecta=!0),/Crosswalk/.test(a)&&(l.crosswalk=!0)}function f(){var a=document.createElement("video"),b=!1;try{(b=!!a.canPlayType)&&(a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(l.oggVideo=!0),a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(l.h264Video=!0,l.mp4Video=!0),a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(l.webmVideo=!0),a.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(l.vp9Video=!0),a.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(l.hlsVideo=!0))}catch(c){}}function g(){l.audioData=!!window.Audio,l.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var a=document.createElement("audio"),b=!1;try{(b=!!a.canPlayType)&&(a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(l.ogg=!0),(a.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||a.canPlayType("audio/opus;").replace(/^no$/,""))&&(l.opus=!0),a.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(l.mp3=!0),a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(l.wav=!0),(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;").replace(/^no$/,""))&&(l.m4a=!0),a.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(l.webm=!0))}catch(c){}}function h(){l.pixelRatio=window.devicePixelRatio||1,l.iPhone=-1!=navigator.userAgent.toLowerCase().indexOf("iphone"),l.iPhone4=2==l.pixelRatio&&l.iPhone,l.iPad=-1!=navigator.userAgent.toLowerCase().indexOf("ipad"),l.typedArray="undefined"!=typeof Int8Array?!0:!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(l.littleEndian=i(),l.LITTLE_ENDIAN=l.littleEndian),l.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==l.littleEndian&&j(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(l.vibration=!0)}function i(){var a=new ArrayBuffer(4),b=new Uint8Array(a),c=new Uint32Array(a);return b[0]=161,b[1]=178,b[2]=195,b[3]=212,3569595041==c[0]?!0:2712847316==c[0]?!1:null}function j(){if(void 0===Uint8ClampedArray)return!1;var a=document.createElement("canvas"),b=a.getContext("2d");if(!b)return!1;var c=b.createImageData(1,1);return c.data instanceof Uint8ClampedArray}function k(){var a,b=document.createElement("p"),c={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(b,null);for(var d in c)void 0!==b.style[d]&&(b.style[d]="translate3d(1px,1px,1px)",a=window.getComputedStyle(b).getPropertyValue(c[d]));document.body.removeChild(b),l.css3D=void 0!==a&&a.length>0&&"none"!==a}var l=this;a(),g(),f(),e(),k(),h(),b(),d(),c()},c.Device.canPlayAudio=function(a){return"mp3"===a&&this.mp3?!0:"ogg"===a&&(this.ogg||this.opus)?!0:"m4a"===a&&this.m4a?!0:"opus"===a&&this.opus?!0:"wav"===a&&this.wav?!0:"webm"===a&&this.webm?!0:!1},c.Device.canPlayVideo=function(a){return"webm"===a&&(this.webmVideo||this.vp9Video)?!0:"mp4"===a&&(this.mp4Video||this.h264Video)?!0:"ogg"!==a&&"ogv"!==a||!this.oggVideo?"mpeg"===a&&this.hlsVideo?!0:!1:!0},c.Device.isConsoleOpen=function(){return window.console&&window.console.firebug?!0:window.console&&(console.profile(),console.profileEnd(),console.clear&&console.clear(),console.profiles)?console.profiles.length>0:!1},c.Device.isAndroidStockBrowser=function(){var a=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return a&&a[1]<537},c.DOM={getOffset:function(a,b){b=b||new c.Point;var d=a.getBoundingClientRect(),e=c.DOM.scrollY,f=c.DOM.scrollX,g=document.documentElement.clientTop,h=document.documentElement.clientLeft;return b.x=d.left+f-h,b.y=d.top+e-g,b},getBounds:function(a,b){return void 0===b&&(b=0),a=a&&!a.nodeType?a[0]:a,a&&1===a.nodeType?this.calibrate(a.getBoundingClientRect(),b):!1},calibrate:function(a,b){b=+b||0;var c={width:0,height:0,left:0,right:0,top:0,bottom:0};return c.width=(c.right=a.right+b)-(c.left=a.left-b),c.height=(c.bottom=a.bottom+b)-(c.top=a.top-b),c},getAspectRatio:function(a){a=null==a?this.visualBounds:1===a.nodeType?this.getBounds(a):a;var b=a.width,c=a.height;return"function"==typeof b&&(b=b.call(a)),"function"==typeof c&&(c=c.call(a)),b/c},inLayoutViewport:function(a,b){var c=this.getBounds(a,b);return!!c&&c.bottom>=0&&c.right>=0&&c.top<=this.layoutBounds.width&&c.left<=this.layoutBounds.height},getScreenOrientation:function(a){var b=window.screen,c=b.orientation||b.mozOrientation||b.msOrientation;if(c&&"string"==typeof c.type)return c.type;if("string"==typeof c)return c;var d="portrait-primary",e="landscape-primary";if("screen"===a)return b.height>b.width?d:e;if("viewport"===a)return this.visualBounds.height>this.visualBounds.width?d:e;if("window.orientation"===a&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?d:e;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return d;if(window.matchMedia("(orientation: landscape)").matches)return e}return this.visualBounds.height>this.visualBounds.width?d:e},visualBounds:new c.Rectangle,layoutBounds:new c.Rectangle,documentBounds:new c.Rectangle},c.Device.whenReady(function(a){var b=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},d=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};Object.defineProperty(c.DOM,"scrollX",{get:b}),Object.defineProperty(c.DOM,"scrollY",{get:d}),Object.defineProperty(c.DOM.visualBounds,"x",{get:b}),Object.defineProperty(c.DOM.visualBounds,"y",{get:d}),Object.defineProperty(c.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(c.DOM.layoutBounds,"y",{value:0});var e=a.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight;if(e){var f=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},g=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(c.DOM.visualBounds,"width",{get:f}),Object.defineProperty(c.DOM.visualBounds,"height",{get:g}),Object.defineProperty(c.DOM.layoutBounds,"width",{get:f}),Object.defineProperty(c.DOM.layoutBounds,"height",{get:g})}else Object.defineProperty(c.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(c.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(c.DOM.layoutBounds,"width",{get:function(){var a=document.documentElement.clientWidth,b=window.innerWidth;return b>a?b:a}}),Object.defineProperty(c.DOM.layoutBounds,"height",{get:function(){var a=document.documentElement.clientHeight,b=window.innerHeight;return b>a?b:a}});Object.defineProperty(c.DOM.documentBounds,"x",{value:0}),Object.defineProperty(c.DOM.documentBounds,"y",{value:0}),Object.defineProperty(c.DOM.documentBounds,"width",{get:function(){var a=document.documentElement;return Math.max(a.clientWidth,a.offsetWidth,a.scrollWidth)}}),Object.defineProperty(c.DOM.documentBounds,"height",{get:function(){var a=document.documentElement;return Math.max(a.clientHeight,a.offsetHeight,a.scrollHeight)}})},null,!0),c.Canvas={create:function(a,b,c){a=a||256,b=b||256;var d=document.createElement("canvas");return"string"==typeof c&&""!==c&&(d.id=c),d.width=a,d.height=b,d.style.display="block",d},setBackgroundColor:function(a,b){return b=b||"rgb(0,0,0)",a.style.backgroundColor=b,a},setTouchAction:function(a,b){return b=b||"none",a.style.msTouchAction=b,a.style["ms-touch-action"]=b,a.style["touch-action"]=b,a},setUserSelect:function(a,b){return b=b||"none",a.style["-webkit-touch-callout"]=b,a.style["-webkit-user-select"]=b,a.style["-khtml-user-select"]=b,a.style["-moz-user-select"]=b,a.style["-ms-user-select"]=b,a.style["user-select"]=b,a.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",a},addToDOM:function(a,b,c){var d;return void 0===c&&(c=!0),b&&("string"==typeof b?d=document.getElementById(b):"object"==typeof b&&1===b.nodeType&&(d=b)),d||(d=document.body),c&&d.style&&(d.style.overflow="hidden"),d.appendChild(a),a},removeFromDOM:function(a){a.parentNode&&a.parentNode.removeChild(a)},setTransform:function(a,b,c,d,e,f,g){return a.setTransform(d,f,g,e,b,c),a},setSmoothingEnabled:function(a,b){var c=["i","mozI","oI","webkitI","msI"];for(var d in c){var e=c[d]+"mageSmoothingEnabled";if(e in a)return a[e]=b,a}return a},getSmoothingEnabled:function(a){return a.imageSmoothingEnabled||a.mozImageSmoothingEnabled||a.oImageSmoothingEnabled||a.webkitImageSmoothingEnabled||a.msImageSmoothingEnabled},setImageRenderingCrisp:function(a){return a.style["image-rendering"]="optimizeSpeed",a.style["image-rendering"]="crisp-edges",a.style["image-rendering"]="-moz-crisp-edges",a.style["image-rendering"]="-webkit-optimize-contrast",a.style["image-rendering"]="optimize-contrast",a.style["image-rendering"]="pixelated",a.style.msInterpolationMode="nearest-neighbor",a},setImageRenderingBicubic:function(a){return a.style["image-rendering"]="auto",a.style.msInterpolationMode="bicubic",a}},c.RequestAnimationFrame=function(a,b){void 0===b&&(b=!1),this.game=a,this.isRunning=!1,this.forceSetTimeOut=b;for(var c=["ms","moz","webkit","o"],d=0;d<c.length&&!window.requestAnimationFrame;d++)window.requestAnimationFrame=window[c[d]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[c[d]+"CancelAnimationFrame"];this._isSetTimeOut=!1,this._onLoop=null,this._timeOutID=null},c.RequestAnimationFrame.prototype={start:function(){this.isRunning=!0;var a=this;!window.requestAnimationFrame||this.forceSetTimeOut?(this._isSetTimeOut=!0,this._onLoop=function(){return a.updateSetTimeout()},this._timeOutID=window.setTimeout(this._onLoop,0)):(this._isSetTimeOut=!1,this._onLoop=function(b){return a.updateRAF(b)},this._timeOutID=window.requestAnimationFrame(this._onLoop))},updateRAF:function(a){this.game.update(Math.floor(a)),this._timeOutID=window.requestAnimationFrame(this._onLoop)},updateSetTimeout:function(){this.game.update(Date.now()),this._timeOutID=window.setTimeout(this._onLoop,this.game.time.timeToCall)},stop:function(){this._isSetTimeOut?clearTimeout(this._timeOutID):window.cancelAnimationFrame(this._timeOutID),this.isRunning=!1},isSetTimeOut:function(){return this._isSetTimeOut},isRAF:function(){return this._isSetTimeOut===!1}},c.RequestAnimationFrame.prototype.constructor=c.RequestAnimationFrame,c.Math={PI2:2*Math.PI,fuzzyEqual:function(a,b,c){return void 0===c&&(c=1e-4),Math.abs(a-b)<c},fuzzyLessThan:function(a,b,c){return void 0===c&&(c=1e-4),b+c>a},fuzzyGreaterThan:function(a,b,c){return void 0===c&&(c=1e-4),a>b-c},fuzzyCeil:function(a,b){return void 0===b&&(b=1e-4),Math.ceil(a-b)},fuzzyFloor:function(a,b){return void 0===b&&(b=1e-4),Math.floor(a+b)},average:function(){for(var a=0,b=0;b<arguments.length;b++)a+=+arguments[b];return a/arguments.length},shear:function(a){return a%1},snapTo:function(a,b,c){return void 0===c&&(c=0),0===b?a:(a-=c,a=b*Math.round(a/b),c+a)},snapToFloor:function(a,b,c){return void 0===c&&(c=0),0===b?a:(a-=c,a=b*Math.floor(a/b),c+a)},snapToCeil:function(a,b,c){return void 0===c&&(c=0),0===b?a:(a-=c,a=b*Math.ceil(a/b),c+a)},roundTo:function(a,b,c){void 0===b&&(b=0),void 0===c&&(c=10);var d=Math.pow(c,-b);return Math.round(a*d)/d},floorTo:function(a,b,c){void 0===b&&(b=0),void 0===c&&(c=10);var d=Math.pow(c,-b);return Math.floor(a*d)/d},ceilTo:function(a,b,c){void 0===b&&(b=0),void 0===c&&(c=10);var d=Math.pow(c,-b);return Math.ceil(a*d)/d},angleBetween:function(a,b,c,d){return Math.atan2(d-b,c-a)},angleBetweenY:function(a,b,c,d){return Math.atan2(c-a,d-b)},angleBetweenPoints:function(a,b){return Math.atan2(b.y-a.y,b.x-a.x)},angleBetweenPointsY:function(a,b){return Math.atan2(b.x-a.x,b.y-a.y)},reverseAngle:function(a){return this.normalizeAngle(a+Math.PI,!0)},normalizeAngle:function(a){return a%=2*Math.PI,a>=0?a:a+2*Math.PI},maxAdd:function(a,b,c){return Math.min(a+b,c)},minSub:function(a,b,c){return Math.max(a-b,c)},wrap:function(a,b,c){var d=c-b;if(0>=d)return 0;var e=(a-b)%d;return 0>e&&(e+=d),e+b},wrapValue:function(a,b,c){var d;return a=Math.abs(a),b=Math.abs(b),c=Math.abs(c),d=(a+b)%c},isOdd:function(a){return!!(1&a)},isEven:function(a){return!(1&a)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])var a=arguments[0];else var a=arguments;for(var b=1,c=0,d=a.length;d>b;b++)a[b]<a[c]&&(c=b);return a[c]},max:function(){if(1===arguments.length&&"object"==typeof arguments[0])var a=arguments[0];else var a=arguments;for(var b=1,c=0,d=a.length;d>b;b++)a[b]>a[c]&&(c=b);return a[c]},minProperty:function(a){if(2===arguments.length&&"object"==typeof arguments[1])var b=arguments[1];else var b=arguments.slice(1);for(var c=1,d=0,e=b.length;e>c;c++)b[c][a]<b[d][a]&&(d=c);return b[d][a]},maxProperty:function(a){if(2===arguments.length&&"object"==typeof arguments[1])var b=arguments[1];else var b=arguments.slice(1);for(var c=1,d=0,e=b.length;e>c;c++)b[c][a]>b[d][a]&&(d=c);return b[d][a]},wrapAngle:function(a,b){return b?this.wrap(a,-Math.PI,Math.PI):this.wrap(a,-180,180)},linearInterpolation:function(a,b){var c=a.length-1,d=c*b,e=Math.floor(d);return 0>b?this.linear(a[0],a[1],d):b>1?this.linear(a[c],a[c-1],c-d):this.linear(a[e],a[e+1>c?c:e+1],d-e)},bezierInterpolation:function(a,b){for(var c=0,d=a.length-1,e=0;d>=e;e++)c+=Math.pow(1-b,d-e)*Math.pow(b,e)*a[e]*this.bernstein(d,e);return c},catmullRomInterpolation:function(a,b){var c=a.length-1,d=c*b,e=Math.floor(d);return a[0]===a[c]?(0>b&&(e=Math.floor(d=c*(1+b))),this.catmullRom(a[(e-1+c)%c],a[e],a[(e+1)%c],a[(e+2)%c],d-e)):0>b?a[0]-(this.catmullRom(a[0],a[0],a[1],a[1],-d)-a[0]):b>1?a[c]-(this.catmullRom(a[c],a[c],a[c-1],a[c-1],d-c)-a[c]):this.catmullRom(a[e?e-1:0],a[e],a[e+1>c?c:e+1],a[e+2>c?c:e+2],d-e)},linear:function(a,b,c){return(b-a)*c+a},bernstein:function(a,b){return this.factorial(a)/this.factorial(b)/this.factorial(a-b)},factorial:function(a){if(0===a)return 1;for(var b=a;--a;)b*=a;return b},catmullRom:function(a,b,c,d,e){var f=.5*(c-a),g=.5*(d-b),h=e*e,i=e*h;return(2*b-2*c+f+g)*i+(-3*b+3*c-2*f-g)*h+f*e+b},difference:function(a,b){return Math.abs(a-b)},roundAwayFromZero:function(a){return a>0?Math.ceil(a):Math.floor(a)},sinCosGenerator:function(a,b,c,d){void 0===b&&(b=1),void 0===c&&(c=1),void 0===d&&(d=1);for(var e=b,f=c,g=d*Math.PI/a,h=[],i=[],j=0;a>j;j++)f-=e*g,e+=f*g,h[j]=f,i[j]=e;return{sin:i,cos:h,length:a}},distance:function(a,b,c,d){var e=a-c,f=b-d;return Math.sqrt(e*e+f*f)},distanceSq:function(a,b,c,d){var e=a-c,f=b-d;return e*e+f*f},distancePow:function(a,b,c,d,e){return void 0===e&&(e=2),Math.sqrt(Math.pow(c-a,e)+Math.pow(d-b,e))},clamp:function(a,b,c){return b>a?b:a>c?c:a},clampBottom:function(a,b){return b>a?b:a},within:function(a,b,c){return Math.abs(a-b)<=c},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},smoothstep:function(a,b,c){return a=Math.max(0,Math.min(1,(a-b)/(c-b))),a*a*(3-2*a)},smootherstep:function(a,b,c){return a=Math.max(0,Math.min(1,(a-b)/(c-b))),a*a*a*(a*(6*a-15)+10)},sign:function(a){return 0>a?-1:a>0?1:0},percent:function(a,b,c){return void 0===c&&(c=0),a>b||c>b?1:c>a||c>a?0:(a-c)/b}};var j=Math.PI/180,k=180/Math.PI;return c.Math.degToRad=function(a){return a*j},c.Math.radToDeg=function(a){return a*k},c.RandomDataGenerator=function(a){void 0===a&&(a=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.sow(a)},c.RandomDataGenerator.prototype={rnd:function(){var a=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|a,this.s0=this.s1,this.s1=this.s2,this.s2=a-this.c,this.s2},sow:function(a){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,a)for(var b=0;b<a.length&&null!=a[b];b++){var c=a[b];this.s0-=this.hash(c),this.s0+=~~(this.s0<0),this.s1-=this.hash(c),this.s1+=~~(this.s1<0),this.s2-=this.hash(c),this.s2+=~~(this.s2<0)}},hash:function(a){var b,c,d;for(d=4022871197,a=a.toString(),c=0;c<a.length;c++)d+=a.charCodeAt(c),b=.02519603282416938*d,d=b>>>0,b-=d,b*=d,d=b>>>0,b-=d,d+=4294967296*b;return 2.3283064365386963e-10*(d>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(a,b){return Math.floor(this.realInRange(0,b-a+1)+a)},between:function(a,b){return this.integerInRange(a,b)},realInRange:function(a,b){return this.frac()*(b-a)+a},normal:function(){return 1-2*this.frac()},uuid:function(){var a="",b="";for(b=a="";a++<36;b+=~a%5|3*a&4?(15^a?8^this.frac()*(20^a?16:4):4).toString(16):"-");return b},pick:function(a){return a[this.integerInRange(0,a.length-1)]},weightedPick:function(a){return a[~~(Math.pow(this.frac(),2)*(a.length-1)+.5)]},timestamp:function(a,b){return this.realInRange(a||9466848e5,b||1577862e6)},angle:function(){return this.integerInRange(-180,180)}},c.RandomDataGenerator.prototype.constructor=c.RandomDataGenerator,c.QuadTree=function(a,b,c,d,e,f,g){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(a,b,c,d,e,f,g)},c.QuadTree.prototype={reset:function(a,b,c,d,e,f,g){this.maxObjects=e||10,this.maxLevels=f||4,this.level=g||0,this.bounds={x:Math.round(a),y:Math.round(b),width:c,height:d,subWidth:Math.floor(c/2),subHeight:Math.floor(d/2),right:Math.round(a)+Math.floor(c/2),bottom:Math.round(b)+Math.floor(d/2)},this.objects.length=0,this.nodes.length=0},populate:function(a){a.forEach(this.populateHandler,this,!0)},populateHandler:function(a){a.body&&a.exists&&this.insert(a.body)},split:function(){this.nodes[0]=new c.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new c.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new c.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new c.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(a){var b,c=0;if(null!=this.nodes[0]&&(b=this.getIndex(a),-1!==b))return void this.nodes[b].insert(a);if(this.objects.push(a),this.objects.length>this.maxObjects&&this.level<this.maxLevels)for(null==this.nodes[0]&&this.split();c<this.objects.length;)b=this.getIndex(this.objects[c]),-1!==b?this.nodes[b].insert(this.objects.splice(c,1)[0]):c++},getIndex:function(a){var b=-1;return a.x<this.bounds.right&&a.right<this.bounds.right?a.y<this.bounds.bottom&&a.bottom<this.bounds.bottom?b=1:a.y>this.bounds.bottom&&(b=2):a.x>this.bounds.right&&(a.y<this.bounds.bottom&&a.bottom<this.bounds.bottom?b=0:a.y>this.bounds.bottom&&(b=3)),b},retrieve:function(a){if(a instanceof c.Rectangle)var b=this.objects,d=this.getIndex(a);else{if(!a.body)return this._empty;var b=this.objects,d=this.getIndex(a.body)}return this.nodes[0]&&(-1!==d?b=b.concat(this.nodes[d].retrieve(a)):(b=b.concat(this.nodes[0].retrieve(a)),b=b.concat(this.nodes[1].retrieve(a)),b=b.concat(this.nodes[2].retrieve(a)),b=b.concat(this.nodes[3].retrieve(a)))),b},clear:function(){this.objects.length=0;for(var a=this.nodes.length;a--;)this.nodes[a].clear(),this.nodes.splice(a,1);this.nodes.length=0}},c.QuadTree.prototype.constructor=c.QuadTree,c.Net=function(a){this.game=a},c.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(a){return-1!==window.location.hostname.indexOf(a)},updateQueryString:function(a,b,c,d){void 0===c&&(c=!1),(void 0===d||""===d)&&(d=window.location.href);var e="",f=new RegExp("([?|&])"+a+"=.*?(&|#|$)(.*)","gi");if(f.test(d))e="undefined"!=typeof b&&null!==b?d.replace(f,"$1"+a+"="+b+"$2$3"):d.replace(f,"$1$3").replace(/(&|\?)$/,"");else if("undefined"!=typeof b&&null!==b){var g=-1!==d.indexOf("?")?"&":"?",h=d.split("#");d=h[0]+g+a+"="+b,h[1]&&(d+="#"+h[1]),e=d}else e=d;return c?void(window.location.href=e):e},getQueryString:function(a){void 0===a&&(a="");var b={},c=location.search.substring(1).split("&");for(var d in c){var e=c[d].split("=");if(e.length>1){if(a&&a==this.decodeURI(e[0]))return this.decodeURI(e[1]);b[this.decodeURI(e[0])]=this.decodeURI(e[1])}}return b},decodeURI:function(a){return decodeURIComponent(a.replace(/\+/g," "))}},c.Net.prototype.constructor=c.Net,c.TweenManager=function(a){this.game=a,this._tweens=[],this._add=[],this.easeMap={Power0:c.Easing.Power0,Power1:c.Easing.Power1,Power2:c.Easing.Power2,Power3:c.Easing.Power3,Power4:c.Easing.Power4,Linear:c.Easing.Linear.None,Quad:c.Easing.Quadratic.Out,Cubic:c.Easing.Cubic.Out,Quart:c.Easing.Quartic.Out,Quint:c.Easing.Quintic.Out,Sine:c.Easing.Sinusoidal.Out,Expo:c.Easing.Exponential.Out,Circ:c.Easing.Circular.Out,Elastic:c.Easing.Elastic.Out,Back:c.Easing.Back.Out,Bounce:c.Easing.Bounce.Out,"Quad.easeIn":c.Easing.Quadratic.In,"Cubic.easeIn":c.Easing.Cubic.In,"Quart.easeIn":c.Easing.Quartic.In,"Quint.easeIn":c.Easing.Quintic.In,"Sine.easeIn":c.Easing.Sinusoidal.In,"Expo.easeIn":c.Easing.Exponential.In,"Circ.easeIn":c.Easing.Circular.In,"Elastic.easeIn":c.Easing.Elastic.In,"Back.easeIn":c.Easing.Back.In,"Bounce.easeIn":c.Easing.Bounce.In,"Quad.easeOut":c.Easing.Quadratic.Out,"Cubic.easeOut":c.Easing.Cubic.Out,"Quart.easeOut":c.Easing.Quartic.Out,"Quint.easeOut":c.Easing.Quintic.Out,"Sine.easeOut":c.Easing.Sinusoidal.Out,"Expo.easeOut":c.Easing.Exponential.Out,"Circ.easeOut":c.Easing.Circular.Out,"Elastic.easeOut":c.Easing.Elastic.Out,"Back.easeOut":c.Easing.Back.Out,"Bounce.easeOut":c.Easing.Bounce.Out,"Quad.easeInOut":c.Easing.Quadratic.InOut,"Cubic.easeInOut":c.Easing.Cubic.InOut,"Quart.easeInOut":c.Easing.Quartic.InOut,"Quint.easeInOut":c.Easing.Quintic.InOut,"Sine.easeInOut":c.Easing.Sinusoidal.InOut,"Expo.easeInOut":c.Easing.Exponential.InOut,"Circ.easeInOut":c.Easing.Circular.InOut,"Elastic.easeInOut":c.Easing.Elastic.InOut,"Back.easeInOut":c.Easing.Back.InOut,"Bounce.easeInOut":c.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},c.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var a=0;a<this._tweens.length;a++)this._tweens[a].pendingDelete=!0;this._add=[]},removeFrom:function(a,b){void 0===b&&(b=!0);var d,e;if(Array.isArray(a))for(d=0,e=a.length;e>d;d++)this.removeFrom(a[d]);else if(a.type===c.GROUP&&b)for(var d=0,e=a.children.length;e>d;d++)this.removeFrom(a.children[d]);else{for(d=0,e=this._tweens.length;e>d;d++)a===this._tweens[d].target&&this.remove(this._tweens[d]);for(d=0,e=this._add.length;e>d;d++)a===this._add[d].target&&this.remove(this._add[d])}},add:function(a){a._manager=this,this._add.push(a)},create:function(a){return new c.Tween(a,this.game,this)},remove:function(a){var b=this._tweens.indexOf(a);-1!==b?this._tweens[b].pendingDelete=!0:(b=this._add.indexOf(a),-1!==b&&(this._add[b].pendingDelete=!0))},update:function(){var a=this._add.length,b=this._tweens.length;if(0===b&&0===a)return!1;for(var c=0;b>c;)this._tweens[c].update(this.game.time.time)?c++:(this._tweens.splice(c,1),b--);return a>0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(a){return this._tweens.some(function(b){return b.target===a})},_pauseAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a]._pause()},_resumeAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a]._resume()},pauseAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a].pause()},resumeAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a].resume(!0)}},c.TweenManager.prototype.constructor=c.TweenManager,c.Tween=function(a,b,d){this.game=b,this.target=a,this.manager=d,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new c.Signal,this.onLoop=new c.Signal,this.onRepeat=new c.Signal,this.onChildComplete=new c.Signal,this.onComplete=new c.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},c.Tween.prototype={to:function(a,b,d,e,f,g,h){return(void 0===b||0>=b)&&(b=1e3),(void 0===d||null===d)&&(d=c.Easing.Default),void 0===e&&(e=!1),void 0===f&&(f=0),void 0===g&&(g=0),void 0===h&&(h=!1),"string"==typeof d&&this.manager.easeMap[d]&&(d=this.manager.easeMap[d]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new c.TweenData(this).to(a,b,d,f,g,h)),e&&this.start(),this)},from:function(a,b,d,e,f,g,h){return void 0===b&&(b=1e3),(void 0===d||null===d)&&(d=c.Easing.Default),void 0===e&&(e=!1),void 0===f&&(f=0),void 0===g&&(g=0),void 0===h&&(h=!1),"string"==typeof d&&this.manager.easeMap[d]&&(d=this.manager.easeMap[d]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new c.TweenData(this).from(a,b,d,f,g,h)),e&&this.start(),this)},start:function(a){if(void 0===a&&(a=0),null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(var b=0;b<this.timeline.length;b++)for(var c in this.timeline[b].vEnd)this.properties[c]=this.target[c]||0,Array.isArray(this.properties[c])||(this.properties[c]*=1);for(var b=0;b<this.timeline.length;b++)this.timeline[b].loadValues();return this.manager.add(this),this.isRunning=!0,(0>a||a>this.timeline.length-1)&&(a=0),this.current=a,this.timeline[this.current].start(),this},stop:function(a){return void 0===a&&(a=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,a&&(this.onComplete.dispatch(this.target,this),this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(a,b,c){if(0===this.timeline.length)return this;if(void 0===c&&(c=0),-1===c)for(var d=0;d<this.timeline.length;d++)this.timeline[d][a]=b;else this.timeline[c][a]=b;return this},delay:function(a,b){return this.updateTweenData("delay",a,b)},repeat:function(a,b,c){return void 0===b&&(b=0),this.updateTweenData("repeatCounter",a,c),this.updateTweenData("repeatDelay",b,c)},repeatDelay:function(a,b){return this.updateTweenData("repeatDelay",a,b)},yoyo:function(a,b,c){return void 0===b&&(b=0),this.updateTweenData("yoyo",a,c),this.updateTweenData("yoyoDelay",b,c)},yoyoDelay:function(a,b){return this.updateTweenData("yoyoDelay",a,b)},easing:function(a,b){return"string"==typeof a&&this.manager.easeMap[a]&&(a=this.manager.easeMap[a]),this.updateTweenData("easingFunction",a,b)},interpolation:function(a,b,d){return void 0===b&&(b=c.Math),this.updateTweenData("interpolationFunction",a,d),this.updateTweenData("interpolationContext",b,d)},repeatAll:function(a){return void 0===a&&(a=0),this.repeatCounter=a,this},chain:function(){for(var a=arguments.length;a--;)a>0?arguments[a-1].chainedTween=arguments[a]:this.chainedTween=arguments[a];return this},loop:function(a){return void 0===a&&(a=!0),a?this.repeatAll(-1):this.repeatCounter=0,this},onUpdateCallback:function(a,b){return this._onUpdateCallback=a,this._onUpdateCallbackContext=b,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var a=0;a<this.timeline.length;a++)this.timeline[a].isRunning||(this.timeline[a].startTime+=this.game.time.time-this._pausedTime)}},_resume:function(){this._codePaused||this.resume()},update:function(a){if(this.pendingDelete)return!1;if(this.isPaused)return!0;var b=this.timeline[this.current].update(a);if(b===c.TweenData.PENDING)return!0;if(b===c.TweenData.RUNNING)return this._hasStarted||(this.onStart.dispatch(this.target,this),this._hasStarted=!0),null!==this._onUpdateCallback&&this._onUpdateCallback.call(this._onUpdateCallbackContext,this,this.timeline[this.current].value,this.timeline[this.current]),this.isRunning;if(b===c.TweenData.LOOPED)return this.onLoop.dispatch(this.target,this),!0;if(b===c.TweenData.COMPLETE){var d=!1;return this.reverse?(this.current--,this.current<0&&(this.current=this.timeline.length-1,d=!0)):(this.current++,this.current===this.timeline.length&&(this.current=0,d=!0)),d?-1===this.repeatCounter?(this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):this.repeatCounter>0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(a,b){if(null===this.game||null===this.target)return null;void 0===a&&(a=60),void 0===b&&(b=[]);for(var c=0;c<this.timeline.length;c++)for(var d in this.timeline[c].vEnd)this.properties[d]=this.target[d]||0,Array.isArray(this.properties[d])||(this.properties[d]*=1);for(var c=0;c<this.timeline.length;c++)this.timeline[c].loadValues();for(var c=0;c<this.timeline.length;c++)b=b.concat(this.timeline[c].generateData(a));return b}},Object.defineProperty(c.Tween.prototype,"totalDuration",{get:function(){for(var a=0,b=0;b<this.timeline.length;b++)a+=this.timeline[b].duration;return a}}),c.Tween.prototype.constructor=c.Tween,c.TweenData=function(a){this.parent=a,this.game=a.game,this.vStart={},this.vStartCache={},this.vEnd={},this.vEndCache={},this.duration=1e3,this.percent=0,this.value=0,this.repeatCounter=0,this.repeatDelay=0,this.interpolate=!1,this.yoyo=!1,this.yoyoDelay=0,this.inReverse=!1,this.delay=0,this.dt=0,this.startTime=null,this.easingFunction=c.Easing.Default,this.interpolationFunction=c.Math.linearInterpolation,this.interpolationContext=c.Math,this.isRunning=!1,this.isFrom=!1
-},c.TweenData.PENDING=0,c.TweenData.RUNNING=1,c.TweenData.LOOPED=2,c.TweenData.COMPLETE=3,c.TweenData.prototype={to:function(a,b,c,d,e,f){return this.vEnd=a,this.duration=b,this.easingFunction=c,this.delay=d,this.repeatCounter=e,this.yoyo=f,this.isFrom=!1,this},from:function(a,b,c,d,e,f){return this.vEnd=a,this.duration=b,this.easingFunction=c,this.delay=d,this.repeatCounter=e,this.yoyo=f,this.isFrom=!0,this},start:function(){if(this.startTime=this.game.time.time+this.delay,this.dt=this.parent.reverse?this.duration:0,this.isRunning=this.delay>0?!1:!0,this.isFrom)for(var a in this.vStartCache)this.vStart[a]=this.vEndCache[a],this.vEnd[a]=this.vStartCache[a],this.parent.target[a]=this.vStart[a];return this.value=0,this.yoyoCounter=0,this},loadValues:function(){for(var a in this.parent.properties){if(this.vStart[a]=this.parent.properties[a],Array.isArray(this.vEnd[a])){if(0===this.vEnd[a].length)continue;0===this.percent&&(this.vEnd[a]=[this.vStart[a]].concat(this.vEnd[a]))}"undefined"!=typeof this.vEnd[a]?("string"==typeof this.vEnd[a]&&(this.vEnd[a]=this.vStart[a]+parseFloat(this.vEnd[a],10)),this.parent.properties[a]=this.vEnd[a]):this.vEnd[a]=this.vStart[a],this.vStartCache[a]=this.vStart[a],this.vEndCache[a]=this.vEnd[a]}return this},update:function(a){if(this.isRunning){if(a<this.startTime)return c.TweenData.RUNNING}else{if(!(a>=this.startTime))return c.TweenData.PENDING;this.isRunning=!0}this.parent.reverse?(this.dt-=this.game.time.elapsedMS*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=this.game.time.elapsedMS*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var b in this.vEnd){var d=this.vStart[b],e=this.vEnd[b];this.parent.target[b]=Array.isArray(e)?this.interpolationFunction.call(this.interpolationContext,e,this.value):d+(e-d)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():c.TweenData.RUNNING},generateData:function(a){this.dt=this.parent.reverse?this.duration:0;var b=[],c=!1,d=1/a*1e3;do{this.parent.reverse?(this.dt-=d,this.dt=Math.max(this.dt,0)):(this.dt+=d,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var e={};for(var f in this.vEnd){var g=this.vStart[f],h=this.vEnd[f];e[f]=Array.isArray(h)?this.interpolationFunction(h,this.value):g+(h-g)*this.value}b.push(e),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(c=!0)}while(!c);if(this.yoyo){var i=b.slice();i.reverse(),b=b.concat(i)}return b},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter)return c.TweenData.COMPLETE;this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return c.TweenData.COMPLETE;if(this.inReverse)for(var a in this.vStartCache)this.vStart[a]=this.vEndCache[a],this.vEnd[a]=this.vStartCache[a];else{for(var a in this.vStartCache)this.vStart[a]=this.vStartCache[a],this.vEnd[a]=this.vEndCache[a];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.dt=this.parent.reverse?this.duration:0,c.TweenData.LOOPED}},c.TweenData.prototype.constructor=c.TweenData,c.Easing={Linear:{None:function(a){return a}},Quadratic:{In:function(a){return a*a},Out:function(a){return a*(2-a)},InOut:function(a){return(a*=2)<1?.5*a*a:-.5*(--a*(a-2)-1)}},Cubic:{In:function(a){return a*a*a},Out:function(a){return--a*a*a+1},InOut:function(a){return(a*=2)<1?.5*a*a*a:.5*((a-=2)*a*a+2)}},Quartic:{In:function(a){return a*a*a*a},Out:function(a){return 1- --a*a*a*a},InOut:function(a){return(a*=2)<1?.5*a*a*a*a:-.5*((a-=2)*a*a*a-2)}},Quintic:{In:function(a){return a*a*a*a*a},Out:function(a){return--a*a*a*a*a+1},InOut:function(a){return(a*=2)<1?.5*a*a*a*a*a:.5*((a-=2)*a*a*a*a+2)}},Sinusoidal:{In:function(a){return 0===a?0:1===a?1:1-Math.cos(a*Math.PI/2)},Out:function(a){return 0===a?0:1===a?1:Math.sin(a*Math.PI/2)},InOut:function(a){return 0===a?0:1===a?1:.5*(1-Math.cos(Math.PI*a))}},Exponential:{In:function(a){return 0===a?0:Math.pow(1024,a-1)},Out:function(a){return 1===a?1:1-Math.pow(2,-10*a)},InOut:function(a){return 0===a?0:1===a?1:(a*=2)<1?.5*Math.pow(1024,a-1):.5*(-Math.pow(2,-10*(a-1))+2)}},Circular:{In:function(a){return 1-Math.sqrt(1-a*a)},Out:function(a){return Math.sqrt(1- --a*a)},InOut:function(a){return(a*=2)<1?-.5*(Math.sqrt(1-a*a)-1):.5*(Math.sqrt(1-(a-=2)*a)+1)}},Elastic:{In:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),-(c*Math.pow(2,10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d)))},Out:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),c*Math.pow(2,-10*a)*Math.sin(2*(a-b)*Math.PI/d)+1)},InOut:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),(a*=2)<1?-.5*c*Math.pow(2,10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d):c*Math.pow(2,-10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d)*.5+1)}},Back:{In:function(a){var b=1.70158;return a*a*((b+1)*a-b)},Out:function(a){var b=1.70158;return--a*a*((b+1)*a+b)+1},InOut:function(a){var b=2.5949095;return(a*=2)<1?.5*a*a*((b+1)*a-b):.5*((a-=2)*a*((b+1)*a+b)+2)}},Bounce:{In:function(a){return 1-c.Easing.Bounce.Out(1-a)},Out:function(a){return 1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375},InOut:function(a){return.5>a?.5*c.Easing.Bounce.In(2*a):.5*c.Easing.Bounce.Out(2*a-1)+.5}}},c.Easing.Default=c.Easing.Linear.None,c.Easing.Power0=c.Easing.Linear.None,c.Easing.Power1=c.Easing.Quadratic.Out,c.Easing.Power2=c.Easing.Cubic.Out,c.Easing.Power3=c.Easing.Quartic.Out,c.Easing.Power4=c.Easing.Quintic.Out,c.Time=function(a){this.game=a,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=0,this.physicsElapsedMS=0,this.desiredFps=60,this.suggestedFps=null,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.fps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new c.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},c.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start()},add:function(a){return this._timers.push(a),a},create:function(a){void 0===a&&(a=!0);var b=new c.Timer(this.game,a);return this._timers.push(b),b},removeAll:function(){for(var a=0;a<this._timers.length;a++)this._timers[a].destroy();this._timers=[],this.events.removeAll()},update:function(a){this.game.raf._isSetTimeOut?this.updateSetTimeout(a):this.updateRAF(a),this.advancedTiming&&this.updateAdvancedTiming(),this.game.paused||(this.events.update(this.time),this._timers.length&&this.updateTimers())},updateSetTimeout:function(a){var b=this.time;this.time=a,this.elapsedMS=this.time-b,this.prevTime=this.now,this.now=a,this.elapsed=this.now-this.prevTime,this.timeToCall=Math.floor(Math.max(0,1e3/this.desiredFps-(this.timeCallExpected-a))),this.timeCallExpected=a+this.timeToCall,this.physicsElapsed=1/this.desiredFps,this.physicsElapsedMS=1e3*this.physicsElapsed},updateRAF:function(a){var b=this.time;this.time=Date.now(),this.elapsedMS=this.time-b,this.prevTime=this.now,this.now=a,this.elapsed=this.now-this.prevTime,this.physicsElapsed=1/this.desiredFps,this.physicsElapsedMS=1e3*this.physicsElapsed},updateTimers:function(){for(var a=0,b=this._timers.length;b>a;)this._timers[a].update(this.time)?a++:(this._timers.splice(a,1),b--)},updateAdvancedTiming:function(){this._frameCount++,this._elapsedAccumulator+=this.elapsed,this._frameCount>=2*this.desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3&&(this.fps=Math.round(1e3*this.frames/(this.now-this._timeLastSecond)),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0)},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var a=this._timers.length;a--;)this._timers[a]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var a=this._timers.length;a--;)this._timers[a]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(a){return this.time-a},elapsedSecondsSince:function(a){return.001*(this.time-a)},reset:function(){this._started=this.time,this.removeAll()}},c.Time.prototype.constructor=c.Time,c.Timer=function(a,b){void 0===b&&(b=!0),this.game=a,this.running=!1,this.autoDestroy=b,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new c.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},c.Timer.MINUTE=6e4,c.Timer.SECOND=1e3,c.Timer.HALF=500,c.Timer.QUARTER=250,c.Timer.prototype={create:function(a,b,d,e,f,g){a=Math.round(a);var h=a;h+=0===this._now?this.game.time.time:this._now;var i=new c.TimerEvent(this,a,h,d,b,e,f,g);return this.events.push(i),this.order(),this.expired=!1,i},add:function(a,b,c){return this.create(a,!1,0,b,c,Array.prototype.splice.call(arguments,3))},repeat:function(a,b,c,d){return this.create(a,!1,b,c,d,Array.prototype.splice.call(arguments,4))},loop:function(a,b,c){return this.create(a,!0,0,b,c,Array.prototype.splice.call(arguments,3))},start:function(a){if(!this.running){this._started=this.game.time.time+(a||0),this.running=!0;for(var b=0;b<this.events.length;b++)this.events[b].tick=this.events[b].delay+this._started}},stop:function(a){this.running=!1,void 0===a&&(a=!0),a&&(this.events.length=0)},remove:function(a){for(var b=0;b<this.events.length;b++)if(this.events[b]===a)return this.events[b].pendingDelete=!0,!0;return!1},order:function(){this.events.length>0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(a,b){return a.tick<b.tick?-1:a.tick>b.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(a){if(this.paused)return!0;if(this.elapsed=a-this._now,this._now=a,this.elapsed>this.timeCap&&this.adjustEvents(a-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i<this._len&&this.running&&this._now>=this.events[this._i].tick&&!this.events[this._i].pendingDelete;)this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick),this._newTick<0&&(this._newTick=this._now+this.events[this._i].delay),this.events[this._i].loop===!0?(this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):this.events[this._i].repeatCount>0?(this.events[this._i].repeatCount--,this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):(this._marked++,this.events[this._i].pendingDelete=!0,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)),this._i++;this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return this.expired&&this.autoDestroy?!1:!0},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(a){for(var b=0;b<this.events.length;b++)if(!this.events[b].pendingDelete){var c=this.events[b].tick-a;0>c&&(c=0),this.events[b].tick=this._now+c}var d=this.nextTick-a;this.nextTick=0>d?this._now:this._now+d},resume:function(){if(this.paused){var a=this.game.time.time;this._pauseTotal+=a-this._now,this._now=a,this.adjustEvents(this._pauseStarted),this.paused=!1,this._codePaused=!1}},_resume:function(){this._codePaused||this.resume()},removeAll:function(){this.onComplete.removeAll(),this.events.length=0,this._len=0,this._i=0},destroy:function(){this.onComplete.removeAll(),this.running=!1,this.events=[],this._len=0,this._i=0}},Object.defineProperty(c.Timer.prototype,"next",{get:function(){return this.nextTick}}),Object.defineProperty(c.Timer.prototype,"duration",{get:function(){return this.running&&this.nextTick>this._now?this.nextTick-this._now:0}}),Object.defineProperty(c.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(c.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(c.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),c.Timer.prototype.constructor=c.Timer,c.TimerEvent=function(a,b,c,d,e,f,g,h){this.timer=a,this.delay=b,this.tick=c,this.repeatCount=d-1,this.loop=e,this.callback=f,this.callbackContext=g,this.args=h,this.pendingDelete=!1},c.TimerEvent.prototype.constructor=c.TimerEvent,c.AnimationManager=function(a){this.sprite=a,this.game=a.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},c.AnimationManager.prototype={loadFrameData:function(a,b){if(void 0===a)return!1;if(this.isLoaded)for(var c in this._anims)this._anims[c].updateFrameData(a);return this._frameData=a,void 0===b||null===b?this.frame=0:"string"==typeof b?this.frameName=b:this.frame=b,this.isLoaded=!0,!0},copyFrameData:function(a,b){if(this._frameData=a.clone(),this.isLoaded)for(var c in this._anims)this._anims[c].updateFrameData(this._frameData);return void 0===b||null===b?this.frame=0:"string"==typeof b?this.frameName=b:this.frame=b,this.isLoaded=!0,!0},add:function(a,b,d,e,f){return b=b||[],d=d||60,void 0===e&&(e=!1),void 0===f&&(f=b&&"number"==typeof b[0]?!0:!1),this._outputFrames=[],this._frameData.getFrameIndexes(b,f,this._outputFrames),this._anims[a]=new c.Animation(this.game,this.sprite,a,this._frameData,this._outputFrames,d,e),this.currentAnim=this._anims[a],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[a]},validateFrames:function(a,b){void 0===b&&(b=!0);for(var c=0;c<a.length;c++)if(b===!0){if(a[c]>this._frameData.total)return!1}else if(this._frameData.checkFrameName(a[c])===!1)return!1;return!0},play:function(a,b,c,d){return this._anims[a]?this.currentAnim===this._anims[a]?this.currentAnim.isPlaying===!1?(this.currentAnim.paused=!1,this.currentAnim.play(b,c,d)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[a],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(b,c,d)):void 0},stop:function(a,b){void 0===b&&(b=!1),"string"==typeof a?this._anims[a]&&(this.currentAnim=this._anims[a],this.currentAnim.stop(b)):this.currentAnim&&this.currentAnim.stop(b)},update:function(){return this.updateIfVisible&&!this.sprite.visible?!1:this.currentAnim&&this.currentAnim.update()?(this.currentFrame=this.currentAnim.currentFrame,!0):!1},next:function(a){this.currentAnim&&(this.currentAnim.next(a),this.currentFrame=this.currentAnim.currentFrame)},previous:function(a){this.currentAnim&&(this.currentAnim.previous(a),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(a){return"string"==typeof a&&this._anims[a]?this._anims[a]:null},refreshFrame:function(){this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid])},destroy:function(){var a=null;for(var a in this._anims)this._anims.hasOwnProperty(a)&&this._anims[a].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},c.AnimationManager.prototype.constructor=c.AnimationManager,Object.defineProperty(c.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(c.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(c.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(a){this.currentAnim.paused=a}}),Object.defineProperty(c.AnimationManager.prototype,"name",{get:function(){return this.currentAnim?this.currentAnim.name:void 0}}),Object.defineProperty(c.AnimationManager.prototype,"frame",{get:function(){return this.currentFrame?this.currentFrame.index:void 0},set:function(a){"number"==typeof a&&this._frameData&&null!==this._frameData.getFrame(a)&&(this.currentFrame=this._frameData.getFrame(a),this.currentFrame&&this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(c.AnimationManager.prototype,"frameName",{get:function(){return this.currentFrame?this.currentFrame.name:void 0},set:function(a){"string"==typeof a&&this._frameData&&null!==this._frameData.getFrameByName(a)?(this.currentFrame=this._frameData.getFrameByName(a),this.currentFrame&&(this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame))):console.warn("Cannot set frameName: "+a)}}),c.Animation=function(a,b,d,e,f,g,h){void 0===h&&(h=!1),this.game=a,this._parent=b,this._frameData=e,this.name=d,this._frames=[],this._frames=this._frames.concat(f),this.delay=1e3/g,this.loop=h,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new c.Signal,this.onUpdate=null,this.onComplete=new c.Signal,this.onLoop=new c.Signal,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},c.Animation.prototype={play:function(a,b,c){return"number"==typeof a&&(this.delay=1e3/a),"boolean"==typeof b&&(this.loop=b),"undefined"!=typeof c&&(this.killOnComplete=c),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},setFrame:function(a,b){var c;if(void 0===b&&(b=!1),"string"==typeof a)for(var d=0;d<this._frames.length;d++)this._frameData.getFrame(this._frames[d]).name===a&&(c=d);else if("number"==typeof a)if(b)c=a;else for(var d=0;d<this._frames.length;d++)this._frames[d]===c&&(c=d);c&&(this._frameIndex=c-1,this._timeNextFrame=this.game.time.time,this.update())},stop:function(a,b){void 0===a&&(a=!1),void 0===b&&(b=!1),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,a&&(this.currentFrame=this._frameData.getFrame(this._frames[0]),this._parent.setFrame(this.currentFrame)),b&&(this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this))},onPause:function(){this.isPlaying&&(this._frameDiff=this._timeNextFrame-this.game.time.time)},onResume:function(){this.isPlaying&&(this._timeNextFrame=this.game.time.time+this._frameDiff)},update:function(){return this.isPaused?!1:this.isPlaying&&this.game.time.time>=this._timeNextFrame?(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay&&(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay),this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this._frameIndex+=this._frameSkip,this._frameIndex>=this._frames.length?this.loop?(this._frameIndex%=this._frames.length,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),this.onUpdate?(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData):!0):(this.complete(),!1):this.updateCurrentFrame(!0)):!1},updateCurrentFrame:function(a,b){if(void 0===b&&(b=!1),!this._frameData)return!1;var c=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(b||!b&&c!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),this.onUpdate&&a?(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData):!0},next:function(a){void 0===a&&(a=1);var b=this._frameIndex+a;b>=this._frames.length&&(this.loop?b%=this._frames.length:b=this._frames.length-1),b!==this._frameIndex&&(this._frameIndex=b,this.updateCurrentFrame(!0))},previous:function(a){void 0===a&&(a=1);var b=this._frameIndex-a;0>b&&(this.loop?b=this._frames.length+b:b++),b!==this._frameIndex&&(this._frameIndex=b,this.updateCurrentFrame(!0))},updateFrameData:function(a){this._frameData=a,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(this.game.onPause.remove(this.onPause,this),this.game.onResume.remove(this.onResume,this),this.game=null,this._parent=null,this._frames=null,this._frameData=null,this.currentFrame=null,this.isPlaying=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},c.Animation.prototype.constructor=c.Animation,Object.defineProperty(c.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(a){this.isPaused=a,a?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(c.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(c.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(a){this.currentFrame=this._frameData.getFrame(this._frames[a]),null!==this.currentFrame&&(this._frameIndex=a,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(c.Animation.prototype,"speed",{get:function(){return Math.round(1e3/this.delay)},set:function(a){a>=1&&(this.delay=1e3/a)}}),Object.defineProperty(c.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(a){a&&null===this.onUpdate?this.onUpdate=new c.Signal:a||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),c.Animation.generateFrameNames=function(a,b,d,e,f){void 0===e&&(e="");var g=[],h="";if(d>b)for(var i=b;d>=i;i++)h="number"==typeof f?c.Utils.pad(i.toString(),f,"0",1):i.toString(),h=a+h+e,g.push(h);else for(var i=b;i>=d;i--)h="number"==typeof f?c.Utils.pad(i.toString(),f,"0",1):i.toString(),h=a+h+e,g.push(h);return g},c.Frame=function(a,b,d,e,f,g){this.index=a,this.x=b,this.y=d,this.width=e,this.height=f,this.name=g,this.centerX=Math.floor(e/2),this.centerY=Math.floor(f/2),this.distance=c.Math.distance(0,0,e,f),this.rotated=!1,this.rotationDirection="cw",this.trimmed=!1,this.sourceSizeW=e,this.sourceSizeH=f,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},c.Frame.prototype={resize:function(a,b){this.width=a,this.height=b,this.centerX=Math.floor(a/2),this.centerY=Math.floor(b/2),this.distance=c.Math.distance(0,0,a,b),this.sourceSizeW=a,this.sourceSizeH=b,this.right=this.x+a,this.bottom=this.y+b},setTrim:function(a,b,c,d,e,f,g){this.trimmed=a,a&&(this.sourceSizeW=b,this.sourceSizeH=c,this.centerX=Math.floor(b/2),this.centerY=Math.floor(c/2),this.spriteSourceSizeX=d,this.spriteSourceSizeY=e,this.spriteSourceSizeW=f,this.spriteSourceSizeH=g)},clone:function(){var a=new c.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var b in this)this.hasOwnProperty(b)&&(a[b]=this[b]);return a},getRect:function(a){return void 0===a?a=new c.Rectangle(this.x,this.y,this.width,this.height):a.setTo(this.x,this.y,this.width,this.height),a}},c.Frame.prototype.constructor=c.Frame,c.FrameData=function(){this._frames=[],this._frameNames=[]},c.FrameData.prototype={addFrame:function(a){return a.index=this._frames.length,this._frames.push(a),""!==a.name&&(this._frameNames[a.name]=a.index),a},getFrame:function(a){return a>=this._frames.length&&(a=0),this._frames[a]},getFrameByName:function(a){return"number"==typeof this._frameNames[a]?this._frames[this._frameNames[a]]:null},checkFrameName:function(a){return null==this._frameNames[a]?!1:!0},clone:function(){for(var a=new c.FrameData,b=0;b<this._frames.length;b++)a._frames.push(this._frames[b].clone());for(var d in this._frameNames)this._frameNames.hasOwnProperty(d)&&a._frameNames.push(this._frameNames[d]);return a},getFrameRange:function(a,b,c){void 0===c&&(c=[]);for(var d=a;b>=d;d++)c.push(this._frames[d]);return c},getFrames:function(a,b,c){if(void 0===b&&(b=!0),void 0===c&&(c=[]),void 0===a||0===a.length)for(var d=0;d<this._frames.length;d++)c.push(this._frames[d]);else for(var d=0;d<a.length;d++)c.push(b?this.getFrame(a[d]):this.getFrameByName(a[d]));return c},getFrameIndexes:function(a,b,c){if(void 0===b&&(b=!0),void 0===c&&(c=[]),void 0===a||0===a.length)for(var d=0;d<this._frames.length;d++)c.push(this._frames[d].index);else for(var d=0;d<a.length;d++)b?c.push(this._frames[a[d]].index):this.getFrameByName(a[d])&&c.push(this.getFrameByName(a[d]).index);return c}},c.FrameData.prototype.constructor=c.FrameData,Object.defineProperty(c.FrameData.prototype,"total",{get:function(){return this._frames.length}}),c.AnimationParser={spriteSheet:function(a,b,d,e,f,g,h){var i=b;if("string"==typeof b&&(i=a.cache.getImage(b)),null===i)return null;var j=i.width,k=i.height;0>=d&&(d=Math.floor(-j/Math.min(-1,d))),0>=e&&(e=Math.floor(-k/Math.min(-1,e)));var l=Math.floor((j-g)/(d+h)),m=Math.floor((k-g)/(e+h)),n=l*m;if(-1!==f&&(n=f),0===j||0===k||d>j||e>k||0===n)return console.warn("Phaser.AnimationParser.spriteSheet: '"+b+"'s width/height zero or width/height < given frameWidth/frameHeight"),null;for(var o=new c.FrameData,p=g,q=g,r=0;n>r;r++)o.addFrame(new c.Frame(r,p,q,d,e,"")),p+=d+h,p+d>j&&(p=g,q+=e+h);return o},JSONData:function(a,b){if(!b.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(b);for(var d,e=new c.FrameData,f=b.frames,g=0;g<f.length;g++)d=e.addFrame(new c.Frame(g,f[g].frame.x,f[g].frame.y,f[g].frame.w,f[g].frame.h,f[g].filename)),f[g].trimmed&&d.setTrim(f[g].trimmed,f[g].sourceSize.w,f[g].sourceSize.h,f[g].spriteSourceSize.x,f[g].spriteSourceSize.y,f[g].spriteSourceSize.w,f[g].spriteSourceSize.h);return e},JSONDataHash:function(a,b){if(!b.frames)return console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"),void console.log(b);var d,e=new c.FrameData,f=b.frames,g=0;for(var h in f)d=e.addFrame(new c.Frame(g,f[h].frame.x,f[h].frame.y,f[h].frame.w,f[h].frame.h,h)),f[h].trimmed&&d.setTrim(f[h].trimmed,f[h].sourceSize.w,f[h].sourceSize.h,f[h].spriteSourceSize.x,f[h].spriteSourceSize.y,f[h].spriteSourceSize.w,f[h].spriteSourceSize.h),g++;return e},XMLData:function(a,b){if(!b.getElementsByTagName("TextureAtlas"))return void console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");for(var d,e,f,g,h,i,j,k,l,m,n,o=new c.FrameData,p=b.getElementsByTagName("SubTexture"),q=0;q<p.length;q++)f=p[q].attributes,e=f.name.value,g=parseInt(f.x.value,10),h=parseInt(f.y.value,10),i=parseInt(f.width.value,10),j=parseInt(f.height.value,10),k=null,l=null,f.frameX&&(k=Math.abs(parseInt(f.frameX.value,10)),l=Math.abs(parseInt(f.frameY.value,10)),m=parseInt(f.frameWidth.value,10),n=parseInt(f.frameHeight.value,10)),d=o.addFrame(new c.Frame(q,g,h,i,j,e)),(null!==k||null!==l)&&d.setTrim(!0,i,j,k,l,m,n);return o}},c.Cache=function(a){this.game=a,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new c.Signal,this._cacheMap=[],this._cacheMap[c.Cache.CANVAS]=this._cache.canvas,this._cacheMap[c.Cache.IMAGE]=this._cache.image,this._cacheMap[c.Cache.TEXTURE]=this._cache.texture,this._cacheMap[c.Cache.SOUND]=this._cache.sound,this._cacheMap[c.Cache.TEXT]=this._cache.text,this._cacheMap[c.Cache.PHYSICS]=this._cache.physics,this._cacheMap[c.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[c.Cache.BINARY]=this._cache.binary,this._cacheMap[c.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[c.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[c.Cache.JSON]=this._cache.json,this._cacheMap[c.Cache.XML]=this._cache.xml,this._cacheMap[c.Cache.VIDEO]=this._cache.video,this._cacheMap[c.Cache.SHADER]=this._cache.shader,this._cacheMap[c.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this.addDefaultImage(),this.addMissingImage()},c.Cache.CANVAS=1,c.Cache.IMAGE=2,c.Cache.TEXTURE=3,c.Cache.SOUND=4,c.Cache.TEXT=5,c.Cache.PHYSICS=6,c.Cache.TILEMAP=7,c.Cache.BINARY=8,c.Cache.BITMAPDATA=9,c.Cache.BITMAPFONT=10,c.Cache.JSON=11,c.Cache.XML=12,c.Cache.VIDEO=13,c.Cache.SHADER=14,c.Cache.RENDER_TEXTURE=15,c.Cache.prototype={addCanvas:function(a,b,c){void 0===c&&(c=b.getContext("2d")),this._cache.canvas[a]={canvas:b,context:c}},addImage:function(a,b,d){this.checkImageKey(a)&&this.removeImage(a);var e={key:a,url:b,data:d,base:new PIXI.BaseTexture(d),frame:new c.Frame(0,0,0,d.width,d.height,a),frameData:new c.FrameData};return e.frameData.addFrame(new c.Frame(0,0,0,d.width,d.height,b)),this._cache.image[a]=e,this._resolveURL(b,e),e},addDefaultImage:function(){var a=new Image;a.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";var b=this.addImage("__default",null,a);PIXI.TextureCache.__default=new PIXI.Texture(b.base)},addMissingImage:function(){var a=new Image;a.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";var b=this.addImage("__missing",null,a);PIXI.TextureCache.__missing=new PIXI.Texture(b.base)},addSound:function(a,b,c,d,e){void 0===d&&(d=!0,e=!1),void 0===e&&(d=!1,e=!0);
-var f=!1;e&&(f=!0),this._cache.sound[a]={url:b,data:c,isDecoding:!1,decoded:f,webAudio:d,audioTag:e,locked:this.game.sound.touchLocked},this._resolveURL(b,this._cache.sound[a])},addText:function(a,b,c){this._cache.text[a]={url:b,data:c},this._resolveURL(b,this._cache.text[a])},addPhysicsData:function(a,b,c,d){this._cache.physics[a]={url:b,data:c,format:d},this._resolveURL(b,this._cache.physics[a])},addTilemap:function(a,b,c,d){this._cache.tilemap[a]={url:b,data:c,format:d},this._resolveURL(b,this._cache.tilemap[a])},addBinary:function(a,b){this._cache.binary[a]=b},addBitmapData:function(a,b,d){return b.key=a,void 0===d&&(d=new c.FrameData,d.addFrame(b.textureFrame)),this._cache.bitmapData[a]={data:b,frameData:d},b},addBitmapFont:function(a,b,d,e,f,g,h){var i={url:b,data:d,font:null,base:new PIXI.BaseTexture(d)};i.font="json"===f?c.LoaderParser.jsonBitmapFont(e,i.base,g,h):c.LoaderParser.xmlBitmapFont(e,i.base,g,h),this._cache.bitmapFont[a]=i,this._resolveURL(b,i)},addJSON:function(a,b,c){this._cache.json[a]={url:b,data:c},this._resolveURL(b,this._cache.json[a])},addXML:function(a,b,c){this._cache.xml[a]={url:b,data:c},this._resolveURL(b,this._cache.xml[a])},addVideo:function(a,b,c,d){this._cache.video[a]={url:b,data:c,isBlob:d,locked:!0},this._resolveURL(b,this._cache.video[a])},addShader:function(a,b,c){this._cache.shader[a]={url:b,data:c},this._resolveURL(b,this._cache.shader[a])},addRenderTexture:function(a,b){this._cache.renderTexture[a]={texture:b,frame:new c.Frame(0,0,0,b.width,b.height,"","")}},addSpriteSheet:function(a,b,d,e,f,g,h,i){var j={key:a,url:b,data:d,frameWidth:e,frameHeight:f,margin:h,spacing:i,base:new PIXI.BaseTexture(d),frameData:c.AnimationParser.spriteSheet(this.game,d,e,f,g,h,i)};this._cache.image[a]=j,this._resolveURL(b,j)},addTextureAtlas:function(a,b,d,e,f){var g={key:a,url:b,data:d,base:new PIXI.BaseTexture(d)};g.frameData=f===c.Loader.TEXTURE_ATLAS_XML_STARLING?c.AnimationParser.XMLData(this.game,e,a):Array.isArray(e.frames)?c.AnimationParser.JSONData(this.game,e,a):c.AnimationParser.JSONDataHash(this.game,e,a),this._cache.image[a]=g,this._resolveURL(b,g)},reloadSound:function(a){var b=this,c=this.getSound(a);c&&(c.data.src=c.url,c.data.addEventListener("canplaythrough",function(){return b.reloadSoundComplete(a)},!1),c.data.load())},reloadSoundComplete:function(a){var b=this.getSound(a);b&&(b.locked=!1,this.onSoundUnlock.dispatch(a))},updateSound:function(a,b,c){var d=this.getSound(a);d&&(d[b]=c)},decodedSound:function(a,b){var c=this.getSound(a);c.data=b,c.decoded=!0,c.isDecoding=!1},isSoundDecoded:function(a){var b=this.getItem(a,c.Cache.SOUND,"isSoundDecoded");return b?b.decoded:void 0},isSoundReady:function(a){var b=this.getItem(a,c.Cache.SOUND,"isSoundDecoded");return b?b.decoded&&!this.game.sound.touchLocked:void 0},checkKey:function(a,b){return this._cacheMap[a][b]?!0:!1},checkURL:function(a){return this._urlMap[this._resolveURL(a)]?!0:!1},checkCanvasKey:function(a){return this.checkKey(c.Cache.CANVAS,a)},checkImageKey:function(a){return this.checkKey(c.Cache.IMAGE,a)},checkTextureKey:function(a){return this.checkKey(c.Cache.TEXTURE,a)},checkSoundKey:function(a){return this.checkKey(c.Cache.SOUND,a)},checkTextKey:function(a){return this.checkKey(c.Cache.TEXT,a)},checkPhysicsKey:function(a){return this.checkKey(c.Cache.PHYSICS,a)},checkTilemapKey:function(a){return this.checkKey(c.Cache.TILEMAP,a)},checkBinaryKey:function(a){return this.checkKey(c.Cache.BINARY,a)},checkBitmapDataKey:function(a){return this.checkKey(c.Cache.BITMAPDATA,a)},checkBitmapFontKey:function(a){return this.checkKey(c.Cache.BITMAPFONT,a)},checkJSONKey:function(a){return this.checkKey(c.Cache.JSON,a)},checkXMLKey:function(a){return this.checkKey(c.Cache.XML,a)},checkVideoKey:function(a){return this.checkKey(c.Cache.VIDEO,a)},checkShaderKey:function(a){return this.checkKey(c.Cache.SHADER,a)},checkRenderTextureKey:function(a){return this.checkKey(c.Cache.RENDER_TEXTURE,a)},getItem:function(a,b,c,d){return this.checkKey(b,a)?void 0===d?this._cacheMap[b][a]:this._cacheMap[b][a][d]:(c&&console.warn("Phaser.Cache."+c+': Key "'+a+'" not found in Cache.'),null)},getCanvas:function(a){return this.getItem(a,c.Cache.CANVAS,"getCanvas","canvas")},getImage:function(a,b){(void 0===a||null===a)&&(a="__default"),void 0===b&&(b=!1);var d=this.getItem(a,c.Cache.IMAGE,"getImage");return null===d&&(d=this.getItem("__missing",c.Cache.IMAGE,"getImage")),b?d:d.data},getTextureFrame:function(a){return this.getItem(a,c.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(a){return this.getItem(a,c.Cache.SOUND,"getSound")},getSoundData:function(a){return this.getItem(a,c.Cache.SOUND,"getSoundData","data")},getText:function(a){return this.getItem(a,c.Cache.TEXT,"getText","data")},getPhysicsData:function(a,b,d){var e=this.getItem(a,c.Cache.PHYSICS,"getPhysicsData","data");if(null===e||void 0===b||null===b)return e;if(e[b]){var f=e[b];if(!f||!d)return f;for(var g in f)if(g=f[g],g.fixtureKey===d)return g;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+d+" in "+a+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+a+" / "+b+'"');return null},getTilemapData:function(a){return this.getItem(a,c.Cache.TILEMAP,"getTilemapData")},getBinary:function(a){return this.getItem(a,c.Cache.BINARY,"getBinary")},getBitmapData:function(a){return this.getItem(a,c.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(a){return this.getItem(a,c.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(a,b){var d=this.getItem(a,c.Cache.JSON,"getJSON","data");return d?b?c.Utils.extend(!0,d):d:null},getXML:function(a){return this.getItem(a,c.Cache.XML,"getXML","data")},getVideo:function(a){return this.getItem(a,c.Cache.VIDEO,"getVideo")},getShader:function(a){return this.getItem(a,c.Cache.SHADER,"getShader","data")},getRenderTexture:function(a){return this.getItem(a,c.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),this.getItem(a,b,"getBaseTexture","base")},getFrame:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),this.getItem(a,b,"getFrame","frame")},getFrameCount:function(a,b){var c=this.getFrameData(a,b);return c?c.total:0},getFrameData:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),this.getItem(a,b,"getFrameData","frameData")},hasFrameData:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),null!==this.getItem(a,b,"","frameData")},updateFrameData:function(a,b,d){void 0===d&&(d=c.Cache.IMAGE),this._cacheMap[d][a]&&(this._cacheMap[d][a].frameData=b)},getFrameByIndex:function(a,b,c){var d=this.getFrameData(a,c);return d?d.getFrame(b):null},getFrameByName:function(a,b,c){var d=this.getFrameData(a,c);return d?d.getFrameByName(b):null},getPixiTexture:function(a){if(PIXI.TextureCache[a])return PIXI.TextureCache[a];var b=this.getPixiBaseTexture(a);return b?new PIXI.Texture(b):null},getPixiBaseTexture:function(a){if(PIXI.BaseTextureCache[a])return PIXI.BaseTextureCache[a];var b=this.getItem(a,c.Cache.IMAGE,"getPixiBaseTexture");return null!==b?b.base:null},getURL:function(a){var a=this._resolveURL(a);return a?this._urlMap[a]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+a+'" or Cache.autoResolveURL was false'),null)},getKeys:function(a){void 0===a&&(a=c.Cache.IMAGE);var b=[];if(this._cacheMap[a])for(var d in this._cacheMap[a])"__default"!==d&&"__missing"!==d&&b.push(d);return b},removeCanvas:function(a){delete this._cache.canvas[a]},removeImage:function(a,b){void 0===b&&(b=!0);var c=this.getImage(a,!0);b&&c.base&&c.base.destroy(),delete this._cache.image[a]},removeSound:function(a){delete this._cache.sound[a]},removeText:function(a){delete this._cache.text[a]},removePhysics:function(a){delete this._cache.physics[a]},removeTilemap:function(a){delete this._cache.tilemap[a]},removeBinary:function(a){delete this._cache.binary[a]},removeBitmapData:function(a){delete this._cache.bitmapData[a]},removeBitmapFont:function(a){delete this._cache.bitmapFont[a]},removeJSON:function(a){delete this._cache.json[a]},removeXML:function(a){delete this._cache.xml[a]},removeVideo:function(a){delete this._cache.video[a]},removeShader:function(a){delete this._cache.shader[a]},removeRenderTexture:function(a){delete this._cache.renderTexture[a]},removeSpriteSheet:function(a){delete this._cache.spriteSheet[a]},removeTextureAtlas:function(a){delete this._cache.atlas[a]},clearGLTextures:function(){for(var a in this.cache.image)this.cache.image[a].base._glTextures=[]},_resolveURL:function(a,b){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+a,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",b&&(this._urlMap[this._urlTemp]=b),this._urlTemp):null},destroy:function(){for(var a=0;a<this._cacheMap.length;a++){var b=this._cacheMap[a];for(var c in b)"__default"!==c&&"__missing"!==c&&(b[c].destroy&&b[c].destroy(),delete b[c])}this._urlMap=null,this._urlResolver=null,this._urlTemp=null}},c.Cache.prototype.constructor=c.Cache,c.Loader=function(a){this.game=a,this.cache=a.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.onLoadStart=new c.Signal,this.onLoadComplete=new c.Signal,this.onPackComplete=new c.Signal,this.onFileStart=new c.Signal,this.onFileComplete=new c.Signal,this.onFileError=new c.Signal,this.useXDomainRequest=!1,this._warnedAboutXDomainRequest=!1,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},c.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,c.Loader.TEXTURE_ATLAS_JSON_HASH=1,c.Loader.TEXTURE_ATLAS_XML_STARLING=2,c.Loader.PHYSICS_LIME_CORONA_JSON=3,c.Loader.PHYSICS_PHASER_JSON=4,c.Loader.prototype={setPreloadSprite:function(a,b){b=b||0,this.preloadSprite={sprite:a,direction:b,width:a.width,height:a.height,rect:null},this.preloadSprite.rect=0===b?new c.Rectangle(0,0,1,a.height):new c.Rectangle(0,0,a.width,1),a.crop(this.preloadSprite.rect),a.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(a,b){return this.getAssetIndex(a,b)>-1},getAssetIndex:function(a,b){for(var c=-1,d=0;d<this._fileList.length;d++){var e=this._fileList[d];if(e.type===a&&e.key===b&&(c=d,!e.loaded&&!e.loading))break}return c},getAsset:function(a,b){var c=this.getAssetIndex(a,b);return c>-1?{index:c,file:this._fileList[c]}:!1},reset:function(a,b){void 0===b&&(b=!1),this.resetLocked||(a&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,b&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(a,b,c,d,e,f){if(void 0===e&&(e=!1),void 0===b||""===b)return console.warn("Phaser.Loader: Invalid or no key given of type "+a),this;if(void 0===c||null===c){if(!f)return console.warn("Phaser.Loader: No URL given for file type: "+a+" key: "+b),this;c=b+f}var g={type:a,key:b,path:this.path,url:c,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(d)for(var h in d)g[h]=d[h];var i=this.getAssetIndex(a,b);if(e&&i>-1){var j=this._fileList[i];j.loading||j.loaded?(this._fileList.push(g),this._totalFileCount++):this._fileList[i]=g}else-1===i&&(this._fileList.push(g),this._totalFileCount++);return this},replaceInFileList:function(a,b,c,d){return this.addToFileList(a,b,c,d,!0)},pack:function(a,b,c,d){if(void 0===b&&(b=null),void 0===c&&(c=null),void 0===d&&(d=null),!b&&!c)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var e={type:"packfile",key:a,url:b,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:d};c&&("string"==typeof c&&(c=JSON.parse(c)),e.data=c||{},e.loaded=!0);for(var f=0;f<this._fileList.length+1;f++){var g=this._fileList[f];if(!g||!g.loaded&&!g.loading&&"packfile"!==g.type){this._fileList.splice(f,1,e),this._totalPackCount++;break}}return this},image:function(a,b,c){return this.addToFileList("image",a,b,void 0,c,".png")},text:function(a,b,c){return this.addToFileList("text",a,b,void 0,c,".txt")},json:function(a,b,c){return this.addToFileList("json",a,b,void 0,c,".json")},shader:function(a,b,c){return this.addToFileList("shader",a,b,void 0,c,".frag")},xml:function(a,b,c){return this.addToFileList("xml",a,b,void 0,c,".xml")},script:function(a,b,c,d){return void 0===c&&(c=!1),c!==!1&&void 0===d&&(d=this),this.addToFileList("script",a,b,{syncPoint:!0,callback:c,callbackContext:d},!1,".js")},binary:function(a,b,c,d){return void 0===c&&(c=!1),c!==!1&&void 0===d&&(d=c),this.addToFileList("binary",a,b,{callback:c,callbackContext:d},!1,".bin")},spritesheet:function(a,b,c,d,e,f,g){return void 0===e&&(e=-1),void 0===f&&(f=0),void 0===g&&(g=0),this.addToFileList("spritesheet",a,b,{frameWidth:c,frameHeight:d,frameMax:e,margin:f,spacing:g},!1,".png")},audio:function(a,b,c){return this.game.sound.noAudio?this:(void 0===c&&(c=!0),"string"==typeof b&&(b=[b]),this.addToFileList("audio",a,b,{buffer:null,autoDecode:c}))},audiosprite:function(a,b,c,d,e){return this.game.sound.noAudio?this:(void 0===c&&(c=null),void 0===d&&(d=null),void 0===e&&(e=!0),this.audio(a,b,e),c?this.json(a+"-audioatlas",c):d?("string"==typeof d&&(d=JSON.parse(d)),this.cache.addJSON(a+"-audioatlas","",d)):console.warn("Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object"),this)},video:function(a,b,c,d){return void 0===c&&(c=this.game.device.firefox?"loadeddata":"canplaythrough"),void 0===d&&(d=!1),"string"==typeof b&&(b=[b]),this.addToFileList("video",a,b,{buffer:null,asBlob:d,loadEvent:c})},tilemap:function(a,b,d,e){if(void 0===b&&(b=null),void 0===d&&(d=null),void 0===e&&(e=c.Tilemap.CSV),b||d||(b=e===c.Tilemap.CSV?a+".csv":a+".json"),d){switch(e){case c.Tilemap.CSV:break;case c.Tilemap.TILED_JSON:"string"==typeof d&&(d=JSON.parse(d))}this.cache.addTilemap(a,null,d,e)}else this.addToFileList("tilemap",a,b,{format:e});return this},physics:function(a,b,d,e){return void 0===b&&(b=null),void 0===d&&(d=null),void 0===e&&(e=c.Physics.LIME_CORONA_JSON),b||d||(b=a+".json"),d?("string"==typeof d&&(d=JSON.parse(d)),this.cache.addPhysicsData(a,null,d,e)):this.addToFileList("physics",a,b,{format:e}),this},bitmapFont:function(a,b,c,d,e,f){if((void 0===b||null===b)&&(b=a+".png"),void 0===c&&(c=null),void 0===d&&(d=null),void 0===e&&(e=0),void 0===f&&(f=0),c)this.addToFileList("bitmapfont",a,b,{atlasURL:c,xSpacing:e,ySpacing:f});else if("string"==typeof d){var g,h;try{g=JSON.parse(d)}catch(i){h=this.parseXml(d)}if(!h&&!g)throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");this.addToFileList("bitmapfont",a,b,{atlasURL:null,atlasData:g||h,atlasType:g?"json":"xml",xSpacing:e,ySpacing:f})}return this},atlasJSONArray:function(a,b,d,e){return this.atlas(a,b,d,e,c.Loader.TEXTURE_ATLAS_JSON_ARRAY)},atlasJSONHash:function(a,b,d,e){return this.atlas(a,b,d,e,c.Loader.TEXTURE_ATLAS_JSON_HASH)},atlasXML:function(a,b,d,e){return void 0===d&&(d=null),void 0===e&&(e=null),d||e||(d=a+".xml"),this.atlas(a,b,d,e,c.Loader.TEXTURE_ATLAS_XML_STARLING)},atlas:function(a,b,d,e,f){if((void 0===b||null===b)&&(b=a+".png"),void 0===d&&(d=null),void 0===e&&(e=null),void 0===f&&(f=c.Loader.TEXTURE_ATLAS_JSON_ARRAY),d||e||(d=f===c.Loader.TEXTURE_ATLAS_XML_STARLING?a+".xml":a+".json"),d)this.addToFileList("textureatlas",a,b,{atlasURL:d,format:f});else{switch(f){case c.Loader.TEXTURE_ATLAS_JSON_ARRAY:"string"==typeof e&&(e=JSON.parse(e));break;case c.Loader.TEXTURE_ATLAS_XML_STARLING:if("string"==typeof e){var g=this.parseXml(e);if(!g)throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");e=g}}this.addToFileList("textureatlas",a,b,{atlasURL:null,atlasData:e,format:f})}return this},withSyncPoint:function(a,b){this._withSyncPointDepth++;try{a.call(b||this,this)}finally{this._withSyncPointDepth--}return this},addSyncPoint:function(a,b){var c=this.getAsset(a,b);return c&&(c.file.syncPoint=!0),this},removeFile:function(a,b){var c=this.getAsset(a,b);c&&(c.loaded||c.loading||this._fileList.splice(c.index,1))},removeAll:function(){this._fileList.length=0,this._flightQueue.length=0},start:function(){this.isLoading||(this.hasLoaded=!1,this.isLoading=!0,this.updateProgress(),this.processLoadQueue())},processLoadQueue:function(){if(!this.isLoading)return console.warn("Phaser.Loader - active loading canceled / reset"),void this.finishedLoading(!0);for(var a=0;a<this._flightQueue.length;a++){var b=this._flightQueue[a];(b.loaded||b.error)&&(this._flightQueue.splice(a,1),a--,b.loading=!1,b.requestUrl=null,b.requestObject=null,b.error&&this.onFileError.dispatch(b.key,b),"packfile"!==b.type?(this._loadedFileCount++,this.onFileComplete.dispatch(this.progress,b.key,!b.error,this._loadedFileCount,this._totalFileCount)):"packfile"===b.type&&b.error&&(this._loadedPackCount++,this.onPackComplete.dispatch(b.key,!b.error,this._loadedPackCount,this._totalPackCount)))}for(var d=!1,e=this.enableParallel?c.Math.clamp(this.maxParallelDownloads,1,12):1,a=this._processingHead;a<this._fileList.length;a++){var b=this._fileList[a];if("packfile"===b.type&&!b.error&&b.loaded&&a===this._processingHead&&(this.processPack(b),this._loadedPackCount++,this.onPackComplete.dispatch(b.key,!b.error,this._loadedPackCount,this._totalPackCount)),b.loaded||b.error?a===this._processingHead&&(this._processingHead=a+1):!b.loading&&this._flightQueue.length<e&&("packfile"!==b.type||b.data?d||(this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this._flightQueue.push(b),b.loading=!0,this.onFileStart.dispatch(this.progress,b.key,b.url),this.loadFile(b)):(this._flightQueue.push(b),b.loading=!0,this.loadFile(b))),!b.loaded&&b.syncPoint&&(d=!0),this._flightQueue.length>=e||d&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var f=this;setTimeout(function(){f.finishedLoading(!0)},2e3)}},finishedLoading:function(a){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,a||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.onLoadComplete.dispatch(),this.reset(),this.game.state.loadComplete())},asyncComplete:function(a,b){void 0===b&&(b=""),a.loaded=!0,a.error=!!b,b&&(a.errorMessage=b,console.warn("Phaser.Loader - "+a.type+"["+a.key+"]: "+b)),this.processLoadQueue()},processPack:function(a){var b=a.data[a.key];if(!b)return void console.warn("Phaser.Loader - "+a.key+": pack has data, but not for pack key");for(var d=0;d<b.length;d++){var e=b[d];switch(e.type){case"image":this.image(e.key,e.url,e.overwrite);break;case"text":this.text(e.key,e.url,e.overwrite);break;case"json":this.json(e.key,e.url,e.overwrite);break;case"xml":this.xml(e.key,e.url,e.overwrite);break;case"script":this.script(e.key,e.url,e.callback,a.callbackContext||this);break;case"binary":this.binary(e.key,e.url,e.callback,a.callbackContext||this);break;case"spritesheet":this.spritesheet(e.key,e.url,e.frameWidth,e.frameHeight,e.frameMax,e.margin,e.spacing);break;case"video":this.video(e.key,e.urls);break;case"audio":this.audio(e.key,e.urls,e.autoDecode);break;case"audiosprite":this.audiosprite(e.key,e.urls,e.jsonURL,e.jsonData,e.autoDecode);break;case"tilemap":this.tilemap(e.key,e.url,e.data,c.Tilemap[e.format]);break;case"physics":this.physics(e.key,e.url,e.data,c.Loader[e.format]);break;case"bitmapFont":this.bitmapFont(e.key,e.textureURL,e.atlasURL,e.atlasData,e.xSpacing,e.ySpacing);break;case"atlasJSONArray":this.atlasJSONArray(e.key,e.textureURL,e.atlasURL,e.atlasData);break;case"atlasJSONHash":this.atlasJSONHash(e.key,e.textureURL,e.atlasURL,e.atlasData);break;case"atlasXML":this.atlasXML(e.key,e.textureURL,e.atlasURL,e.atlasData);break;case"atlas":this.atlas(e.key,e.textureURL,e.atlasURL,e.atlasData,c.Loader[e.format]);break;case"shader":this.shader(e.key,e.url,e.overwrite)}}},transformUrl:function(a,b){return a?"http"===a.substr(0,4)||"//"===a.substr(0,2)?a:this.baseURL+b.path+a:!1},loadFile:function(a){switch(a.type){case"packfile":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.fileComplete);break;case"image":case"spritesheet":case"textureatlas":case"bitmapfont":this.loadImageTag(a);break;case"audio":a.url=this.getAudioURL(a.url),a.url?this.game.sound.usingWebAudio?this.xhrLoad(a,this.transformUrl(a.url,a),"arraybuffer",this.fileComplete):this.game.sound.usingAudioTag&&this.loadAudioTag(a):this.fileError(a,null,"No supported audio URL specified or device does not have audio playback support");break;case"video":a.url=this.getVideoURL(a.url),a.url?a.asBlob?this.xhrLoad(a,this.transformUrl(a.url,a),"arraybuffer",this.fileComplete):this.loadVideoTag(a):this.fileError(a,null,"No supported video URL specified or device does not have video playback support");break;case"json":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.jsonLoadComplete);break;case"xml":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.xmlLoadComplete);break;case"tilemap":a.format===c.Tilemap.TILED_JSON?this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.jsonLoadComplete):a.format===c.Tilemap.CSV?this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.csvLoadComplete):this.asyncComplete(a,"invalid Tilemap format: "+a.format);break;case"text":case"script":case"shader":case"physics":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.fileComplete);break;case"binary":this.xhrLoad(a,this.transformUrl(a.url,a),"arraybuffer",this.fileComplete)}},loadImageTag:function(a){var b=this;a.data=new Image,a.data.name=a.key,this.crossOrigin&&(a.data.crossOrigin=this.crossOrigin),a.data.onload=function(){a.data.onload&&(a.data.onload=null,a.data.onerror=null,b.fileComplete(a))},a.data.onerror=function(){a.data.onload&&(a.data.onload=null,a.data.onerror=null,b.fileError(a))},a.data.src=this.transformUrl(a.url,a),a.data.complete&&a.data.width&&a.data.height&&(a.data.onload=null,a.data.onerror=null,this.fileComplete(a))},loadVideoTag:function(a){var b=this;a.data=document.createElement("video"),a.data.name=a.key,a.data.controls=!1,a.data.autoplay=!1;var d=function(){a.data.removeEventListener(a.loadEvent,d,!1),a.data.onerror=null,a.data.canplay=!0,c.GAMES[b.game.id].load.fileComplete(a)};a.data.onerror=function(){a.data.removeEventListener(a.loadEvent,d,!1),a.data.onerror=null,a.data.canplay=!1,b.fileError(a)},a.data.addEventListener(a.loadEvent,d,!1),a.data.src=this.transformUrl(a.url,a),a.data.load()},loadAudioTag:function(a){var b=this;if(this.game.sound.touchLocked)a.data=new Audio,a.data.name=a.key,a.data.preload="auto",a.data.src=this.transformUrl(a.url,a),this.fileComplete(a);else{a.data=new Audio,a.data.name=a.key;var d=function(){a.data.removeEventListener("canplaythrough",d,!1),a.data.onerror=null,c.GAMES[b.game.id].load.fileComplete(a)};a.data.onerror=function(){a.data.removeEventListener("canplaythrough",d,!1),a.data.onerror=null,b.fileError(a)},a.data.preload="auto",a.data.src=this.transformUrl(a.url,a),a.data.addEventListener("canplaythrough",d,!1),a.data.load()}},xhrLoad:function(a,b,c,d,e){if(this.useXDomainRequest&&window.XDomainRequest)return void this.xhrLoadWithXDR(a,b,c,d,e);var f=new XMLHttpRequest;f.open("GET",b,!0),f.responseType=c,e=e||this.fileError;var g=this;f.onload=function(){try{return d.call(g,a,f)}catch(b){g.hasLoaded?window.console&&console.error(b):g.asyncComplete(a,b.message||"Exception")}},f.onerror=function(){try{return e.call(g,a,f)}catch(b){g.hasLoaded?window.console&&console.error(b):g.asyncComplete(a,b.message||"Exception")}},a.requestObject=f,a.requestUrl=b,f.send()},xhrLoadWithXDR:function(a,b,c,d,e){this._warnedAboutXDomainRequest||this.game.device.ie&&!(this.game.device.ieVersion>=10)||(this._warnedAboutXDomainRequest=!0,console.warn("Phaser.Loader - using XDomainRequest outside of IE 9"));var f=new window.XDomainRequest;f.open("GET",b,!0),f.responseType=c,f.timeout=3e3,e=e||this.fileError;var g=this;f.onerror=function(){try{return e.call(g,a,f)}catch(b){g.asyncComplete(a,b.message||"Exception")}},f.ontimeout=function(){try{return e.call(g,a,f)}catch(b){g.asyncComplete(a,b.message||"Exception")}},f.onprogress=function(){},f.onload=function(){try{return d.call(g,a,f)}catch(b){g.asyncComplete(a,b.message||"Exception")}},a.requestObject=f,a.requestUrl=b,setTimeout(function(){f.send()},0)},getVideoURL:function(a){for(var b=0;b<a.length;b++){var c,d=a[b];if(d.uri)d=d.uri,c=d.type;else{if(0===d.indexOf("blob:")||0===d.indexOf("data:"))return d;d.indexOf("?")>=0&&(d=d.substr(0,d.indexOf("?")));var e=d.substr((Math.max(0,d.lastIndexOf("."))||1/0)+1);c=e.toLowerCase()}if(this.game.device.canPlayVideo(c))return a[b]}return null},getAudioURL:function(a){if(this.game.sound.noAudio)return null;for(var b=0;b<a.length;b++){var c,d=a[b];if(d.uri)d=d.uri,c=d.type;else{if(0===d.indexOf("blob:")||0===d.indexOf("data:"))return d;d.indexOf("?")>=0&&(d=d.substr(0,d.indexOf("?")));var e=d.substr((Math.max(0,d.lastIndexOf("."))||1/0)+1);c=e.toLowerCase()}if(this.game.device.canPlayAudio(c))return a[b]}return null},fileError:function(a,b,c){var d=a.requestUrl||this.transformUrl(a.url,a),e="error loading asset from URL "+d;!c&&b&&(c=b.status),c&&(e=e+" ("+c+")"),this.asyncComplete(a,e)},fileComplete:function(a,b){var d=!0;switch(a.type){case"packfile":var e=JSON.parse(b.responseText);a.data=e||{};break;case"image":this.cache.addImage(a.key,a.url,a.data);break;case"spritesheet":this.cache.addSpriteSheet(a.key,a.url,a.data,a.frameWidth,a.frameHeight,a.frameMax,a.margin,a.spacing);break;case"textureatlas":if(null==a.atlasURL)this.cache.addTextureAtlas(a.key,a.url,a.data,a.atlasData,a.format);else if(d=!1,a.format==c.Loader.TEXTURE_ATLAS_JSON_ARRAY||a.format==c.Loader.TEXTURE_ATLAS_JSON_HASH)this.xhrLoad(a,this.transformUrl(a.atlasURL,a),"text",this.jsonLoadComplete);else{if(a.format!=c.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+a.format);this.xhrLoad(a,this.transformUrl(a.atlasURL,a),"text",this.xmlLoadComplete)}break;case"bitmapfont":a.atlasURL?(d=!1,this.xhrLoad(a,this.transformUrl(a.atlasURL,a),"text",function(a,b){var c;try{c=JSON.parse(b.responseText)}catch(d){}c?(a.atlasType="json",this.jsonLoadComplete(a,b)):(a.atlasType="xml",this.xmlLoadComplete(a,b))})):this.cache.addBitmapFont(a.key,a.url,a.data,a.atlasData,a.atlasType,a.xSpacing,a.ySpacing);break;case"video":if(a.asBlob)try{a.data=new Blob([new Uint8Array(b.response)])}catch(f){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+a.key)}this.cache.addVideo(a.key,a.url,a.data,a.asBlob);break;case"audio":this.game.sound.usingWebAudio?(a.data=b.response,this.cache.addSound(a.key,a.url,a.data,!0,!1),a.autoDecode&&this.game.sound.decode(a.key)):this.cache.addSound(a.key,a.url,a.data,!1,!0);break;case"text":a.data=b.responseText,this.cache.addText(a.key,a.url,a.data);break;case"shader":a.data=b.responseText,this.cache.addShader(a.key,a.url,a.data);break;case"physics":var e=JSON.parse(b.responseText);this.cache.addPhysicsData(a.key,a.url,e,a.format);break;case"script":a.data=document.createElement("script"),a.data.language="javascript",a.data.type="text/javascript",a.data.defer=!1,a.data.text=b.responseText,document.head.appendChild(a.data),a.callback&&(a.data=a.callback.call(a.callbackContext,a.key,b.responseText));break;case"binary":a.data=a.callback?a.callback.call(a.callbackContext,a.key,b.response):b.response,this.cache.addBinary(a.key,a.data)}d&&this.asyncComplete(a)},jsonLoadComplete:function(a,b){var c=JSON.parse(b.responseText);"tilemap"===a.type?this.cache.addTilemap(a.key,a.url,c,a.format):"bitmapfont"===a.type?this.cache.addBitmapFont(a.key,a.url,a.data,c,a.atlasType,a.xSpacing,a.ySpacing):"json"===a.type?this.cache.addJSON(a.key,a.url,c):this.cache.addTextureAtlas(a.key,a.url,a.data,c,a.format),this.asyncComplete(a)},csvLoadComplete:function(a,b){var c=b.responseText;this.cache.addTilemap(a.key,a.url,c,a.format),this.asyncComplete(a)},xmlLoadComplete:function(a,b){var c=b.responseText,d=this.parseXml(c);if(!d){var e=b.responseType||b.contentType;return console.warn("Phaser.Loader - "+a.key+": invalid XML ("+e+")"),void this.asyncComplete(a,"invalid XML")}"bitmapfont"===a.type?this.cache.addBitmapFont(a.key,a.url,a.data,d,a.atlasType,a.xSpacing,a.ySpacing):"textureatlas"===a.type?this.cache.addTextureAtlas(a.key,a.url,a.data,d,a.format):"xml"===a.type&&this.cache.addXML(a.key,a.url,d),this.asyncComplete(a)},parseXml:function(a){var b;try{if(window.DOMParser){var c=new DOMParser;b=c.parseFromString(a,"text/xml")}else b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a)}catch(d){b=null}return b&&b.documentElement&&!b.getElementsByTagName("parsererror").length?b:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(c.Loader.prototype,"progressFloat",{get:function(){var a=this._loadedFileCount/this._totalFileCount*100;return c.Math.clamp(a||0,0,100)}}),Object.defineProperty(c.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),c.Loader.prototype.constructor=c.Loader,c.LoaderParser={bitmapFont:function(a,b,c,d){return this.xmlBitmapFont(a,b,c,d)},xmlBitmapFont:function(a,b,c,d){var e={},f=a.getElementsByTagName("info")[0],g=a.getElementsByTagName("common")[0];e.font=f.getAttribute("face"),e.size=parseInt(f.getAttribute("size"),10),e.lineHeight=parseInt(g.getAttribute("lineHeight"),10)+d,e.chars={};for(var h=a.getElementsByTagName("char"),i=0;i<h.length;i++){var j=parseInt(h[i].getAttribute("id"),10);e.chars[j]={x:parseInt(h[i].getAttribute("x"),10),y:parseInt(h[i].getAttribute("y"),10),width:parseInt(h[i].getAttribute("width"),10),height:parseInt(h[i].getAttribute("height"),10),xOffset:parseInt(h[i].getAttribute("xoffset"),10),yOffset:parseInt(h[i].getAttribute("yoffset"),10),xAdvance:parseInt(h[i].getAttribute("xadvance"),10)+c,kerning:{}}}var k=a.getElementsByTagName("kerning");for(i=0;i<k.length;i++){var l=parseInt(k[i].getAttribute("first"),10),m=parseInt(k[i].getAttribute("second"),10),n=parseInt(k[i].getAttribute("amount"),10);e.chars[m].kerning[l]=n}return this.finalizeBitmapFont(b,e)},jsonBitmapFont:function(a,b,c,d){var e={font:a.font.info._face,size:parseInt(a.font.info._size,10),lineHeight:parseInt(a.font.common._lineHeight,10)+d,chars:{}};return a.font.chars["char"].forEach(function(a){var b=parseInt(a._id,10);e.chars[b]={x:parseInt(a._x,10),y:parseInt(a._y,10),width:parseInt(a._width,10),height:parseInt(a._height,10),xOffset:parseInt(a._xoffset,10),yOffset:parseInt(a._yoffset,10),xAdvance:parseInt(a._xadvance,10)+c,kerning:{}}}),a.font.kernings&&a.font.kernings.kerning&&a.font.kernings.kerning.forEach(function(a){e.chars[a._second].kerning[a._first]=parseInt(a._amount,10)}),this.finalizeBitmapFont(b,e)},finalizeBitmapFont:function(a,b){return Object.keys(b.chars).forEach(function(d){var e=b.chars[d];e.texture=new PIXI.Texture(a,new c.Rectangle(e.x,e.y,e.width,e.height))
-}),b}},c.AudioSprite=function(a,b){this.game=a,this.key=b,this.config=this.game.cache.getJSON(b+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var c in this.config.spritemap){var d=this.config.spritemap[c],e=this.game.add.sound(this.key);e.addMarker(c,d.start,d.end-d.start,null,d.loop),this.sounds[c]=e}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},c.AudioSprite.prototype={play:function(a,b){return void 0===b&&(b=1),this.sounds[a].play(a,null,b)},stop:function(a){if(a)this.sounds[a].stop();else for(var b in this.sounds)this.sounds[b].stop()},get:function(a){return this.sounds[a]}},c.AudioSprite.prototype.constructor=c.AudioSprite,c.Sound=function(a,b,d,e,f){void 0===d&&(d=1),void 0===e&&(e=!1),void 0===f&&(f=a.sound.connectToMaster),this.game=a,this.name=b,this.key=b,this.loop=e,this.volume=d,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,this.gainNode=void 0===this.context.createGain?this.context.createGainNode():this.context.createGain(),this.gainNode.gain.value=d*this.game.sound.volume,f&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(b)&&this.game.cache.isSoundReady(b)?(this._sound=this.game.cache.getSoundData(b),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new c.Signal,this.onPlay=new c.Signal,this.onPause=new c.Signal,this.onResume=new c.Signal,this.onLoop=new c.Signal,this.onStop=new c.Signal,this.onMute=new c.Signal,this.onMarkerComplete=new c.Signal,this.onFadeComplete=new c.Signal,this._volume=d,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},c.Sound.prototype={soundHasUnlocked:function(a){a===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(a,b,c,d,e){(void 0===d||null===d)&&(d=1),void 0===e&&(e=!1),this.markers[a]={name:a,start:b,stop:b+c,volume:d,duration:c,durationMS:1e3*c,loop:e}},removeMarker:function(a){delete this.markers[a]},onEndedHandler:function(){this.isPlaying=!1,this.stop()},update:function(){return this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),void(this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop())))):void this.destroy()},loopFull:function(a){this.play(null,0,a,!0)},play:function(a,b,c,d,e){if((void 0===a||a===!1||null===a)&&(a=""),void 0===e&&(e=!0),this.isPlaying&&!this.allowMultiple&&!e&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||e))if(this.usingWebAudio)if(this._sound.disconnect(this.externalNode?this.externalNode:this.gainNode),void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(f){}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(""===a&&Object.keys(this.markers).length>0)return this;if(""!==a){if(this.currentMarker=a,!this.markers[a])return this;this.position=this.markers[a].start,this.volume=this.markers[a].volume,this.loop=this.markers[a].loop,this.duration=this.markers[a].duration,this.durationMS=this.markers[a].durationMS,"undefined"!=typeof c&&(this.volume=c),"undefined"!=typeof d&&(this.loop=d),this._tempMarker=a,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else b=b||0,void 0===c&&(c=this._volume),void 0===d&&(d=this.loop),this.position=b,this.volume=c,this.loop=d,this.duration=0,this.durationMS=0,this._tempMarker=a,this._tempPosition=b,this._tempVolume=c,this._tempLoop=d;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this._sound.connect(this.externalNode?this.externalNode:this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===a&&(this._sound.loop=!0),this.loop||""!==a||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===a?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).isDecoding===!1&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._sound.volume=this._muted?0:this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(a,b,c,d){a=a||"",b=b||0,c=c||1,void 0===d&&(d=!1),this.play(a,b,c,d,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var a=this.position+this.pausedPosition/1e3;this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this._sound.connect(this.externalNode?this.externalNode:this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var b=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,a,b):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,a):this._sound.start(0,a,b)}else this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio)if(this._sound.disconnect(this.externalNode?this.externalNode:this.gainNode),void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(a){}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.pendingPlayback=!1,this.isPlaying=!1;var b=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.paused||this.onStop.dispatch(this,b)},fadeIn:function(a,b,c){void 0===b&&(b=!1),void 0===c&&(c=this.currentMarker),this.paused||(this.play(c,0,0,b),this.fadeTo(a,1))},fadeOut:function(a){this.fadeTo(a,0)},fadeTo:function(a,b){if(this.isPlaying&&!this.paused&&b!==this.volume){if(void 0===a&&(a=1e3),void 0===b)return void console.warn("Phaser.Sound.fadeTo: No Volume Specified.");this.fadeTween=this.game.add.tween(this).to({volume:b},a,c.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)}},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},destroy:function(a){void 0===a&&(a=!0),this.stop(),a?this.game.sound.remove(this):(this.markers={},this.context=null,this._buffer=null,this.externalNode=null,this.onDecoded.dispose(),this.onPlay.dispose(),this.onPause.dispose(),this.onResume.dispose(),this.onLoop.dispose(),this.onStop.dispose(),this.onMute.dispose(),this.onMarkerComplete.dispose())}},c.Sound.prototype.constructor=c.Sound,Object.defineProperty(c.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(c.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(c.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(a){a=a||!1,a!==this._muted&&(a?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(c.Sound.prototype,"volume",{get:function(){return this._volume},set:function(a){return this.game.device.firefox&&this.usingAudioTag&&(a=this.game.math.clamp(a,0,1)),this._muted?void(this._muteVolume=a):(this._tempVolume=a,this._volume=a,void(this.usingWebAudio?this.gainNode.gain.value=a:this.usingAudioTag&&this._sound&&(this._sound.volume=a)))}}),c.SoundManager=function(a){this.game=a,this.onSoundDecode=new c.Signal,this.onVolumeChange=new c.Signal,this.onMute=new c.Signal,this.onUnMute=new c.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new c.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},c.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&this.game.device.webAudio===!1&&(this.channels=1),window.PhaserGlobal){if(window.PhaserGlobal.disableAudio===!0)return this.noAudio=!0,void(this.touchLocked=!1);if(window.PhaserGlobal.disableWebAudio===!0)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(window.PhaserGlobal&&window.PhaserGlobal.audioContext)this.context=window.PhaserGlobal.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(a){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(a){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,this.masterGain=void 0===this.context.createGain?this.context.createGainNode():this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||(!this.game.device.cocoonJS&&this.game.device.iOS||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)&&this.setTouchLock()},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.touchLocked=!1,this._unlockSource=null;else if(this.usingWebAudio){var a=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=a,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0)}return!0},stopAll:function(){if(!this.noAudio)for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].stop()},pauseAll:function(){if(!this.noAudio)for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].pause()},resumeAll:function(){if(!this.noAudio)for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].resume()},decode:function(a,b){b=b||null;var c=this.game.cache.getSoundData(a);if(c&&this.game.cache.isSoundDecoded(a)===!1){this.game.cache.updateSound(a,"isDecoding",!0);var d=this;try{this.context.decodeAudioData(c,function(c){c&&(d.game.cache.decodedSound(a,c),d.onSoundDecode.dispatch(a,b))})}catch(e){}}},setDecodedCallback:function(a,b,d){"string"==typeof a&&(a=[a]),this._watchList.reset();for(var e=0;e<a.length;e++)a[e]instanceof c.Sound?this.game.cache.isSoundDecoded(a[e].key)||this._watchList.add(a[e].key):this.game.cache.isSoundDecoded(a[e])||this._watchList.add(a[e]);0===this._watchList.total?(this._watching=!1,b.call(d)):(this._watching=!0,this._watchCallback=b,this._watchContext=d)},update:function(){if(!this.noAudio){!this.touchLocked||null===this._unlockSource||this._unlockSource.playbackState!==this._unlockSource.PLAYING_STATE&&this._unlockSource.playbackState!==this._unlockSource.FINISHED_STATE||(this.touchLocked=!1,this._unlockSource=null);for(var a=0;a<this._sounds.length;a++)this._sounds[a].update();if(this._watching){for(var b=this._watchList.first;b;)this.game.cache.isSoundDecoded(b)&&this._watchList.remove(b),b=this._watchList.next;0===this._watchList.total&&(this._watching=!1,this._watchCallback.call(this._watchContext))}}},add:function(a,b,d,e){void 0===b&&(b=1),void 0===d&&(d=!1),void 0===e&&(e=this.connectToMaster);var f=new c.Sound(this.game,a,b,d,e);return this._sounds.push(f),f},addSprite:function(a){var b=new c.AudioSprite(this.game,a);return b},remove:function(a){for(var b=this._sounds.length;b--;)if(this._sounds[b]===a)return this._sounds[b].destroy(!1),this._sounds.splice(b,1),!0;return!1},removeByKey:function(a){for(var b=this._sounds.length,c=0;b--;)this._sounds[b].key===a&&(this._sounds[b].destroy(!1),this._sounds.splice(b,1),c++);return c},play:function(a,b,c){if(!this.noAudio){var d=this.add(a,b,c);return d.play(),d}},setMute:function(){if(!this._muted){this._muted=!0,this.usingWebAudio&&(this._muteVolume=this.masterGain.gain.value,this.masterGain.gain.value=0);for(var a=0;a<this._sounds.length;a++)this._sounds[a].usingAudioTag&&(this._sounds[a].mute=!0);this.onMute.dispatch()}},unsetMute:function(){if(this._muted&&!this._codeMuted){this._muted=!1,this.usingWebAudio&&(this.masterGain.gain.value=this._muteVolume);for(var a=0;a<this._sounds.length;a++)this._sounds[a].usingAudioTag&&(this._sounds[a].mute=!1);this.onUnMute.dispatch()}},destroy:function(){this.stopAll();for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].destroy();this._sounds=[],this.onSoundDecode.dispose(),this.context&&window.PhaserGlobal&&(window.PhaserGlobal.audioContext=this.context)}},c.SoundManager.prototype.constructor=c.SoundManager,Object.defineProperty(c.SoundManager.prototype,"mute",{get:function(){return this._muted},set:function(a){if(a=a||!1){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(c.SoundManager.prototype,"volume",{get:function(){return this._volume},set:function(a){if(0>a?a=0:a>1&&(a=1),this._volume!==a){if(this._volume=a,this.usingWebAudio)this.masterGain.gain.value=a;else for(var b=0;b<this._sounds.length;b++)this._sounds[b].usingAudioTag&&(this._sounds[b].volume=this._sounds[b].volume*a);this.onVolumeChange.dispatch(a)}}}),c.Utils.Debug=function(a){this.game=a,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.renderShadow=!0,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1},c.Utils.Debug.prototype={boot:function(){this.game.renderType===c.CANVAS?this.context=this.game.context:(this.bmd=this.game.make.bitmapData(this.game.width,this.game.height),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.canvas=c.Canvas.create(this.game.width,this.game.height,"",!0),this.context=this.canvas.getContext("2d"))},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(a,b,c,d){"number"!=typeof a&&(a=0),"number"!=typeof b&&(b=0),c=c||"rgb(255,255,255)",void 0===d&&(d=0),this.currentX=a,this.currentY=b,this.currentColor=c,this.columnWidth=d,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=c,this.context.fillStyle=c,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var a=this.currentX,b=0;b<arguments.length;b++)this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(arguments[b],a+1,this.currentY+1),this.context.fillStyle=this.currentColor),this.context.fillText(arguments[b],a,this.currentY),a+=this.columnWidth;this.currentY+=this.lineHeight},soundInfo:function(a,b,c,d){this.start(b,c,d),this.line("Sound: "+a.key+" Locked: "+a.game.sound.touchLocked),this.line("Is Ready?: "+this.game.cache.isSoundReady(a.key)+" Pending Playback: "+a.pendingPlayback),this.line("Decoded: "+a.isDecoded+" Decoding: "+a.isDecoding),this.line("Total Duration: "+a.totalDuration+" Playing: "+a.isPlaying),this.line("Time: "+a.currentTime),this.line("Volume: "+a.volume+" Muted: "+a.mute),this.line("WebAudio: "+a.usingWebAudio+" Audio: "+a.usingAudioTag),""!==a.currentMarker&&(this.line("Marker: "+a.currentMarker+" Duration: "+a.duration+" (ms: "+a.durationMS+")"),this.line("Start: "+a.markers[a.currentMarker].start+" Stop: "+a.markers[a.currentMarker].stop),this.line("Position: "+a.position)),this.stop()},cameraInfo:function(a,b,c,d){this.start(b,c,d),this.line("Camera ("+a.width+" x "+a.height+")"),this.line("X: "+a.x+" Y: "+a.y),a.bounds&&this.line("Bounds x: "+a.bounds.x+" Y: "+a.bounds.y+" w: "+a.bounds.width+" h: "+a.bounds.height),this.line("View x: "+a.view.x+" Y: "+a.view.y+" w: "+a.view.width+" h: "+a.view.height),this.line("Total in view: "+a.totalInView),this.stop()},timer:function(a,b,c,d){this.start(b,c,d),this.line("Timer (running: "+a.running+" expired: "+a.expired+")"),this.line("Next Tick: "+a.next+" Duration: "+a.duration),this.line("Paused: "+a.paused+" Length: "+a.length),this.stop()},pointer:function(a,b,c,d,e){null!=a&&(void 0===b&&(b=!1),c=c||"rgba(0,255,0,0.5)",d=d||"rgba(255,0,0,0.5)",(b!==!0||a.isUp!==!0)&&(this.start(a.x,a.y-100,e),this.context.beginPath(),this.context.arc(a.x,a.y,a.circle.radius,0,2*Math.PI),this.context.fillStyle=a.active?c:d,this.context.fill(),this.context.closePath(),this.context.beginPath(),this.context.moveTo(a.positionDown.x,a.positionDown.y),this.context.lineTo(a.position.x,a.position.y),this.context.lineWidth=2,this.context.stroke(),this.context.closePath(),this.line("ID: "+a.id+" Active: "+a.active),this.line("World X: "+a.worldX+" World Y: "+a.worldY),this.line("Screen X: "+a.x+" Screen Y: "+a.y),this.line("Duration: "+a.duration+" ms"),this.line("is Down: "+a.isDown+" is Up: "+a.isUp),this.stop()))},spriteInputInfo:function(a,b,c,d){this.start(b,c,d),this.line("Sprite Input: ("+a.width+" x "+a.height+")"),this.line("x: "+a.input.pointerX().toFixed(1)+" y: "+a.input.pointerY().toFixed(1)),this.line("over: "+a.input.pointerOver()+" duration: "+a.input.overDuration().toFixed(0)),this.line("down: "+a.input.pointerDown()+" duration: "+a.input.downDuration().toFixed(0)),this.line("just over: "+a.input.justOver()+" just out: "+a.input.justOut()),this.stop()},key:function(a,b,c,d){this.start(b,c,d,150),this.line("Key:",a.keyCode,"isDown:",a.isDown),this.line("justDown:",a.justDown,"justUp:",a.justUp),this.line("Time Down:",a.timeDown.toFixed(0),"duration:",a.duration.toFixed(0)),this.stop()},inputInfo:function(a,b,c){this.start(a,b,c),this.line("Input"),this.line("X: "+this.game.input.x+" Y: "+this.game.input.y),this.line("World X: "+this.game.input.worldX+" World Y: "+this.game.input.worldY),this.line("Scale X: "+this.game.input.scale.x.toFixed(1)+" Scale Y: "+this.game.input.scale.x.toFixed(1)),this.line("Screen X: "+this.game.input.activePointer.screenX+" Screen Y: "+this.game.input.activePointer.screenY),this.stop()},spriteBounds:function(a,b,c){var d=a.getBounds();d.x+=this.game.camera.x,d.y+=this.game.camera.y,this.rectangle(d,b,c)},ropeSegments:function(a,b,c){var d=a.segments,e=this;d.forEach(function(a){e.rectangle(a,b,c)},this)},spriteInfo:function(a,b,c,d){this.start(b,c,d),this.line("Sprite:  ("+a.width+" x "+a.height+") anchor: "+a.anchor.x+" x "+a.anchor.y),this.line("x: "+a.x.toFixed(1)+" y: "+a.y.toFixed(1)),this.line("angle: "+a.angle.toFixed(1)+" rotation: "+a.rotation.toFixed(1)),this.line("visible: "+a.visible+" in camera: "+a.inCamera),this.line("bounds x: "+a._bounds.x.toFixed(1)+" y: "+a._bounds.y.toFixed(1)+" w: "+a._bounds.width.toFixed(1)+" h: "+a._bounds.height.toFixed(1)),this.stop()},spriteCoords:function(a,b,c,d){this.start(b,c,d,100),a.name&&this.line(a.name),this.line("x:",a.x.toFixed(2),"y:",a.y.toFixed(2)),this.line("pos x:",a.position.x.toFixed(2),"pos y:",a.position.y.toFixed(2)),this.line("world x:",a.world.x.toFixed(2),"world y:",a.world.y.toFixed(2)),this.stop()},lineInfo:function(a,b,c,d){this.start(b,c,d,80),this.line("start.x:",a.start.x.toFixed(2),"start.y:",a.start.y.toFixed(2)),this.line("end.x:",a.end.x.toFixed(2),"end.y:",a.end.y.toFixed(2)),this.line("length:",a.length.toFixed(2),"angle:",a.angle),this.stop()},pixel:function(a,b,c,d){d=d||2,this.start(),this.context.fillStyle=c,this.context.fillRect(a,b,d,d),this.stop()},geom:function(a,b,d,e){void 0===d&&(d=!0),void 0===e&&(e=0),b=b||"rgba(0,255,0,0.4)",this.start(),this.context.fillStyle=b,this.context.strokeStyle=b,a instanceof c.Rectangle||1===e?d?this.context.fillRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height):this.context.strokeRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height):a instanceof c.Circle||2===e?(this.context.beginPath(),this.context.arc(a.x-this.game.camera.x,a.y-this.game.camera.y,a.radius,0,2*Math.PI,!1),this.context.closePath(),d?this.context.fill():this.context.stroke()):a instanceof c.Point||3===e?this.context.fillRect(a.x-this.game.camera.x,a.y-this.game.camera.y,4,4):(a instanceof c.Line||4===e)&&(this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(a.start.x+.5-this.game.camera.x,a.start.y+.5-this.game.camera.y),this.context.lineTo(a.end.x+.5-this.game.camera.x,a.end.y+.5-this.game.camera.y),this.context.closePath(),this.context.stroke()),this.stop()},rectangle:function(a,b,c){void 0===c&&(c=!0),b=b||"rgba(0, 255, 0, 0.4)",this.start(),c?(this.context.fillStyle=b,this.context.fillRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height)):(this.context.strokeStyle=b,this.context.strokeRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height)),this.stop()},text:function(a,b,c,d,e){d=d||"rgb(255,255,255)",e=e||"16px Courier",this.start(),this.context.font=e,this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(a,b+1,c+1)),this.context.fillStyle=d,this.context.fillText(a,b,c),this.stop()},quadTree:function(a,b){b=b||"rgba(255,0,0,0.3)",this.start();var c=a.bounds;if(0===a.nodes.length){this.context.strokeStyle=b,this.context.strokeRect(c.x,c.y,c.width,c.height),this.text("size: "+a.objects.length,c.x+4,c.y+16,"rgb(0,200,0)","12px Courier"),this.context.strokeStyle="rgb(0,255,0)";for(var d=0;d<a.objects.length;d++)this.context.strokeRect(a.objects[d].x,a.objects[d].y,a.objects[d].width,a.objects[d].height)}else for(var d=0;d<a.nodes.length;d++)this.quadTree(a.nodes[d]);this.stop()},body:function(a,b,d){a.body&&(this.start(),a.body.type===c.Physics.ARCADE?c.Physics.Arcade.Body.render(this.context,a.body,b,d):a.body.type===c.Physics.NINJA?c.Physics.Ninja.Body.render(this.context,a.body,b,d):a.body.type===c.Physics.BOX2D&&c.Physics.Box2D.renderBody(this.context,a.body,b),this.stop())},bodyInfo:function(a,b,d,e){a.body&&(this.start(b,d,e,210),a.body.type===c.Physics.ARCADE?c.Physics.Arcade.Body.renderBodyInfo(this,a.body):a.body.type===c.Physics.BOX2D&&this.game.physics.box2d.renderBodyInfo(this,a.body),this.stop())},box2dWorld:function(){this.start(),this.context.translate(-this.game.camera.view.x,-this.game.camera.view.y,0),this.game.physics.box2d.renderDebugDraw(this.context),this.stop()},box2dBody:function(a,b){this.start(),c.Physics.Box2D.renderBody(this.context,a,b),this.stop()}},c.Utils.Debug.prototype.constructor=c.Utils.Debug,c.ArraySet=function(a){this.position=0,this.list=a||[]},c.ArraySet.prototype={add:function(a){return this.exists(a)||this.list.push(a),a},getIndex:function(a){return this.list.indexOf(a)},getByKey:function(a,b){for(var c=this.list.length;c--;)if(this.list[c][a]===b)return this.list[c];return null},exists:function(a){return this.list.indexOf(a)>-1},reset:function(){this.list.length=0},remove:function(a){var b=this.list.indexOf(a);return b>-1?(this.list.splice(b,1),a):void 0},setAll:function(a,b){for(var c=this.list.length;c--;)this.list[c]&&(this.list[c][a]=b)},callAll:function(a){for(var b=Array.prototype.splice.call(arguments,1),c=this.list.length;c--;)this.list[c]&&this.list[c][a]&&this.list[c][a].apply(this.list[c],b)},removeAll:function(a){void 0===a&&(a=!1);for(var b=this.list.length;b--;)if(this.list[b]){var c=this.remove(this.list[b]);a&&c.destroy()}this.position=0,this.list=[]}},Object.defineProperty(c.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(c.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(c.ArraySet.prototype,"next",{get:function(){return this.position<this.list.length?(this.position++,this.list[this.position]):null}}),c.ArraySet.prototype.constructor=c.ArraySet,c.ArrayUtils={getRandomItem:function(a,b,c){if(null==a)return null;void 0===b&&(b=0),void 0===c&&(c=a.length);var d=b+Math.floor(Math.random()*c);return void 0===a[d]?null:a[d]},removeRandomItem:function(a,b,c){if(null==a)return null;void 0===b&&(b=0),void 0===c&&(c=a.length);var d=b+Math.floor(Math.random()*c);if(d<a.length){var e=a.splice(d,1);return void 0===e[0]?null:e[0]}return null},shuffle:function(a){for(var b=a.length-1;b>0;b--){var c=Math.floor(Math.random()*(b+1)),d=a[b];a[b]=a[c],a[c]=d}return a},transposeMatrix:function(a){for(var b=a.length,c=a[0].length,d=new Array(c),e=0;c>e;e++){d[e]=new Array(b);for(var f=b-1;f>-1;f--)d[e][f]=a[f][e]}return d},rotateMatrix:function(a,b){if("string"!=typeof b&&(b=(b%360+360)%360),90===b||-270===b||"rotateLeft"===b)a=c.ArrayUtils.transposeMatrix(a),a=a.reverse();else if(-90===b||270===b||"rotateRight"===b)a=a.reverse(),a=c.ArrayUtils.transposeMatrix(a);else if(180===Math.abs(b)||"rotate180"===b){for(var d=0;d<a.length;d++)a[d].reverse();a=a.reverse()}return a},findClosest:function(a,b){if(!b.length)return 0/0;if(1===b.length||a<b[0])return b[0];for(var c=1;b[c]<a;)c++;var d=b[c-1],e=c<b.length?b[c]:Number.POSITIVE_INFINITY;return a-d>=e-a?e:d},rotate:function(a){var b=a.shift();return a.push(b),b},numberArray:function(a,b){for(var c=[],d=a;b>=d;d++)c.push(d);return c},numberArrayStep:function(a,b,d){a=+a||0;var e=typeof b;"number"!==e&&"string"!==e||!d||d[b]!==a||(b=d=null),d=null==d?1:+d||0,null===b?(b=a,a=0):b=+b||0;for(var f=-1,g=Math.max(c.Math.roundAwayFromZero((b-a)/(d||1)),0),h=new Array(g);++f<g;)h[f]=a,a+=d;return h}},c.Color={packPixel:function(a,b,d,e){return c.Device.LITTLE_ENDIAN?(e<<24|d<<16|b<<8|a)>>>0:(a<<24|b<<16|d<<8|e)>>>0},unpackPixel:function(a,b,d,e){return(void 0===b||null===b)&&(b=c.Color.createColor()),(void 0===d||null===d)&&(d=!1),(void 0===e||null===e)&&(e=!1),c.Device.LITTLE_ENDIAN?(b.a=(4278190080&a)>>>24,b.b=(16711680&a)>>>16,b.g=(65280&a)>>>8,b.r=255&a):(b.r=(4278190080&a)>>>24,b.g=(16711680&a)>>>16,b.b=(65280&a)>>>8,b.a=255&a),b.color=a,b.rgba="rgba("+b.r+","+b.g+","+b.b+","+b.a/255+")",d&&c.Color.RGBtoHSL(b.r,b.g,b.b,b),e&&c.Color.RGBtoHSV(b.r,b.g,b.b,b),b},fromRGBA:function(a,b){return b||(b=c.Color.createColor()),b.r=(4278190080&a)>>>24,b.g=(16711680&a)>>>16,b.b=(65280&a)>>>8,b.a=255&a,b.rgba="rgba("+b.r+","+b.g+","+b.b+","+b.a+")",b},toRGBA:function(a,b,c,d){return a<<24|b<<16|c<<8|d},RGBtoHSL:function(a,b,d,e){e||(e=c.Color.createColor(a,b,d,1)),a/=255,b/=255,d/=255;var f=Math.min(a,b,d),g=Math.max(a,b,d);if(e.h=0,e.s=0,e.l=(g+f)/2,g!==f){var h=g-f;e.s=e.l>.5?h/(2-g-f):h/(g+f),g===a?e.h=(b-d)/h+(d>b?6:0):g===b?e.h=(d-a)/h+2:g===d&&(e.h=(a-b)/h+4),e.h/=6}return e},HSLtoRGB:function(a,b,d,e){if(e?(e.r=d,e.g=d,e.b=d):e=c.Color.createColor(d,d,d),0!==b){var f=.5>d?d*(1+b):d+b-d*b,g=2*d-f;e.r=c.Color.hueToColor(g,f,a+1/3),e.g=c.Color.hueToColor(g,f,a),e.b=c.Color.hueToColor(g,f,a-1/3)}return e.r=Math.floor(255*e.r|0),e.g=Math.floor(255*e.g|0),e.b=Math.floor(255*e.b|0),c.Color.updateColor(e),e},RGBtoHSV:function(a,b,d,e){e||(e=c.Color.createColor(a,b,d,255)),a/=255,b/=255,d/=255;var f=Math.min(a,b,d),g=Math.max(a,b,d),h=g-f;return e.h=0,e.s=0===g?0:h/g,e.v=g,g!==f&&(g===a?e.h=(b-d)/h+(d>b?6:0):g===b?e.h=(d-a)/h+2:g===d&&(e.h=(a-b)/h+4),e.h/=6),e},HSVtoRGB:function(a,b,d,e){void 0===e&&(e=c.Color.createColor(0,0,0,1,a,b,0,d));var f,g,h,i=Math.floor(6*a),j=6*a-i,k=d*(1-b),l=d*(1-j*b),m=d*(1-(1-j)*b);switch(i%6){case 0:f=d,g=m,h=k;break;case 1:f=l,g=d,h=k;break;case 2:f=k,g=d,h=m;break;case 3:f=k,g=l,h=d;break;case 4:f=m,g=k,h=d;break;case 5:f=d,g=k,h=l}return e.r=Math.floor(255*f),e.g=Math.floor(255*g),e.b=Math.floor(255*h),c.Color.updateColor(e),e},hueToColor:function(a,b,c){return 0>c&&(c+=1),c>1&&(c-=1),1/6>c?a+6*(b-a)*c:.5>c?b:2/3>c?a+(b-a)*(2/3-c)*6:a},createColor:function(a,b,d,e,f,g,h,i){var j={r:a||0,g:b||0,b:d||0,a:e||1,h:f||0,s:g||0,l:h||0,v:i||0,color:0,color32:0,rgba:""};return c.Color.updateColor(j)},updateColor:function(a){return a.rgba="rgba("+a.r.toString()+","+a.g.toString()+","+a.b.toString()+","+a.a.toString()+")",a.color=c.Color.getColor(a.r,a.g,a.b),a.color32=c.Color.getColor32(a.a,a.r,a.g,a.b),a},getColor32:function(a,b,c,d){return a<<24|b<<16|c<<8|d},getColor:function(a,b,c){return a<<16|b<<8|c},RGBtoString:function(a,b,d,e,f){return void 0===e&&(e=255),void 0===f&&(f="#"),"#"===f?"#"+((1<<24)+(a<<16)+(b<<8)+d).toString(16).slice(1):"0x"+c.Color.componentToHex(e)+c.Color.componentToHex(a)+c.Color.componentToHex(b)+c.Color.componentToHex(d)},hexToRGB:function(a){var b=c.Color.hexToColor(a);return b?c.Color.getColor32(b.a,b.r,b.g,b.b):void 0},hexToColor:function(a,b){a=a.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(a,b,c,d){return b+b+c+c+d+d});var d=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);if(d){var e=parseInt(d[1],16),f=parseInt(d[2],16),g=parseInt(d[3],16);b?(b.r=e,b.g=f,b.b=g):b=c.Color.createColor(e,f,g)}return b},webToColor:function(a,b){b||(b=c.Color.createColor());var d=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(a);return d&&(b.r=parseInt(d[1],10),b.g=parseInt(d[2],10),b.b=parseInt(d[3],10),b.a=void 0!==d[4]?parseFloat(d[4]):1,c.Color.updateColor(b)),b
-},valueToColor:function(a,b){if(b||(b=c.Color.createColor()),"string"==typeof a)return 0===a.indexOf("rgb")?c.Color.webToColor(a,b):(b.a=1,c.Color.hexToColor(a,b));if("number"==typeof a){var d=c.Color.getRGB(a);return b.r=d.r,b.g=d.g,b.b=d.b,b.a=d.a/255,b}return b},componentToHex:function(a){var b=a.toString(16);return 1==b.length?"0"+b:b},HSVColorWheel:function(a,b){void 0===a&&(a=1),void 0===b&&(b=1);for(var d=[],e=0;359>=e;e++)d.push(c.Color.HSVtoRGB(e/359,a,b));return d},HSLColorWheel:function(a,b){void 0===a&&(a=.5),void 0===b&&(b=.5);for(var d=[],e=0;359>=e;e++)d.push(c.Color.HSLtoRGB(e/359,a,b));return d},interpolateColor:function(a,b,d,e,f){void 0===f&&(f=255);var g=c.Color.getRGB(a),h=c.Color.getRGB(b),i=(h.red-g.red)*e/d+g.red,j=(h.green-g.green)*e/d+g.green,k=(h.blue-g.blue)*e/d+g.blue;return c.Color.getColor32(f,i,j,k)},interpolateColorWithRGB:function(a,b,d,e,f,g){var h=c.Color.getRGB(a),i=(b-h.red)*g/f+h.red,j=(d-h.green)*g/f+h.green,k=(e-h.blue)*g/f+h.blue;return c.Color.getColor(i,j,k)},interpolateRGB:function(a,b,d,e,f,g,h,i){var j=(e-a)*i/h+a,k=(f-b)*i/h+b,l=(g-d)*i/h+d;return c.Color.getColor(j,k,l)},getRandomColor:function(a,b,d){if(void 0===a&&(a=0),void 0===b&&(b=255),void 0===d&&(d=255),b>255||a>b)return c.Color.getColor(255,255,255);var e=a+Math.round(Math.random()*(b-a)),f=a+Math.round(Math.random()*(b-a)),g=a+Math.round(Math.random()*(b-a));return c.Color.getColor32(d,e,f,g)},getRGB:function(a){return a>16777215?{alpha:a>>>24,red:a>>16&255,green:a>>8&255,blue:255&a,a:a>>>24,r:a>>16&255,g:a>>8&255,b:255&a}:{alpha:255,red:a>>16&255,green:a>>8&255,blue:255&a,a:255,r:a>>16&255,g:a>>8&255,b:255&a}},getWebRGB:function(a){if("object"==typeof a)return"rgba("+a.r.toString()+","+a.g.toString()+","+a.b.toString()+","+(a.a/255).toString()+")";var b=c.Color.getRGB(a);return"rgba("+b.r.toString()+","+b.g.toString()+","+b.b.toString()+","+(b.a/255).toString()+")"},getAlpha:function(a){return a>>>24},getAlphaFloat:function(a){return(a>>>24)/255},getRed:function(a){return a>>16&255},getGreen:function(a){return a>>8&255},getBlue:function(a){return 255&a},blendNormal:function(a){return a},blendLighten:function(a,b){return b>a?b:a},blendDarken:function(a,b){return b>a?a:b},blendMultiply:function(a,b){return a*b/255},blendAverage:function(a,b){return(a+b)/2},blendAdd:function(a,b){return Math.min(255,a+b)},blendSubtract:function(a,b){return Math.max(0,a+b-255)},blendDifference:function(a,b){return Math.abs(a-b)},blendNegation:function(a,b){return 255-Math.abs(255-a-b)},blendScreen:function(a,b){return 255-((255-a)*(255-b)>>8)},blendExclusion:function(a,b){return a+b-2*a*b/255},blendOverlay:function(a,b){return 128>b?2*a*b/255:255-2*(255-a)*(255-b)/255},blendSoftLight:function(a,b){return 128>b?2*((a>>1)+64)*(b/255):255-2*(255-((a>>1)+64))*(255-b)/255},blendHardLight:function(a,b){return c.Color.blendOverlay(b,a)},blendColorDodge:function(a,b){return 255===b?b:Math.min(255,(a<<8)/(255-b))},blendColorBurn:function(a,b){return 0===b?b:Math.max(0,255-(255-a<<8)/b)},blendLinearDodge:function(a,b){return c.Color.blendAdd(a,b)},blendLinearBurn:function(a,b){return c.Color.blendSubtract(a,b)},blendLinearLight:function(a,b){return 128>b?c.Color.blendLinearBurn(a,2*b):c.Color.blendLinearDodge(a,2*(b-128))},blendVividLight:function(a,b){return 128>b?c.Color.blendColorBurn(a,2*b):c.Color.blendColorDodge(a,2*(b-128))},blendPinLight:function(a,b){return 128>b?c.Color.blendDarken(a,2*b):c.Color.blendLighten(a,2*(b-128))},blendHardMix:function(a,b){return c.Color.blendVividLight(a,b)<128?0:255},blendReflect:function(a,b){return 255===b?b:Math.min(255,a*a/(255-b))},blendGlow:function(a,b){return c.Color.blendReflect(b,a)},blendPhoenix:function(a,b){return Math.min(a,b)-Math.max(a,b)+255}},c.LinkedList=function(){this.next=null,this.prev=null,this.first=null,this.last=null,this.total=0},c.LinkedList.prototype={add:function(a){return 0===this.total&&null===this.first&&null===this.last?(this.first=a,this.last=a,this.next=a,a.prev=this,this.total++,a):(this.last.next=a,a.prev=this.last,this.last=a,this.total++,a)},reset:function(){this.first=null,this.last=null,this.next=null,this.prev=null,this.total=0},remove:function(a){return 1===this.total?(this.reset(),void(a.next=a.prev=null)):(a===this.first?this.first=this.first.next:a===this.last&&(this.last=this.last.prev),a.prev&&(a.prev.next=a.next),a.next&&(a.next.prev=a.prev),a.next=a.prev=null,null===this.first&&(this.last=null),void this.total--)},callAll:function(a){if(this.first&&this.last){var b=this.first;do b&&b[a]&&b[a].call(b),b=b.next;while(b!=this.last.next)}}},c.LinkedList.prototype.constructor=c.LinkedList,c.Physics=function(a,b){b=b||{},this.game=a,this.config=b,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},c.Physics.ARCADE=0,c.Physics.P2JS=1,c.Physics.NINJA=2,c.Physics.BOX2D=3,c.Physics.CHIPMUNK=4,c.Physics.MATTERJS=5,c.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&this.config.arcade!==!0||!c.Physics.hasOwnProperty("Arcade")||(this.arcade=new c.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&this.config.ninja===!0&&c.Physics.hasOwnProperty("Ninja")&&(this.ninja=new c.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&this.config.p2===!0&&c.Physics.hasOwnProperty("P2")&&(this.p2=new c.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&this.config.box2d===!0&&c.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new c.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&this.config.matter===!0&&c.Physics.hasOwnProperty("Matter")&&(this.matter=new c.Physics.Matter(this.game,this.config))},startSystem:function(a){a===c.Physics.ARCADE?this.arcade=new c.Physics.Arcade(this.game):a===c.Physics.P2JS?null===this.p2?this.p2=new c.Physics.P2(this.game,this.config):this.p2.reset():a===c.Physics.NINJA?this.ninja=new c.Physics.Ninja(this.game):a===c.Physics.BOX2D?null===this.box2d?this.box2d=new c.Physics.Box2D(this.game,this.config):this.box2d.reset():a===c.Physics.MATTERJS&&(null===this.matter?this.matter=new c.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(a,b,d){void 0===b&&(b=c.Physics.ARCADE),void 0===d&&(d=!1),b===c.Physics.ARCADE?this.arcade.enable(a):b===c.Physics.P2JS&&this.p2?this.p2.enable(a,d):b===c.Physics.NINJA&&this.ninja?this.ninja.enableAABB(a):b===c.Physics.BOX2D&&this.box2d?this.box2d.enable(a):b===c.Physics.MATTERJS&&this.matter&&this.matter.enable(a)},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},c.Physics.prototype.constructor=c.Physics,c.Physics.Arcade=function(a){this.game=a,this.gravity=new c.Point,this.bounds=new c.Rectangle(0,0,a.world.width,a.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=c.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new c.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this._total=0,this.setBoundsToWorld()},c.Physics.Arcade.prototype.constructor=c.Physics.Arcade,c.Physics.Arcade.SORT_NONE=0,c.Physics.Arcade.LEFT_RIGHT=1,c.Physics.Arcade.RIGHT_LEFT=2,c.Physics.Arcade.TOP_BOTTOM=3,c.Physics.Arcade.BOTTOM_TOP=4,c.Physics.Arcade.prototype={setBounds:function(a,b,c,d){this.bounds.setTo(a,b,c,d)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(a,b){void 0===b&&(b=!0);var d=1;if(Array.isArray(a))for(d=a.length;d--;)a[d]instanceof c.Group?this.enable(a[d].children,b):(this.enableBody(a[d]),b&&a[d].hasOwnProperty("children")&&a[d].children.length>0&&this.enable(a[d],!0));else a instanceof c.Group?this.enable(a.children,b):(this.enableBody(a),b&&a.hasOwnProperty("children")&&a.children.length>0&&this.enable(a.children,!0))},enableBody:function(a){a.hasOwnProperty("body")&&null===a.body&&(a.body=new c.Physics.Arcade.Body(a),a.parent&&a.parent instanceof c.Group&&a.parent.addToHash(a))},updateMotion:function(a){var b=this.computeVelocity(0,a,a.angularVelocity,a.angularAcceleration,a.angularDrag,a.maxAngular)-a.angularVelocity;a.angularVelocity+=b,a.rotation+=a.angularVelocity*this.game.time.physicsElapsed,a.velocity.x=this.computeVelocity(1,a,a.velocity.x,a.acceleration.x,a.drag.x,a.maxVelocity.x),a.velocity.y=this.computeVelocity(2,a,a.velocity.y,a.acceleration.y,a.drag.y,a.maxVelocity.y)},computeVelocity:function(a,b,c,d,e,f){return void 0===f&&(f=1e4),1===a&&b.allowGravity?c+=(this.gravity.x+b.gravity.x)*this.game.time.physicsElapsed:2===a&&b.allowGravity&&(c+=(this.gravity.y+b.gravity.y)*this.game.time.physicsElapsed),d?c+=d*this.game.time.physicsElapsed:e&&(e*=this.game.time.physicsElapsed,c-e>0?c-=e:0>c+e?c+=e:c=0),c>f?c=f:-f>c&&(c=-f),c},overlap:function(a,b,c,d,e){if(c=c||null,d=d||null,e=e||c,this._total=0,!Array.isArray(a)&&Array.isArray(b))for(var f=0;f<b.length;f++)this.collideHandler(a,b[f],c,d,e,!0);else if(Array.isArray(a)&&!Array.isArray(b))for(var f=0;f<a.length;f++)this.collideHandler(a[f],b,c,d,e,!0);else if(Array.isArray(a)&&Array.isArray(b))for(var f=0;f<a.length;f++)for(var g=0;g<b.length;g++)this.collideHandler(a[f],b[g],c,d,e,!0);else this.collideHandler(a,b,c,d,e,!0);return this._total>0},collide:function(a,b,c,d,e){if(c=c||null,d=d||null,e=e||c,this._total=0,!Array.isArray(a)&&Array.isArray(b))for(var f=0;f<b.length;f++)this.collideHandler(a,b[f],c,d,e,!1);else if(Array.isArray(a)&&!Array.isArray(b))for(var f=0;f<a.length;f++)this.collideHandler(a[f],b,c,d,e,!1);else if(Array.isArray(a)&&Array.isArray(b))for(var f=0;f<a.length;f++)for(var g=0;g<b.length;g++)this.collideHandler(a[f],b[g],c,d,e,!1);else this.collideHandler(a,b,c,d,e,!1);return this._total>0},sortLeftRight:function(a,b){return a.body&&b.body?a.body.x-b.body.x:0},sortRightLeft:function(a,b){return a.body&&b.body?b.body.x-a.body.x:0},sortTopBottom:function(a,b){return a.body&&b.body?a.body.y-b.body.y:0},sortBottomTop:function(a,b){return a.body&&b.body?b.body.y-a.body.y:0},sort:function(a,b){null!==a.physicsSortDirection?b=a.physicsSortDirection:void 0===b&&(b=this.sortDirection),b===c.Physics.Arcade.LEFT_RIGHT?a.hash.sort(this.sortLeftRight):b===c.Physics.Arcade.RIGHT_LEFT?a.hash.sort(this.sortRightLeft):b===c.Physics.Arcade.TOP_BOTTOM?a.hash.sort(this.sortTopBottom):b===c.Physics.Arcade.BOTTOM_TOP&&a.hash.sort(this.sortBottomTop)},collideHandler:function(a,b,d,e,f,g){return void 0===b&&a.physicsType===c.GROUP?(this.sort(a),void this.collideGroupVsSelf(a,d,e,f,g)):void(a&&b&&a.exists&&b.exists&&(this.sortDirection!==c.Physics.Arcade.SORT_NONE&&(a.physicsType===c.GROUP&&this.sort(a),b.physicsType===c.GROUP&&this.sort(b)),a.physicsType===c.SPRITE?b.physicsType===c.SPRITE?this.collideSpriteVsSprite(a,b,d,e,f,g):b.physicsType===c.GROUP?this.collideSpriteVsGroup(a,b,d,e,f,g):b.physicsType===c.TILEMAPLAYER&&this.collideSpriteVsTilemapLayer(a,b,d,e,f,g):a.physicsType===c.GROUP?b.physicsType===c.SPRITE?this.collideSpriteVsGroup(b,a,d,e,f,g):b.physicsType===c.GROUP?this.collideGroupVsGroup(a,b,d,e,f,g):b.physicsType===c.TILEMAPLAYER&&this.collideGroupVsTilemapLayer(a,b,d,e,f,g):a.physicsType===c.TILEMAPLAYER&&(b.physicsType===c.SPRITE?this.collideSpriteVsTilemapLayer(b,a,d,e,f,g):b.physicsType===c.GROUP&&this.collideGroupVsTilemapLayer(b,a,d,e,f,g))))},collideSpriteVsSprite:function(a,b,c,d,e,f){return a.body&&b.body?(this.separate(a.body,b.body,d,e,f)&&(c&&c.call(e,a,b),this._total++),!0):!1},collideSpriteVsGroup:function(a,b,d,e,f,g){if(0!==b.length&&a.body){var h;if(this.skipQuadTree||a.body.skipQuadTree){for(var i=0;i<b.hash.length;i++)if(b.hash[i]&&b.hash[i].exists&&b.hash[i].body){if(h=b.hash[i].body,this.sortDirection===c.Physics.Arcade.LEFT_RIGHT){if(a.body.right<h.x)break;if(h.right<a.body.x)continue}else if(this.sortDirection===c.Physics.Arcade.RIGHT_LEFT){if(a.body.x>h.right)break;if(h.x>a.body.right)continue}else if(this.sortDirection===c.Physics.Arcade.TOP_BOTTOM){if(a.body.bottom<h.y)break;if(h.bottom<a.body.y)continue}else if(this.sortDirection===c.Physics.Arcade.BOTTOM_TOP){if(a.body.y>h.bottom)break;if(h.y>a.body.bottom)continue}this.collideSpriteVsSprite(a,b.hash[i],d,e,f,g)}}else{this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(b);for(var j=this.quadTree.retrieve(a),i=0;i<j.length;i++)this.separate(a.body,j[i],e,f,g)&&(d&&d.call(f,a,j[i].sprite),this._total++)}}},collideGroupVsSelf:function(a,b,d,e,f){if(0!==a.length)for(var g=0;g<a.hash.length;g++)if(a.hash[g]&&a.hash[g].exists&&a.hash[g].body)for(var h=a.hash[g],i=g+1;i<a.hash.length;i++)if(a.hash[i]&&a.hash[i].exists&&a.hash[i].body){var j=a.hash[i];if(this.sortDirection===c.Physics.Arcade.LEFT_RIGHT){if(h.body.right<j.body.x)break;if(j.body.right<h.body.x)continue}else if(this.sortDirection===c.Physics.Arcade.RIGHT_LEFT){if(h.body.x>j.body.right)continue;if(j.body.x>h.body.right)break}else if(this.sortDirection===c.Physics.Arcade.TOP_BOTTOM){if(h.body.bottom<j.body.y)continue;if(j.body.bottom<h.body.y)break}else if(this.sortDirection===c.Physics.Arcade.BOTTOM_TOP){if(h.body.y>j.body.bottom)continue;if(j.body.y>h.body.bottom)break}this.collideSpriteVsSprite(h,j,b,d,e,f)}},collideGroupVsGroup:function(a,b,d,e,f,g){if(0!==a.length&&0!==b.length)for(var h=0;h<a.children.length;h++)a.children[h].exists&&(a.children[h].physicsType===c.GROUP?this.collideGroupVsGroup(a.children[h],b,d,e,f,g):this.collideSpriteVsGroup(a.children[h],b,d,e,f,g))},separate:function(a,b,c,d,e){if(!a.enable||!b.enable||!this.intersects(a,b))return!1;if(c&&c.call(d,a.sprite,b.sprite)===!1)return!1;var f=!1;return f=this.forceX||Math.abs(this.gravity.y+a.gravity.y)<Math.abs(this.gravity.x+a.gravity.x)?this.separateX(a,b,e)||this.separateY(a,b,e):this.separateY(a,b,e)||this.separateX(a,b,e),e?!0:f},intersects:function(a,b){return a.right<=b.position.x?!1:a.bottom<=b.position.y?!1:a.position.x>=b.right?!1:a.position.y>=b.bottom?!1:!0},separateX:function(a,b,c){if(a.immovable&&b.immovable)return!1;var d=0;if(this.intersects(a,b)){var e=a.deltaAbsX()+b.deltaAbsX()+this.OVERLAP_BIAS;if(0===a.deltaX()&&0===b.deltaX()?(a.embedded=!0,b.embedded=!0):a.deltaX()>b.deltaX()?(d=a.right-b.x,d>e||a.checkCollision.right===!1||b.checkCollision.left===!1?d=0:(a.touching.none=!1,a.touching.right=!0,b.touching.none=!1,b.touching.left=!0)):a.deltaX()<b.deltaX()&&(d=a.x-b.width-b.x,-d>e||a.checkCollision.left===!1||b.checkCollision.right===!1?d=0:(a.touching.none=!1,a.touching.left=!0,b.touching.none=!1,b.touching.right=!0)),a.overlapX=d,b.overlapX=d,0!==d){if(c||a.customSeparateX||b.customSeparateX)return!0;var f=a.velocity.x,g=b.velocity.x;if(a.immovable||b.immovable)a.immovable?b.immovable||(b.x+=d,b.velocity.x=f-g*b.bounce.x,a.moves&&(b.y+=(a.y-a.prev.y)*a.friction.y)):(a.x=a.x-d,a.velocity.x=g-f*a.bounce.x,b.moves&&(a.y+=(b.y-b.prev.y)*b.friction.y));else{d*=.5,a.x=a.x-d,b.x+=d;var h=Math.sqrt(g*g*b.mass/a.mass)*(g>0?1:-1),i=Math.sqrt(f*f*a.mass/b.mass)*(f>0?1:-1),j=.5*(h+i);h-=j,i-=j,a.velocity.x=j+h*a.bounce.x,b.velocity.x=j+i*b.bounce.x}return!0}}return!1},separateY:function(a,b,c){if(a.immovable&&b.immovable)return!1;var d=0;if(this.intersects(a,b)){var e=a.deltaAbsY()+b.deltaAbsY()+this.OVERLAP_BIAS;if(0===a.deltaY()&&0===b.deltaY()?(a.embedded=!0,b.embedded=!0):a.deltaY()>b.deltaY()?(d=a.bottom-b.y,d>e||a.checkCollision.down===!1||b.checkCollision.up===!1?d=0:(a.touching.none=!1,a.touching.down=!0,b.touching.none=!1,b.touching.up=!0)):a.deltaY()<b.deltaY()&&(d=a.y-b.bottom,-d>e||a.checkCollision.up===!1||b.checkCollision.down===!1?d=0:(a.touching.none=!1,a.touching.up=!0,b.touching.none=!1,b.touching.down=!0)),a.overlapY=d,b.overlapY=d,0!==d){if(c||a.customSeparateY||b.customSeparateY)return!0;var f=a.velocity.y,g=b.velocity.y;if(a.immovable||b.immovable)a.immovable?b.immovable||(b.y+=d,b.velocity.y=f-g*b.bounce.y,a.moves&&(b.x+=(a.x-a.prev.x)*a.friction.x)):(a.y=a.y-d,a.velocity.y=g-f*a.bounce.y,b.moves&&(a.x+=(b.x-b.prev.x)*b.friction.x));else{d*=.5,a.y=a.y-d,b.y+=d;var h=Math.sqrt(g*g*b.mass/a.mass)*(g>0?1:-1),i=Math.sqrt(f*f*a.mass/b.mass)*(f>0?1:-1),j=.5*(h+i);h-=j,i-=j,a.velocity.y=j+h*a.bounce.y,b.velocity.y=j+i*b.bounce.y}return!0}}return!1},getObjectsUnderPointer:function(a,b,c,d){return 0!==b.length&&a.exists?this.getObjectsAtLocation(a.x,a.y,b,c,d,a):void 0},getObjectsAtLocation:function(a,b,d,e,f,g){this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(d);for(var h=new c.Rectangle(a,b,1,1),i=[],j=this.quadTree.retrieve(h),k=0;k<j.length;k++)j[k].hitTest(a,b)&&(e&&e.call(f,g,j[k].sprite),i.push(j[k].sprite));return i},moveToObject:function(a,b,c,d){void 0===c&&(c=60),void 0===d&&(d=0);var e=Math.atan2(b.y-a.y,b.x-a.x);return d>0&&(c=this.distanceBetween(a,b)/(d/1e3)),a.body.velocity.x=Math.cos(e)*c,a.body.velocity.y=Math.sin(e)*c,e},moveToPointer:function(a,b,c,d){void 0===b&&(b=60),c=c||this.game.input.activePointer,void 0===d&&(d=0);var e=this.angleToPointer(a,c);return d>0&&(b=this.distanceToPointer(a,c)/(d/1e3)),a.body.velocity.x=Math.cos(e)*b,a.body.velocity.y=Math.sin(e)*b,e},moveToXY:function(a,b,c,d,e){void 0===d&&(d=60),void 0===e&&(e=0);var f=Math.atan2(c-a.y,b-a.x);return e>0&&(d=this.distanceToXY(a,b,c)/(e/1e3)),a.body.velocity.x=Math.cos(f)*d,a.body.velocity.y=Math.sin(f)*d,f},velocityFromAngle:function(a,b,d){return void 0===b&&(b=60),d=d||new c.Point,d.setTo(Math.cos(this.game.math.degToRad(a))*b,Math.sin(this.game.math.degToRad(a))*b)},velocityFromRotation:function(a,b,d){return void 0===b&&(b=60),d=d||new c.Point,d.setTo(Math.cos(a)*b,Math.sin(a)*b)},accelerationFromRotation:function(a,b,d){return void 0===b&&(b=60),d=d||new c.Point,d.setTo(Math.cos(a)*b,Math.sin(a)*b)},accelerateToObject:function(a,b,c,d,e){void 0===c&&(c=60),void 0===d&&(d=1e3),void 0===e&&(e=1e3);var f=this.angleBetween(a,b);return a.body.acceleration.setTo(Math.cos(f)*c,Math.sin(f)*c),a.body.maxVelocity.setTo(d,e),f},accelerateToPointer:function(a,b,c,d,e){void 0===c&&(c=60),void 0===b&&(b=this.game.input.activePointer),void 0===d&&(d=1e3),void 0===e&&(e=1e3);var f=this.angleToPointer(a,b);return a.body.acceleration.setTo(Math.cos(f)*c,Math.sin(f)*c),a.body.maxVelocity.setTo(d,e),f},accelerateToXY:function(a,b,c,d,e,f){void 0===d&&(d=60),void 0===e&&(e=1e3),void 0===f&&(f=1e3);var g=this.angleToXY(a,b,c);return a.body.acceleration.setTo(Math.cos(g)*d,Math.sin(g)*d),a.body.maxVelocity.setTo(e,f),g},distanceBetween:function(a,b){var c=a.x-b.x,d=a.y-b.y;return Math.sqrt(c*c+d*d)},distanceToXY:function(a,b,c){var d=a.x-b,e=a.y-c;return Math.sqrt(d*d+e*e)},distanceToPointer:function(a,b){b=b||this.game.input.activePointer;var c=a.x-b.worldX,d=a.y-b.worldY;return Math.sqrt(c*c+d*d)},angleBetween:function(a,b){var c=b.x-a.x,d=b.y-a.y;return Math.atan2(d,c)},angleToXY:function(a,b,c){var d=b-a.x,e=c-a.y;return Math.atan2(e,d)},angleToPointer:function(a,b){b=b||this.game.input.activePointer;var c=b.worldX-a.x,d=b.worldY-a.y;return Math.atan2(d,c)}},c.Physics.Arcade.Body=function(a){this.sprite=a,this.game=a.game,this.type=c.Physics.ARCADE,this.enable=!0,this.offset=new c.Point,this.position=new c.Point(a.x,a.y),this.prev=new c.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=a.rotation,this.preRotation=a.rotation,this.width=a.width,this.height=a.height,this.sourceWidth=a.width,this.sourceHeight=a.height,a.texture&&(this.sourceWidth=a.texture.frame.width,this.sourceHeight=a.texture.frame.height),this.halfWidth=Math.abs(a.width/2),this.halfHeight=Math.abs(a.height/2),this.center=new c.Point(a.x+this.halfWidth,a.y+this.halfHeight),this.velocity=new c.Point,this.newVelocity=new c.Point(0,0),this.deltaMax=new c.Point(0,0),this.acceleration=new c.Point,this.drag=new c.Point,this.allowGravity=!0,this.gravity=new c.Point(0,0),this.bounce=new c.Point,this.maxVelocity=new c.Point(1e4,1e4),this.friction=new c.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=c.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,any:!0,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={up:!1,down:!1,left:!1,right:!1},this.tilePadding=new c.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this._reset=!0,this._sx=a.scale.x,this._sy=a.scale.y,this._dx=0,this._dy=0},c.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var a=this.sprite.getBounds();a.ceilAll(),(a.width!==this.width||a.height!==this.height)&&(this.width=a.width,this.height=a.height,this._reset=!0)}else{var b=Math.abs(this.sprite.scale.x),c=Math.abs(this.sprite.scale.y);(b!==this._sx||c!==this._sy)&&(this.width=this.sourceWidth*b,this.height=this.sourceHeight*c,this._sx=b,this._sy=c,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight))},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,this.wasTouching.none=this.touching.none,this.wasTouching.up=this.touching.up,this.wasTouching.down=this.touching.down,this.wasTouching.left=this.touching.left,this.wasTouching.right=this.touching.right,this.touching.none=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.width+this.offset.x,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.height+this.offset.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),this.moves&&(this.game.physics.arcade.updateMotion(this),this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed),this.position.x+=this.newVelocity.x,this.position.y+=this.newVelocity.y,(this.position.x!==this.prev.x||this.position.y!==this.prev.y)&&(this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.angle=Math.atan2(this.velocity.y,this.velocity.x)),this.collideWorldBounds&&this.checkWorldBounds()),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},postUpdate:function(){this.enable&&this.dirty&&(this.dirty=!1,this.deltaX()<0?this.facing=c.LEFT:this.deltaX()>0&&(this.facing=c.RIGHT),this.deltaY()<0?this.facing=c.UP:this.deltaY()>0&&(this.facing=c.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof c.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null},checkWorldBounds:function(){var a=this.position,b=this.game.physics.arcade.bounds,c=this.game.physics.arcade.checkCollision;a.x<b.x&&c.left?(a.x=b.x,this.velocity.x*=-this.bounce.x,this.blocked.left=!0):this.right>b.right&&c.right&&(a.x=b.right-this.width,this.velocity.x*=-this.bounce.x,this.blocked.right=!0),a.y<b.y&&c.up?(a.y=b.y,this.velocity.y*=-this.bounce.y,this.blocked.up=!0):this.bottom>b.bottom&&c.down&&(a.y=b.bottom-this.height,this.velocity.y*=-this.bounce.y,this.blocked.down=!0)},setSize:function(a,b,c,d){void 0===c&&(c=this.offset.x),void 0===d&&(d=this.offset.y),this.sourceWidth=a,this.sourceHeight=b,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(c,d),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(a,b){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this.position.x=a-this.sprite.anchor.x*this.width+this.offset.x,this.position.y=b-this.sprite.anchor.y*this.height+this.offset.y,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this._sx=this.sprite.scale.x,this._sy=this.sprite.scale.y,this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},hitTest:function(a,b){return c.Rectangle.contains(this,a,b)},onFloor:function(){return this.blocked.down},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation}},Object.defineProperty(c.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(c.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(c.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(a){this.position.x=a}}),Object.defineProperty(c.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(a){this.position.y=a}}),c.Physics.Arcade.Body.render=function(a,b,c,d){void 0===d&&(d=!0),c=c||"rgba(0,255,0,0.4)",d?(a.fillStyle=c,a.fillRect(b.position.x-b.game.camera.x,b.position.y-b.game.camera.y,b.width,b.height)):(a.strokeStyle=c,a.strokeRect(b.position.x-b.game.camera.x,b.position.y-b.game.camera.y,b.width,b.height))},c.Physics.Arcade.Body.renderBodyInfo=function(a,b){a.line("x: "+b.x.toFixed(2),"y: "+b.y.toFixed(2),"width: "+b.width,"height: "+b.height),a.line("velocity x: "+b.velocity.x.toFixed(2),"y: "+b.velocity.y.toFixed(2),"deltaX: "+b._dx.toFixed(2),"deltaY: "+b._dy.toFixed(2)),a.line("acceleration x: "+b.acceleration.x.toFixed(2),"y: "+b.acceleration.y.toFixed(2),"speed: "+b.speed.toFixed(2),"angle: "+b.angle.toFixed(2)),a.line("gravity x: "+b.gravity.x,"y: "+b.gravity.y,"bounce x: "+b.bounce.x.toFixed(2),"y: "+b.bounce.y.toFixed(2)),a.line("touching left: "+b.touching.left,"right: "+b.touching.right,"up: "+b.touching.up,"down: "+b.touching.down),a.line("blocked left: "+b.blocked.left,"right: "+b.blocked.right,"up: "+b.blocked.up,"down: "+b.blocked.down)},c.Physics.Arcade.Body.prototype.constructor=c.Physics.Arcade.Body,c.Physics.Arcade.TilemapCollision=function(){},c.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(a,b,c,d,e,f){if(a.body){var g=b.getTiles(a.body.position.x-a.body.tilePadding.x,a.body.position.y-a.body.tilePadding.y,a.body.width+a.body.tilePadding.x,a.body.height+a.body.tilePadding.y,!1,!1);if(0!==g.length)for(var h=0;h<g.length;h++)d?d.call(e,a,g[h])&&this.separateTile(h,a.body,g[h],f)&&(this._total++,c&&c.call(e,a,g[h])):this.separateTile(h,a.body,g[h],f)&&(this._total++,c&&c.call(e,a,g[h]))}},collideGroupVsTilemapLayer:function(a,b,c,d,e,f){if(0!==a.length)for(var g=0;g<a.children.length;g++)a.children[g].exists&&this.collideSpriteVsTilemapLayer(a.children[g],b,c,d,e,f)},separateTile:function(a,b,c,d){if(!b.enable)return!1;if(!c.intersects(b.position.x,b.position.y,b.right,b.bottom))return!1;if(d)return!0;if(c.collisionCallback&&!c.collisionCallback.call(c.collisionCallbackContext,b.sprite,c))return!1;if(c.layer.callbacks[c.index]&&!c.layer.callbacks[c.index].callback.call(c.layer.callbacks[c.index].callbackContext,b.sprite,c))return!1;if(!(c.faceLeft||c.faceRight||c.faceTop||c.faceBottom))return!1;var e=0,f=0,g=0,h=1;if(b.deltaAbsX()>b.deltaAbsY()?g=-1:b.deltaAbsX()<b.deltaAbsY()&&(h=-1),0!==b.deltaX()&&0!==b.deltaY()&&(c.faceLeft||c.faceRight)&&(c.faceTop||c.faceBottom)&&(g=Math.min(Math.abs(b.position.x-c.right),Math.abs(b.right-c.left)),h=Math.min(Math.abs(b.position.y-c.bottom),Math.abs(b.bottom-c.top))),h>g){if((c.faceLeft||c.faceRight)&&(e=this.tileCheckX(b,c),0!==e&&!c.intersects(b.position.x,b.position.y,b.right,b.bottom)))return!0;(c.faceTop||c.faceBottom)&&(f=this.tileCheckY(b,c))}else{if((c.faceTop||c.faceBottom)&&(f=this.tileCheckY(b,c),0!==f&&!c.intersects(b.position.x,b.position.y,b.right,b.bottom)))return!0;(c.faceLeft||c.faceRight)&&(e=this.tileCheckX(b,c))}return 0!==e||0!==f},tileCheckX:function(a,b){var c=0;return a.deltaX()<0&&!a.blocked.left&&b.collideRight&&a.checkCollision.left?b.faceRight&&a.x<b.right&&(c=a.x-b.right,c<-this.TILE_BIAS&&(c=0)):a.deltaX()>0&&!a.blocked.right&&b.collideLeft&&a.checkCollision.right&&b.faceLeft&&a.right>b.left&&(c=a.right-b.left,c>this.TILE_BIAS&&(c=0)),0!==c&&(a.customSeparateX?a.overlapX=c:this.processTileSeparationX(a,c)),c},tileCheckY:function(a,b){var c=0;return a.deltaY()<0&&!a.blocked.up&&b.collideDown&&a.checkCollision.up?b.faceBottom&&a.y<b.bottom&&(c=a.y-b.bottom,c<-this.TILE_BIAS&&(c=0)):a.deltaY()>0&&!a.blocked.down&&b.collideUp&&a.checkCollision.down&&b.faceTop&&a.bottom>b.top&&(c=a.bottom-b.top,c>this.TILE_BIAS&&(c=0)),0!==c&&(a.customSeparateY?a.overlapY=c:this.processTileSeparationY(a,c)),c},processTileSeparationX:function(a,b){0>b?a.blocked.left=!0:b>0&&(a.blocked.right=!0),a.position.x-=b,a.velocity.x=0===a.bounce.x?0:-a.velocity.x*a.bounce.x},processTileSeparationY:function(a,b){0>b?a.blocked.up=!0:b>0&&(a.blocked.down=!0),a.position.y-=b,a.velocity.y=0===a.bounce.y?0:-a.velocity.y*a.bounce.y}},c.Utils.mixinPrototype(c.Physics.Arcade.prototype,c.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,c.Physics.P2=function(a,b){this.game=a,void 0===b?b={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(b.hasOwnProperty("gravity")||(b.gravity=[0,0]),b.hasOwnProperty("broadphase")||(b.broadphase=new p2.SAPBroadphase)),this.config=b,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new c.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new c.Signal,this.onBodyRemoved=new c.Signal,this.onSpringAdded=new c.Signal,this.onSpringRemoved=new c.Signal,this.onConstraintAdded=new c.Signal,this.onConstraintRemoved=new c.Signal,this.onContactMaterialAdded=new c.Signal,this.onContactMaterialRemoved=new c.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new c.Signal,this.onEndContact=new c.Signal,b.hasOwnProperty("mpx")&&b.hasOwnProperty("pxm")&&b.hasOwnProperty("mpxi")&&b.hasOwnProperty("pxmi")&&(this.mpx=b.mpx,this.mpxi=b.mpxi,this.pxm=b.pxm,this.pxmi=b.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new c.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new c.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new c.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)
-},c.Physics.P2.prototype={removeBodyNextStep:function(a){this._toRemove.push(a)},preUpdate:function(){for(var a=this._toRemove.length;a--;)this.removeBody(this._toRemove[a]);this._toRemove.length=0},enable:function(a,b,d){void 0===b&&(b=!1),void 0===d&&(d=!0);var e=1;if(Array.isArray(a))for(e=a.length;e--;)a[e]instanceof c.Group?this.enable(a[e].children,b,d):(this.enableBody(a[e],b),d&&a[e].hasOwnProperty("children")&&a[e].children.length>0&&this.enable(a[e],b,!0));else a instanceof c.Group?this.enable(a.children,b,d):(this.enableBody(a,b),d&&a.hasOwnProperty("children")&&a.children.length>0&&this.enable(a.children,b,!0))},enableBody:function(a,b){a.hasOwnProperty("body")&&null===a.body&&(a.body=new c.Physics.P2.Body(this.game,a,a.x,a.y,1),a.body.debug=b,"undefined"!=typeof a.anchor&&a.anchor.set(.5))},setImpactEvents:function(a){a?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(a,b){this.postBroadphaseCallback=a,this.callbackContext=b,null!==a?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(a){if(this.postBroadphaseCallback&&0!==a.pairs.length)for(var b=a.pairs.length-2;b>=0;b-=2)a.pairs[b].parent&&a.pairs[b+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,a.pairs[b].parent,a.pairs[b+1].parent)&&a.pairs.splice(b,2)},impactHandler:function(a){if(a.bodyA.parent&&a.bodyB.parent){var b=a.bodyA.parent,c=a.bodyB.parent;b._bodyCallbacks[a.bodyB.id]&&b._bodyCallbacks[a.bodyB.id].call(b._bodyCallbackContext[a.bodyB.id],b,c,a.shapeA,a.shapeB),c._bodyCallbacks[a.bodyA.id]&&c._bodyCallbacks[a.bodyA.id].call(c._bodyCallbackContext[a.bodyA.id],c,b,a.shapeB,a.shapeA),b._groupCallbacks[a.shapeB.collisionGroup]&&b._groupCallbacks[a.shapeB.collisionGroup].call(b._groupCallbackContext[a.shapeB.collisionGroup],b,c,a.shapeA,a.shapeB),c._groupCallbacks[a.shapeA.collisionGroup]&&c._groupCallbacks[a.shapeA.collisionGroup].call(c._groupCallbackContext[a.shapeA.collisionGroup],c,b,a.shapeB,a.shapeA)}},beginContactHandler:function(a){a.bodyA&&a.bodyB&&(this.onBeginContact.dispatch(a.bodyA,a.bodyB,a.shapeA,a.shapeB,a.contactEquations),a.bodyA.parent&&a.bodyA.parent.onBeginContact.dispatch(a.bodyB.parent,a.bodyB,a.shapeA,a.shapeB,a.contactEquations),a.bodyB.parent&&a.bodyB.parent.onBeginContact.dispatch(a.bodyA.parent,a.bodyA,a.shapeB,a.shapeA,a.contactEquations))},endContactHandler:function(a){a.bodyA&&a.bodyB&&(this.onEndContact.dispatch(a.bodyA,a.bodyB,a.shapeA,a.shapeB),a.bodyA.parent&&a.bodyA.parent.onEndContact.dispatch(a.bodyB.parent,a.bodyB,a.shapeA,a.shapeB),a.bodyB.parent&&a.bodyB.parent.onEndContact.dispatch(a.bodyA.parent,a.bodyA,a.shapeB,a.shapeA))},setBoundsToWorld:function(a,b,c,d,e){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,a,b,c,d,e)},setWorldMaterial:function(a,b,c,d,e){void 0===b&&(b=!0),void 0===c&&(c=!0),void 0===d&&(d=!0),void 0===e&&(e=!0),b&&this.walls.left&&(this.walls.left.shapes[0].material=a),c&&this.walls.right&&(this.walls.right.shapes[0].material=a),d&&this.walls.top&&(this.walls.top.shapes[0].material=a),e&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=a)},updateBoundsCollisionGroup:function(a){var b=this.everythingCollisionGroup.mask;void 0===a&&(b=this.boundsCollisionGroup.mask),this.walls.left&&(this.walls.left.shapes[0].collisionGroup=b),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=b),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=b),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=b)},setBounds:function(a,b,c,d,e,f,g,h,i){void 0===e&&(e=this._boundsLeft),void 0===f&&(f=this._boundsRight),void 0===g&&(g=this._boundsTop),void 0===h&&(h=this._boundsBottom),void 0===i&&(i=this._boundsOwnGroup),this.walls.left&&this.world.removeBody(this.walls.left),this.walls.right&&this.world.removeBody(this.walls.right),this.walls.top&&this.world.removeBody(this.walls.top),this.walls.bottom&&this.world.removeBody(this.walls.bottom),e&&(this.walls.left=new p2.Body({mass:0,position:[this.pxmi(a),this.pxmi(b)],angle:1.5707963267948966}),this.walls.left.addShape(new p2.Plane),i&&(this.walls.left.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.left)),f&&(this.walls.right=new p2.Body({mass:0,position:[this.pxmi(a+c),this.pxmi(b)],angle:-1.5707963267948966}),this.walls.right.addShape(new p2.Plane),i&&(this.walls.right.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.right)),g&&(this.walls.top=new p2.Body({mass:0,position:[this.pxmi(a),this.pxmi(b)],angle:-3.141592653589793}),this.walls.top.addShape(new p2.Plane),i&&(this.walls.top.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.top)),h&&(this.walls.bottom=new p2.Body({mass:0,position:[this.pxmi(a),this.pxmi(b+d)]}),this.walls.bottom.addShape(new p2.Plane),i&&(this.walls.bottom.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.bottom)),this._boundsLeft=e,this._boundsRight=f,this._boundsTop=g,this._boundsBottom=h,this._boundsOwnGroup=i},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||this.world.step(this.useElapsedTime?this.game.time.physicsElapsed:this.frameRate)},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new c.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new c.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new c.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var a=this.world.constraints,b=a.length-1;b>=0;b--)this.world.removeConstraint(a[b]);for(var c=this.world.bodies,b=c.length-1;b>=0;b--)this.world.removeBody(c[b]);for(var d=this.world.springs,b=d.length-1;b>=0;b--)this.world.removeSpring(d[b]);for(var e=this.world.contactMaterials,b=e.length-1;b>=0;b--)this.world.removeContactMaterial(e[b]);this.world.off("beginContact",this.beginContactHandler,this),this.world.off("endContact",this.endContactHandler,this),this.postBroadphaseCallback=null,this.callbackContext=null,this.impactCallback=null,this.collisionGroups=[],this._toRemove=[],this.boundsCollidesWith=[]},destroy:function(){this.clear(),this.game=null},addBody:function(a){return a.data.world?!1:(this.world.addBody(a.data),this.onBodyAdded.dispatch(a),!0)},removeBody:function(a){return a.data.world==this.world&&(this.world.removeBody(a.data),this.onBodyRemoved.dispatch(a)),a},addSpring:function(a){return this.world.addSpring(a instanceof c.Physics.P2.Spring||a instanceof c.Physics.P2.RotationalSpring?a.data:a),this.onSpringAdded.dispatch(a),a},removeSpring:function(a){return this.world.removeSpring(a instanceof c.Physics.P2.Spring||a instanceof c.Physics.P2.RotationalSpring?a.data:a),this.onSpringRemoved.dispatch(a),a},createDistanceConstraint:function(a,b,d,e,f,g){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.DistanceConstraint(this,a,b,d,e,f,g)):void console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(a,b,d,e){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.GearConstraint(this,a,b,d,e)):void console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(a,b,d,e,f,g){return a=this.getBody(a),d=this.getBody(d),a&&d?this.addConstraint(new c.Physics.P2.RevoluteConstraint(this,a,b,d,e,f,g)):void console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(a,b,d,e,f){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.LockConstraint(this,a,b,d,e,f)):void console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(a,b,d,e,f,g,h){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.PrismaticConstraint(this,a,b,d,e,f,g,h)):void console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(a){return this.world.addConstraint(a),this.onConstraintAdded.dispatch(a),a},removeConstraint:function(a){return this.world.removeConstraint(a),this.onConstraintRemoved.dispatch(a),a},addContactMaterial:function(a){return this.world.addContactMaterial(a),this.onContactMaterialAdded.dispatch(a),a},removeContactMaterial:function(a){return this.world.removeContactMaterial(a),this.onContactMaterialRemoved.dispatch(a),a},getContactMaterial:function(a,b){return this.world.getContactMaterial(a,b)},setMaterial:function(a,b){for(var c=b.length;c--;)b[c].setMaterial(a)},createMaterial:function(a,b){a=a||"";var d=new c.Physics.P2.Material(a);return this.materials.push(d),"undefined"!=typeof b&&b.setMaterial(d),d},createContactMaterial:function(a,b,d){void 0===a&&(a=this.createMaterial()),void 0===b&&(b=this.createMaterial());var e=new c.Physics.P2.ContactMaterial(a,b,d);return this.addContactMaterial(e)},getBodies:function(){for(var a=[],b=this.world.bodies.length;b--;)a.push(this.world.bodies[b].parent);return a},getBody:function(a){return a instanceof p2.Body?a:a instanceof c.Physics.P2.Body?a.data:a.body&&a.body.type===c.Physics.P2JS?a.body.data:null},getSprings:function(){for(var a=[],b=this.world.springs.length;b--;)a.push(this.world.springs[b].parent);return a},getConstraints:function(){for(var a=[],b=this.world.constraints.length;b--;)a.push(this.world.constraints[b]);return a},hitTest:function(a,b,d,e){void 0===b&&(b=this.world.bodies),void 0===d&&(d=5),void 0===e&&(e=!1);for(var f=[this.pxmi(a.x),this.pxmi(a.y)],g=[],h=b.length;h--;)b[h]instanceof c.Physics.P2.Body&&(!e||b[h].data.type!==p2.Body.STATIC)?g.push(b[h].data):b[h]instanceof p2.Body&&b[h].parent&&(!e||b[h].type!==p2.Body.STATIC)?g.push(b[h]):b[h]instanceof c.Sprite&&b[h].hasOwnProperty("body")&&(!e||b[h].body.data.type!==p2.Body.STATIC)&&g.push(b[h].body.data);return this.world.hitTest(f,g,d)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(a){var b=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|b),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|b),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|b),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|b),this._collisionGroupID++;var d=new c.Physics.P2.CollisionGroup(b);return this.collisionGroups.push(d),a&&this.setCollisionGroup(a,d),d},setCollisionGroup:function(a,b){if(a instanceof c.Group)for(var d=0;d<a.total;d++)a.children[d].body&&a.children[d].body.type===c.Physics.P2JS&&a.children[d].body.setCollisionGroup(b);else a.body.setCollisionGroup(b)},createSpring:function(a,b,d,e,f,g,h,i,j){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addSpring(new c.Physics.P2.Spring(this,a,b,d,e,f,g,h,i,j)):void console.warn("Cannot create Spring, invalid body objects given")},createRotationalSpring:function(a,b,d,e,f){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addSpring(new c.Physics.P2.RotationalSpring(this,a,b,d,e,f)):void console.warn("Cannot create Rotational Spring, invalid body objects given")},createBody:function(a,b,d,e,f,g){void 0===e&&(e=!1);var h=new c.Physics.P2.Body(this.game,null,a,b,d);if(g){var i=h.addPolygon(f,g);if(!i)return!1}return e&&this.world.addBody(h.data),h},createParticle:function(a,b,d,e,f,g){void 0===e&&(e=!1);var h=new c.Physics.P2.Body(this.game,null,a,b,d);if(g){var i=h.addPolygon(f,g);if(!i)return!1}return e&&this.world.addBody(h.data),h},convertCollisionObjects:function(a,b,c){void 0===c&&(c=!0);for(var d=[],e=0,f=a.collision[b].length;f>e;e++){var g=a.collision[b][e],h=this.createBody(g.x,g.y,0,c,{},g.polyline);h&&d.push(h)}return d},clearTilemapLayerBodies:function(a,b){b=a.getLayer(b);for(var c=a.layers[b].bodies.length;c--;)a.layers[b].bodies[c].destroy();a.layers[b].bodies.length=0},convertTilemap:function(a,b,c,d){b=a.getLayer(b),void 0===c&&(c=!0),void 0===d&&(d=!0),this.clearTilemapLayerBodies(a,b);for(var e=0,f=0,g=0,h=0,i=a.layers[b].height;i>h;h++){e=0;for(var j=0,k=a.layers[b].width;k>j;j++){var l=a.layers[b].data[h][j];if(l&&l.index>-1&&l.collides)if(d){var m=a.getTileRight(b,j,h);if(0===e&&(f=l.x*l.width,g=l.y*l.height,e=l.width),m&&m.collides)e+=l.width;else{var n=this.createBody(f,g,0,!1);n.addRectangle(e,l.height,e/2,l.height/2,0),c&&this.addBody(n),a.layers[b].bodies.push(n),e=0}}else{var n=this.createBody(l.x*l.width,l.y*l.height,0,!1);n.addRectangle(l.width,l.height,l.width/2,l.height/2,0),c&&this.addBody(n),a.layers[b].bodies.push(n)}}}return a.layers[b].bodies},mpx:function(a){return a*=20},pxm:function(a){return.05*a},mpxi:function(a){return a*=-20},pxmi:function(a){return a*-.05}},Object.defineProperty(c.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(a){this.world.defaultContactMaterial.friction=a}}),Object.defineProperty(c.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(a){this.world.defaultContactMaterial.restitution=a}}),Object.defineProperty(c.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(a){this.world.defaultContactMaterial=a}}),Object.defineProperty(c.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(a){this.world.applySpringForces=a}}),Object.defineProperty(c.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(a){this.world.applyDamping=a}}),Object.defineProperty(c.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(a){this.world.applyGravity=a}}),Object.defineProperty(c.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(a){this.world.solveConstraints=a}}),Object.defineProperty(c.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(c.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(a){this.world.emitImpactEvent=a}}),Object.defineProperty(c.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(a){this.world.sleepMode=a}}),Object.defineProperty(c.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),c.Physics.P2.FixtureList=function(a){Array.isArray(a)||(a=[a]),this.rawList=a,this.init(),this.parse(this.rawList)},c.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(a,b){var c=function(b){b.collisionGroup=a};this.getFixtures(b).forEach(c)},setMask:function(a,b){var c=function(b){b.collisionMask=a};this.getFixtures(b).forEach(c)},setSensor:function(a,b){var c=function(b){b.sensor=a};this.getFixtures(b).forEach(c)},setMaterial:function(a,b){var c=function(b){b.material=a};this.getFixtures(b).forEach(c)},getFixtures:function(a){var b=[];if(a){a instanceof Array||(a=[a]);var c=this;return a.forEach(function(a){c.namedFixtures[a]&&b.push(c.namedFixtures[a])}),this.flatten(b)}return this.allFixtures},getFixtureByKey:function(a){return this.namedFixtures[a]},getGroup:function(a){return this.groupedFixtures[a]},parse:function(){var a,b,c,d;c=this.rawList,d=[];for(a in c)b=c[a],isNaN(a-0)?this.namedFixtures[a]=this.flatten(b):(this.groupedFixtures[a]=this.groupedFixtures[a]||[],this.groupedFixtures[a]=this.groupedFixtures[a].concat(b)),d.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(a){var b,c;return b=[],c=arguments.callee,a.forEach(function(a){return Array.prototype.push.apply(b,Array.isArray(a)?c(a):[a])}),b}},c.Physics.P2.PointProxy=function(a,b){this.world=a,this.destination=b},c.Physics.P2.PointProxy.prototype.constructor=c.Physics.P2.PointProxy,Object.defineProperty(c.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(a){this.destination[0]=this.world.pxm(a)}}),Object.defineProperty(c.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(a){this.destination[1]=this.world.pxm(a)}}),Object.defineProperty(c.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(a){this.destination[0]=a}}),Object.defineProperty(c.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(a){this.destination[1]=a}}),c.Physics.P2.InversePointProxy=function(a,b){this.world=a,this.destination=b},c.Physics.P2.InversePointProxy.prototype.constructor=c.Physics.P2.InversePointProxy,Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(a){this.destination[0]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(a){this.destination[1]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(a){this.destination[0]=-a}}),Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(a){this.destination[1]=-a}}),c.Physics.P2.Body=function(a,b,d,e,f){b=b||null,d=d||0,e=e||0,void 0===f&&(f=1),this.game=a,this.world=a.physics.p2,this.sprite=b,this.type=c.Physics.P2JS,this.offset=new c.Point,this.data=new p2.Body({position:[this.world.pxmi(d),this.world.pxmi(e)],mass:f}),this.data.parent=this,this.velocity=new c.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new c.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new c.Point,this.onBeginContact=new c.Signal,this.onEndContact=new c.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,b&&(this.setRectangleFromSprite(b),b.exists&&this.game.physics.p2.addBody(this))},c.Physics.P2.Body.prototype={createBodyCallback:function(a,b,c){var d=-1;a.id?d=a.id:a.body&&(d=a.body.id),d>-1&&(null===b?(delete this._bodyCallbacks[d],delete this._bodyCallbackContext[d]):(this._bodyCallbacks[d]=b,this._bodyCallbackContext[d]=c))},createGroupCallback:function(a,b,c){null===b?(delete this._groupCallbacks[a.mask],delete this._groupCallbackContext[a.mask]):(this._groupCallbacks[a.mask]=b,this._groupCallbackContext[a.mask]=c)},getCollisionMask:function(){var a=0;this._collideWorldBounds&&(a=this.game.physics.p2.boundsCollisionGroup.mask);for(var b=0;b<this.collidesWith.length;b++)a|=this.collidesWith[b].mask;return a},updateCollisionMask:function(a){var b=this.getCollisionMask();if(void 0===a)for(var c=this.data.shapes.length-1;c>=0;c--)this.data.shapes[c].collisionMask=b;else a.collisionMask=b},setCollisionGroup:function(a,b){var c=this.getCollisionMask();if(void 0===b)for(var d=this.data.shapes.length-1;d>=0;d--)this.data.shapes[d].collisionGroup=a.mask,this.data.shapes[d].collisionMask=c;else b.collisionGroup=a.mask,b.collisionMask=c},clearCollision:function(a,b,c){if(void 0===a&&(a=!0),void 0===b&&(b=!0),void 0===c)for(var d=this.data.shapes.length-1;d>=0;d--)a&&(this.data.shapes[d].collisionGroup=null),b&&(this.data.shapes[d].collisionMask=null);else a&&(c.collisionGroup=null),b&&(c.collisionMask=null);a&&(this.collidesWith.length=0)},collides:function(a,b,c,d){if(Array.isArray(a))for(var e=0;e<a.length;e++)-1===this.collidesWith.indexOf(a[e])&&(this.collidesWith.push(a[e]),b&&this.createGroupCallback(a[e],b,c));else-1===this.collidesWith.indexOf(a)&&(this.collidesWith.push(a),b&&this.createGroupCallback(a,b,c));var f=this.getCollisionMask();if(void 0===d)for(var e=this.data.shapes.length-1;e>=0;e--)this.data.shapes[e].collisionMask=f;else d.collisionMask=f},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(a,b){return this.data.getVelocityAtPoint(a,b)},applyDamping:function(a){this.data.applyDamping(a)},applyImpulse:function(a,b,c){this.data.applyImpulse(a,[this.world.pxmi(b),this.world.pxmi(c)])},applyImpulseLocal:function(a,b,c){this.data.applyImpulseLocal(a,[this.world.pxmi(b),this.world.pxmi(c)])},applyForce:function(a,b,c){this.data.applyForce(a,[this.world.pxmi(b),this.world.pxmi(c)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0,this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0,this.data.angularDamping=0},toLocalFrame:function(a,b){return this.data.toLocalFrame(a,b)},toWorldFrame:function(a,b){return this.data.toWorldFrame(a,b)},rotateLeft:function(a){this.data.angularVelocity=this.world.pxm(-a)},rotateRight:function(a){this.data.angularVelocity=this.world.pxm(a)},moveForward:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.velocity[0]=b*Math.cos(c),this.data.velocity[1]=b*Math.sin(c)},moveBackward:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.velocity[0]=-(b*Math.cos(c)),this.data.velocity[1]=-(b*Math.sin(c))},thrust:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.force[0]+=b*Math.cos(c),this.data.force[1]+=b*Math.sin(c)},reverse:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.force[0]-=b*Math.cos(c),this.data.force[1]-=b*Math.sin(c)},moveLeft:function(a){this.data.velocity[0]=this.world.pxmi(-a)},moveRight:function(a){this.data.velocity[0]=this.world.pxmi(a)},moveUp:function(a){this.data.velocity[1]=this.world.pxmi(-a)},moveDown:function(a){this.data.velocity[1]=this.world.pxmi(a)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0]),this.sprite.y=this.world.mpxi(this.data.position[1]),this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(a,b,c,d){void 0===c&&(c=!1),void 0===d&&(d=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),c&&this.setZeroDamping(),d&&(this.mass=1),this.x=a,this.y=b},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var a=0;a<this.game.physics.p2._toRemove.length;a++)this.game.physics.p2._toRemove[a]===this&&this.game.physics.p2._toRemove.splice(a,1);this.data.world!==this.game.physics.p2.world&&this.game.physics.p2.addBody(this)},removeFromWorld:function(){this.data.world===this.game.physics.p2.world&&this.game.physics.p2.removeBodyNextStep(this)},destroy:function(){this.removeFromWorld(),this.clearShapes(),this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this.debugBody&&this.debugBody.destroy(!0,!0),this.debugBody=null,this.sprite&&(this.sprite.body=null,this.sprite=null)},clearShapes:function(){for(var a=this.data.shapes.length;a--;)this.data.removeShape(this.data.shapes[a]);this.shapeChanged()},addShape:function(a,b,c,d){return void 0===b&&(b=0),void 0===c&&(c=0),void 0===d&&(d=0),this.data.addShape(a,[this.world.pxmi(b),this.world.pxmi(c)],d),this.shapeChanged(),a},addCircle:function(a,b,c,d){var e=new p2.Circle({radius:this.world.pxm(a)});return this.addShape(e,b,c,d)},addRectangle:function(a,b,c,d,e){var f=new p2.Box({width:this.world.pxm(a),height:this.world.pxm(b)});return this.addShape(f,c,d,e)},addPlane:function(a,b,c){var d=new p2.Plane;return this.addShape(d,a,b,c)},addParticle:function(a,b,c){var d=new p2.Particle;return this.addShape(d,a,b,c)},addLine:function(a,b,c,d){var e=new p2.Line({length:this.world.pxm(a)});return this.addShape(e,b,c,d)},addCapsule:function(a,b,c,d,e){var f=new p2.Capsule({length:this.world.pxm(a),radius:this.world.pxm(b)});return this.addShape(f,c,d,e)},addPolygon:function(a,b){a=a||{},Array.isArray(b)||(b=Array.prototype.slice.call(arguments,1));var c=[];if(1===b.length&&Array.isArray(b[0]))c=b[0].slice(0);else if(Array.isArray(b[0]))c=b.slice();else if("number"==typeof b[0])for(var d=0,e=b.length;e>d;d+=2)c.push([b[d],b[d+1]]);var f=c.length-1;c[f][0]===c[0][0]&&c[f][1]===c[0][1]&&c.pop();for(var g=0;g<c.length;g++)c[g][0]=this.world.pxmi(c[g][0]),c[g][1]=this.world.pxmi(c[g][1]);var h=this.data.fromPolygon(c,a);return this.shapeChanged(),h},removeShape:function(a){var b=this.data.removeShape(a);return this.shapeChanged(),b},setCircle:function(a,b,c,d){return this.clearShapes(),this.addCircle(a,b,c,d)},setRectangle:function(a,b,c,d,e){return void 0===a&&(a=16),void 0===b&&(b=16),this.clearShapes(),this.addRectangle(a,b,c,d,e)},setRectangleFromSprite:function(a){return void 0===a&&(a=this.sprite),this.clearShapes(),this.addRectangle(a.width,a.height,0,0,a.rotation)},setMaterial:function(a,b){if(void 0===b)for(var c=this.data.shapes.length-1;c>=0;c--)this.data.shapes[c].material=a;else b.material=a},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(a,b){for(var c=this.game.cache.getPhysicsData(a,b),d=[],e=0;e<c.length;e++){var f=c[e],g=this.addFixture(f);d[f.filter.group]=d[f.filter.group]||[],d[f.filter.group]=d[f.filter.group].concat(g),f.fixtureKey&&(d[f.fixtureKey]=g)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),d},addFixture:function(a){var b=[];if(a.circle){var c=new p2.Circle({radius:this.world.pxm(a.circle.radius)});c.collisionGroup=a.filter.categoryBits,c.collisionMask=a.filter.maskBits,c.sensor=a.isSensor;var d=p2.vec2.create();d[0]=this.world.pxmi(a.circle.position[0]-this.sprite.width/2),d[1]=this.world.pxmi(a.circle.position[1]-this.sprite.height/2),this.data.addShape(c,d),b.push(c)}else for(var e=a.polygons,f=p2.vec2.create(),g=0;g<e.length;g++){for(var h=e[g],i=[],j=0;j<h.length;j+=2)i.push([this.world.pxmi(h[j]),this.world.pxmi(h[j+1])]);for(var c=new p2.Convex({vertices:i}),k=0;k!==c.vertices.length;k++){var l=c.vertices[k];p2.vec2.sub(l,l,c.centerOfMass)}p2.vec2.scale(f,c.centerOfMass,1),f[0]-=this.world.pxmi(this.sprite.width/2),f[1]-=this.world.pxmi(this.sprite.height/2),c.updateTriangles(),c.updateCenterOfMass(),c.updateBoundingRadius(),c.collisionGroup=a.filter.categoryBits,c.collisionMask=a.filter.maskBits,c.sensor=a.isSensor,this.data.addShape(c,f),b.push(c)}return b},loadPolygon:function(a,b){if(null===a)var c=b;else var c=this.game.cache.getPhysicsData(a,b);for(var d=p2.vec2.create(),e=0;e<c.length;e++){for(var f=[],g=0;g<c[e].shape.length;g+=2)f.push([this.world.pxmi(c[e].shape[g]),this.world.pxmi(c[e].shape[g+1])]);for(var h=new p2.Convex({vertices:f}),i=0;i!==h.vertices.length;i++){var j=h.vertices[i];p2.vec2.sub(j,j,h.centerOfMass)}p2.vec2.scale(d,h.centerOfMass,1),d[0]-=this.world.pxmi(this.sprite.width/2),d[1]-=this.world.pxmi(this.sprite.height/2),h.updateTriangles(),h.updateCenterOfMass(),h.updateBoundingRadius(),this.data.addShape(h,d)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),!0}},c.Physics.P2.Body.prototype.constructor=c.Physics.P2.Body,c.Physics.P2.Body.DYNAMIC=1,c.Physics.P2.Body.STATIC=2,c.Physics.P2.Body.KINEMATIC=4,Object.defineProperty(c.Physics.P2.Body.prototype,"static",{get:function(){return this.data.type===c.Physics.P2.Body.STATIC},set:function(a){a&&this.data.type!==c.Physics.P2.Body.STATIC?(this.data.type=c.Physics.P2.Body.STATIC,this.mass=0):a||this.data.type!==c.Physics.P2.Body.STATIC||(this.data.type=c.Physics.P2.Body.DYNAMIC,0===this.mass&&(this.mass=1))}}),Object.defineProperty(c.Physics.P2.Body.prototype,"dynamic",{get:function(){return this.data.type===c.Physics.P2.Body.DYNAMIC},set:function(a){a&&this.data.type!==c.Physics.P2.Body.DYNAMIC?(this.data.type=c.Physics.P2.Body.DYNAMIC,0===this.mass&&(this.mass=1)):a||this.data.type!==c.Physics.P2.Body.DYNAMIC||(this.data.type=c.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"kinematic",{get:function(){return this.data.type===c.Physics.P2.Body.KINEMATIC},set:function(a){a&&this.data.type!==c.Physics.P2.Body.KINEMATIC?(this.data.type=c.Physics.P2.Body.KINEMATIC,this.mass=4):a||this.data.type!==c.Physics.P2.Body.KINEMATIC||(this.data.type=c.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"allowSleep",{get:function(){return this.data.allowSleep},set:function(a){a!==this.data.allowSleep&&(this.data.allowSleep=a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angle",{get:function(){return c.Math.wrapAngle(c.Math.radToDeg(this.data.angle))},set:function(a){this.data.angle=c.Math.degToRad(c.Math.wrapAngle(a))}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angularDamping",{get:function(){return this.data.angularDamping},set:function(a){this.data.angularDamping=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angularForce",{get:function(){return this.data.angularForce},set:function(a){this.data.angularForce=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angularVelocity",{get:function(){return this.data.angularVelocity},set:function(a){this.data.angularVelocity=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"damping",{get:function(){return this.data.damping},set:function(a){this.data.damping=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"fixedRotation",{get:function(){return this.data.fixedRotation},set:function(a){a!==this.data.fixedRotation&&(this.data.fixedRotation=a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"inertia",{get:function(){return this.data.inertia},set:function(a){this.data.inertia=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"mass",{get:function(){return this.data.mass},set:function(a){a!==this.data.mass&&(this.data.mass=a,this.data.updateMassProperties())}}),Object.defineProperty(c.Physics.P2.Body.prototype,"motionState",{get:function(){return this.data.type},set:function(a){a!==this.data.type&&(this.data.type=a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"rotation",{get:function(){return this.data.angle},set:function(a){this.data.angle=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"sleepSpeedLimit",{get:function(){return this.data.sleepSpeedLimit},set:function(a){this.data.sleepSpeedLimit=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"x",{get:function(){return this.world.mpxi(this.data.position[0])},set:function(a){this.data.position[0]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"y",{get:function(){return this.world.mpxi(this.data.position[1])},set:function(a){this.data.position[1]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"id",{get:function(){return this.data.id}}),Object.defineProperty(c.Physics.P2.Body.prototype,"debug",{get:function(){return null!==this.debugBody},set:function(a){a&&!this.debugBody?this.debugBody=new c.Physics.P2.BodyDebug(this.game,this.data):!a&&this.debugBody&&(this.debugBody.destroy(),this.debugBody=null)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"collideWorldBounds",{get:function(){return this._collideWorldBounds},set:function(a){a&&!this._collideWorldBounds?(this._collideWorldBounds=!0,this.updateCollisionMask()):!a&&this._collideWorldBounds&&(this._collideWorldBounds=!1,this.updateCollisionMask())}}),c.Physics.P2.BodyDebug=function(a,b,d){c.Group.call(this,a);
-var e={pixelsPerLengthUnit:20,debugPolygons:!1,lineWidth:1,alpha:.5};this.settings=c.Utils.extend(e,d),this.ppu=this.settings.pixelsPerLengthUnit,this.ppu=-1*this.ppu,this.body=b,this.canvas=new c.Graphics(a),this.canvas.alpha=this.settings.alpha,this.add(this.canvas),this.draw(),this.updateSpriteTransform()},c.Physics.P2.BodyDebug.prototype=Object.create(c.Group.prototype),c.Physics.P2.BodyDebug.prototype.constructor=c.Physics.P2.BodyDebug,c.Utils.extend(c.Physics.P2.BodyDebug.prototype,{updateSpriteTransform:function(){this.position.x=this.body.position[0]*this.ppu,this.position.y=this.body.position[1]*this.ppu,this.rotation=this.body.angle},draw:function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o;if(h=this.body,j=this.canvas,j.clear(),c=parseInt(this.randomPastelHex(),16),f=16711680,g=this.lineWidth,h instanceof p2.Body&&h.shapes.length){var p=h.shapes.length;for(d=0;d!==p;){if(b=h.shapes[d],i=b.position||0,a=b.angle||0,b instanceof p2.Circle)this.drawCircle(j,i[0]*this.ppu,i[1]*this.ppu,a,b.radius*this.ppu,c,g);else if(b instanceof p2.Capsule)this.drawCapsule(j,i[0]*this.ppu,i[1]*this.ppu,a,b.length*this.ppu,b.radius*this.ppu,f,c,g);else if(b instanceof p2.Plane)this.drawPlane(j,i[0]*this.ppu,-i[1]*this.ppu,c,f,5*g,10*g,10*g,100*this.ppu,a);else if(b instanceof p2.Line)this.drawLine(j,b.length*this.ppu,f,g);else if(b instanceof p2.Box)this.drawRectangle(j,i[0]*this.ppu,i[1]*this.ppu,a,b.width*this.ppu,b.height*this.ppu,f,c,g);else if(b instanceof p2.Convex){for(l=[],m=p2.vec2.create(),e=n=0,o=b.vertices.length;o>=0?o>n:n>o;e=o>=0?++n:--n)k=b.vertices[e],p2.vec2.rotate(m,k,a),l.push([(m[0]+i[0])*this.ppu,-(m[1]+i[1])*this.ppu]);this.drawConvex(j,l,b.triangles,f,c,g,this.settings.debugPolygons,[i[0]*this.ppu,-i[1]*this.ppu])}d++}}},drawRectangle:function(a,b,c,d,e,f,g,h,i){void 0===i&&(i=1),void 0===g&&(g=0),a.lineStyle(i,g,1),a.beginFill(h),a.drawRect(b-e/2,c-f/2,e,f)},drawCircle:function(a,b,c,d,e,f,g){void 0===g&&(g=1),void 0===f&&(f=16777215),a.lineStyle(g,0,1),a.beginFill(f,1),a.drawCircle(b,c,2*-e),a.endFill(),a.moveTo(b,c),a.lineTo(b+e*Math.cos(-d),c+e*Math.sin(-d))},drawLine:function(a,b,c,d){void 0===d&&(d=1),void 0===c&&(c=0),a.lineStyle(5*d,c,1),a.moveTo(-b/2,0),a.lineTo(b/2,0)},drawConvex:function(a,b,c,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r,s;if(void 0===f&&(f=1),void 0===d&&(d=0),g){for(i=[16711680,65280,255],j=0;j!==b.length+1;)l=b[j%b.length],m=b[(j+1)%b.length],o=l[0],r=l[1],p=m[0],s=m[1],a.lineStyle(f,i[j%i.length],1),a.moveTo(o,-r),a.lineTo(p,-s),a.drawCircle(o,-r,2*f),j++;return a.lineStyle(f,0,1),a.drawCircle(h[0],h[1],2*f)}for(a.lineStyle(f,d,1),a.beginFill(e),j=0;j!==b.length;)k=b[j],n=k[0],q=k[1],0===j?a.moveTo(n,-q):a.lineTo(n,-q),j++;return a.endFill(),b.length>2?(a.moveTo(b[b.length-1][0],-b[b.length-1][1]),a.lineTo(b[0][0],-b[0][1])):void 0},drawPath:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r;for(void 0===e&&(e=1),void 0===c&&(c=0),a.lineStyle(e,c,1),"number"==typeof d&&a.beginFill(d),h=null,i=null,g=0;g<b.length;)p=b[g],q=p[0],r=p[1],(q!==h||r!==i)&&(0===g?a.moveTo(q,r):(j=h,k=i,l=q,m=r,n=b[(g+1)%b.length][0],o=b[(g+1)%b.length][1],f=(l-j)*(o-k)-(n-j)*(m-k),0!==f&&a.lineTo(q,r)),h=q,i=r),g++;"number"==typeof d&&a.endFill(),b.length>2&&"number"==typeof d&&(a.moveTo(b[b.length-1][0],b[b.length-1][1]),a.lineTo(b[0][0],b[0][1]))},drawPlane:function(a,b,c,d,e,f,g,h,i,j){var k,l,m;void 0===f&&(f=1),void 0===d&&(d=16777215),a.lineStyle(f,e,11),a.beginFill(d),k=i,a.moveTo(b,-c),l=b+Math.cos(j)*this.game.width,m=c+Math.sin(j)*this.game.height,a.lineTo(l,-m),a.moveTo(b,-c),l=b+Math.cos(j)*-this.game.width,m=c+Math.sin(j)*-this.game.height,a.lineTo(l,-m)},drawCapsule:function(a,b,c,d,e,f,g,h,i){void 0===i&&(i=1),void 0===g&&(g=0),a.lineStyle(i,g,1);var j=Math.cos(d),k=Math.sin(d);a.beginFill(h,1),a.drawCircle(-e/2*j+b,-e/2*k+c,2*-f),a.drawCircle(e/2*j+b,e/2*k+c,2*-f),a.endFill(),a.lineStyle(i,g,0),a.beginFill(h,1),a.moveTo(-e/2*j+f*k+b,-e/2*k+f*j+c),a.lineTo(e/2*j+f*k+b,e/2*k+f*j+c),a.lineTo(e/2*j-f*k+b,e/2*k-f*j+c),a.lineTo(-e/2*j-f*k+b,-e/2*k-f*j+c),a.endFill(),a.lineStyle(i,g,1),a.moveTo(-e/2*j+f*k+b,-e/2*k+f*j+c),a.lineTo(e/2*j+f*k+b,e/2*k+f*j+c),a.moveTo(-e/2*j-f*k+b,-e/2*k-f*j+c),a.lineTo(e/2*j-f*k+b,e/2*k-f*j+c)},randomPastelHex:function(){var a,b,c,d;return c=[255,255,255],d=Math.floor(256*Math.random()),b=Math.floor(256*Math.random()),a=Math.floor(256*Math.random()),d=Math.floor((d+3*c[0])/4),b=Math.floor((b+3*c[1])/4),a=Math.floor((a+3*c[2])/4),this.rgbToHex(d,b,a)},rgbToHex:function(a,b,c){return this.componentToHex(a)+this.componentToHex(b)+this.componentToHex(c)},componentToHex:function(a){var b;return b=a.toString(16),2===b.len?b:b+"0"}}),c.Physics.P2.Spring=function(a,b,c,d,e,f,g,h,i,j){this.game=a.game,this.world=a,void 0===d&&(d=1),void 0===e&&(e=100),void 0===f&&(f=1),d=a.pxm(d);var k={restLength:d,stiffness:e,damping:f};"undefined"!=typeof g&&null!==g&&(k.worldAnchorA=[a.pxm(g[0]),a.pxm(g[1])]),"undefined"!=typeof h&&null!==h&&(k.worldAnchorB=[a.pxm(h[0]),a.pxm(h[1])]),"undefined"!=typeof i&&null!==i&&(k.localAnchorA=[a.pxm(i[0]),a.pxm(i[1])]),"undefined"!=typeof j&&null!==j&&(k.localAnchorB=[a.pxm(j[0]),a.pxm(j[1])]),this.data=new p2.LinearSpring(b,c,k),this.data.parent=this},c.Physics.P2.Spring.prototype.constructor=c.Physics.P2.Spring,c.Physics.P2.RotationalSpring=function(a,b,c,d,e,f){this.game=a.game,this.world=a,void 0===d&&(d=null),void 0===e&&(e=100),void 0===f&&(f=1),d&&(d=a.pxm(d));var g={restAngle:d,stiffness:e,damping:f};this.data=new p2.RotationalSpring(b,c,g),this.data.parent=this},c.Physics.P2.Spring.prototype.constructor=c.Physics.P2.Spring,c.Physics.P2.Material=function(a){this.name=a,p2.Material.call(this)},c.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),c.Physics.P2.Material.prototype.constructor=c.Physics.P2.Material,c.Physics.P2.ContactMaterial=function(a,b,c){p2.ContactMaterial.call(this,a,b,c)},c.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),c.Physics.P2.ContactMaterial.prototype.constructor=c.Physics.P2.ContactMaterial,c.Physics.P2.CollisionGroup=function(a){this.mask=a},c.Physics.P2.DistanceConstraint=function(a,b,c,d,e,f,g){void 0===d&&(d=100),void 0===e&&(e=[0,0]),void 0===f&&(f=[0,0]),void 0===g&&(g=Number.MAX_VALUE),this.game=a.game,this.world=a,d=a.pxm(d),e=[a.pxmi(e[0]),a.pxmi(e[1])],f=[a.pxmi(f[0]),a.pxmi(f[1])];var h={distance:d,localAnchorA:e,localAnchorB:f,maxForce:g};p2.DistanceConstraint.call(this,b,c,h)},c.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),c.Physics.P2.DistanceConstraint.prototype.constructor=c.Physics.P2.DistanceConstraint,c.Physics.P2.GearConstraint=function(a,b,c,d,e){void 0===d&&(d=0),void 0===e&&(e=1),this.game=a.game,this.world=a;var f={angle:d,ratio:e};p2.GearConstraint.call(this,b,c,f)},c.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),c.Physics.P2.GearConstraint.prototype.constructor=c.Physics.P2.GearConstraint,c.Physics.P2.LockConstraint=function(a,b,c,d,e,f){void 0===d&&(d=[0,0]),void 0===e&&(e=0),void 0===f&&(f=Number.MAX_VALUE),this.game=a.game,this.world=a,d=[a.pxm(d[0]),a.pxm(d[1])];var g={localOffsetB:d,localAngleB:e,maxForce:f};p2.LockConstraint.call(this,b,c,g)},c.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),c.Physics.P2.LockConstraint.prototype.constructor=c.Physics.P2.LockConstraint,c.Physics.P2.PrismaticConstraint=function(a,b,c,d,e,f,g,h){void 0===d&&(d=!0),void 0===e&&(e=[0,0]),void 0===f&&(f=[0,0]),void 0===g&&(g=[0,0]),void 0===h&&(h=Number.MAX_VALUE),this.game=a.game,this.world=a,e=[a.pxmi(e[0]),a.pxmi(e[1])],f=[a.pxmi(f[0]),a.pxmi(f[1])];var i={localAnchorA:e,localAnchorB:f,localAxisA:g,maxForce:h,disableRotationalLock:!d};p2.PrismaticConstraint.call(this,b,c,i)},c.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),c.Physics.P2.PrismaticConstraint.prototype.constructor=c.Physics.P2.PrismaticConstraint,c.Physics.P2.RevoluteConstraint=function(a,b,c,d,e,f,g){void 0===f&&(f=Number.MAX_VALUE),void 0===g&&(g=null),this.game=a.game,this.world=a,c=[a.pxmi(c[0]),a.pxmi(c[1])],e=[a.pxmi(e[0]),a.pxmi(e[1])],g&&(g=[a.pxmi(g[0]),a.pxmi(g[1])]);var h={worldPivot:g,localPivotA:c,localPivotB:e,maxForce:f};p2.RevoluteConstraint.call(this,b,d,h)},c.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),c.Physics.P2.RevoluteConstraint.prototype.constructor=c.Physics.P2.RevoluteConstraint,c.ImageCollection=function(a,b,c,d,e,f,g){(void 0===c||0>=c)&&(c=32),(void 0===d||0>=d)&&(d=32),void 0===e&&(e=0),void 0===f&&(f=0),this.name=a,this.firstgid=0|b,this.imageWidth=0|c,this.imageHeight=0|d,this.imageMargin=0|e,this.imageSpacing=0|f,this.properties=g||{},this.images=[],this.total=0},c.ImageCollection.prototype={containsImageIndex:function(a){return a>=this.firstgid&&a<this.firstgid+this.total},addImage:function(a,b){this.images.push({gid:a,image:b}),this.total++}},c.ImageCollection.prototype.constructor=c.ImageCollection,c.Tile=function(a,b,c,d,e,f){this.layer=a,this.index=b,this.x=c,this.y=d,this.rotation=0,this.flipped=!1,this.worldX=c*e,this.worldY=d*f,this.width=e,this.height=f,this.centerX=Math.abs(e/2),this.centerY=Math.abs(f/2),this.alpha=1,this.properties={},this.scanned=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.collisionCallback=null,this.collisionCallbackContext=this},c.Tile.prototype={containsPoint:function(a,b){return!(a<this.worldX||b<this.worldY||a>this.right||b>this.bottom)},intersects:function(a,b,c,d){return c<=this.worldX?!1:d<=this.worldY?!1:a>=this.worldX+this.width?!1:b>=this.worldY+this.height?!1:!0},setCollisionCallback:function(a,b){this.collisionCallback=a,this.collisionCallbackContext=b},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(a,b,c,d){this.collideLeft=a,this.collideRight=b,this.collideUp=c,this.collideDown=d,this.faceLeft=a,this.faceRight=b,this.faceTop=c,this.faceBottom=d},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(a,b){return a&&b?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:a?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:b?this.faceTop||this.faceBottom||this.faceLeft||this.faceRight:!1},copy:function(a){this.index=a.index,this.alpha=a.alpha,this.properties=a.properties,this.collideUp=a.collideUp,this.collideDown=a.collideDown,this.collideLeft=a.collideLeft,this.collideRight=a.collideRight,this.collisionCallback=a.collisionCallback,this.collisionCallbackContext=a.collisionCallbackContext}},c.Tile.prototype.constructor=c.Tile,Object.defineProperty(c.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(c.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(c.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(c.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(c.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(c.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),c.Tilemap=function(a,b,d,e,f,g){this.game=a,this.key=b;var h=c.TilemapParser.parse(this.game,b,d,e,f,g);null!==h&&(this.width=h.width,this.height=h.height,this.tileWidth=h.tileWidth,this.tileHeight=h.tileHeight,this.orientation=h.orientation,this.format=h.format,this.version=h.version,this.properties=h.properties,this.widthInPixels=h.widthInPixels,this.heightInPixels=h.heightInPixels,this.layers=h.layers,this.tilesets=h.tilesets,this.imagecollections=h.imagecollections,this.tiles=h.tiles,this.objects=h.objects,this.collideIndexes=[],this.collision=h.collision,this.images=h.images,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},c.Tilemap.CSV=0,c.Tilemap.TILED_JSON=1,c.Tilemap.NORTH=0,c.Tilemap.EAST=1,c.Tilemap.SOUTH=2,c.Tilemap.WEST=3,c.Tilemap.prototype={create:function(a,b,c,d,e,f){return void 0===f&&(f=this.game.world),this.width=b,this.height=c,this.setTileSize(d,e),this.layers.length=0,this.createBlankLayer(a,b,c,d,e,f)},setTileSize:function(a,b){this.tileWidth=a,this.tileHeight=b,this.widthInPixels=this.width*a,this.heightInPixels=this.height*b},addTilesetImage:function(a,b,d,e,f,g,h){if(void 0===a)return null;void 0===d&&(d=this.tileWidth),void 0===e&&(e=this.tileHeight),void 0===f&&(f=0),void 0===g&&(g=0),void 0===h&&(h=0),0===d&&(d=32),0===e&&(e=32);var i=null;if((void 0===b||null===b)&&(b=a),b instanceof c.BitmapData)i=b.canvas;else{if(!this.game.cache.checkImageKey(b))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+b+'"'),null;i=this.game.cache.getImage(b)}var j=this.getTilesetIndex(a);if(null===j&&this.format===c.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+b+'"'),null;if(this.tilesets[j])return this.tilesets[j].setImage(i),this.tilesets[j];var k=new c.Tileset(a,h,d,e,f,g,{});k.setImage(i),this.tilesets.push(k);for(var l=this.tilesets.length-1,m=f,n=f,o=0,p=0,q=0,r=h;r<h+k.total&&(this.tiles[r]=[m,n,l],m+=d+g,o++,o!==k.total)&&(p++,p!==k.columns||(m=f,n+=e+g,p=0,q++,q!==k.rows));r++);return k},createFromObjects:function(a,b,d,e,f,g,h,i,j){if(void 0===f&&(f=!0),void 0===g&&(g=!1),void 0===h&&(h=this.game.world),void 0===i&&(i=c.Sprite),void 0===j&&(j=!0),!this.objects[a])return void console.warn("Tilemap.createFromObjects: Invalid objectgroup name given: "+a);for(var k,l=!1,m=0,n=this.objects[a].length;n>m;m++)if("undefined"!=typeof this.objects[a][m].gid&&"number"==typeof b&&this.objects[a][m].gid===b&&(l=!0),"undefined"!=typeof this.objects[a][m].id&&"number"==typeof b&&this.objects[a][m].id===b&&(l=!0),"undefined"!=typeof this.objects[a][m].name&&"string"==typeof b&&this.objects[a][m].name===b&&(l=!0),l){k=new i(this.game,this.objects[a][m].x,this.objects[a][m].y,d,e),k.name=this.objects[a][m].name,k.visible=this.objects[a][m].visible,k.autoCull=g,k.exists=f,k.width=this.objects[a][m].width,k.height=this.objects[a][m].height,this.objects[a][m].rotation&&(k.angle=this.objects[a][m].rotation),j&&(k.y-=k.height),h.add(k);for(var o in this.objects[a][m].properties)h.set(k,o,this.objects[a][m].properties[o],!1,!1,0,!0)}},createFromTiles:function(a,b,d,e,f,g){"number"==typeof a&&(a=[a]),void 0===b||null===b?b=[]:"number"==typeof b&&(b=[b]),e=this.getLayer(e),void 0===f&&(f=this.game.world),void 0===g&&(g={}),void 0===g.customClass&&(g.customClass=c.Sprite),void 0===g.adjustY&&(g.adjustY=!0);var h=this.layers[e].width,i=this.layers[e].height;if(this.copy(0,0,h,i,e),this._results.length<2)return 0;for(var j,k=0,l=1,m=this._results.length;m>l;l++)if(-1!==a.indexOf(this._results[l].index)){j=new g.customClass(this.game,this._results[l].worldX,this._results[l].worldY,d);for(var n in g)j[n]=g[n];f.add(j),k++}if(1===b.length)for(l=0;l<a.length;l++)this.replace(a[l],b[0],0,0,h,i,e);else if(b.length>1)for(l=0;l<a.length;l++)this.replace(a[l],b[l],0,0,h,i,e);return k},createLayer:function(a,b,d,e){void 0===b&&(b=this.game.width),void 0===d&&(d=this.game.height),void 0===e&&(e=this.game.world);var f=a;return"string"==typeof a&&(f=this.getLayerIndex(a)),null===f||f>this.layers.length?void console.warn("Tilemap.createLayer: Invalid layer ID given: "+f):e.add(new c.TilemapLayer(this.game,this,f,b,d))},createBlankLayer:function(a,b,d,e,f,g){if(void 0===g&&(g=this.game.world),null!==this.getLayerIndex(a))return void console.warn("Tilemap.createBlankLayer: Layer with matching name already exists");for(var h,i={name:a,x:0,y:0,width:b,height:d,widthInPixels:b*e,heightInPixels:d*f,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},j=[],k=0;d>k;k++){h=[];for(var l=0;b>l;l++)h.push(new c.Tile(i,-1,l,k,e,f));j.push(h)}i.data=j,this.layers.push(i),this.currentLayer=this.layers.length-1;var m=i.widthInPixels,n=i.heightInPixels;m>this.game.width&&(m=this.game.width),n>this.game.height&&(n=this.game.height);var j=new c.TilemapLayer(this.game,this,this.layers.length-1,m,n);return j.name=a,g.add(j)},getIndex:function(a,b){for(var c=0;c<a.length;c++)if(a[c].name===b)return c;return null},getLayerIndex:function(a){return this.getIndex(this.layers,a)},getTilesetIndex:function(a){return this.getIndex(this.tilesets,a)},getImageIndex:function(a){return this.getIndex(this.images,a)},getObjectIndex:function(a){return this.getIndex(this.objects,a)},setTileIndexCallback:function(a,b,c,d){if(d=this.getLayer(d),"number"==typeof a)this.layers[d].callbacks[a]={callback:b,callbackContext:c};else for(var e=0,f=a.length;f>e;e++)this.layers[d].callbacks[a[e]]={callback:b,callbackContext:c}},setTileLocationCallback:function(a,b,c,d,e,f,g){if(g=this.getLayer(g),this.copy(a,b,c,d,g),!(this._results.length<2))for(var h=1;h<this._results.length;h++)this._results[h].setCollisionCallback(e,f)},setCollision:function(a,b,c,d){if(void 0===b&&(b=!0),void 0===d&&(d=!0),c=this.getLayer(c),"number"==typeof a)return this.setCollisionByIndex(a,b,c,!0);if(Array.isArray(a)){for(var e=0;e<a.length;e++)this.setCollisionByIndex(a[e],b,c,!1);d&&this.calculateFaces(c)}},setCollisionBetween:function(a,b,c,d,e){if(void 0===c&&(c=!0),void 0===e&&(e=!0),d=this.getLayer(d),!(a>b)){for(var f=a;b>=f;f++)this.setCollisionByIndex(f,c,d,!1);e&&this.calculateFaces(d)}},setCollisionByExclusion:function(a,b,c,d){void 0===b&&(b=!0),void 0===d&&(d=!0),c=this.getLayer(c);for(var e=0,f=this.tiles.length;f>e;e++)-1===a.indexOf(e)&&this.setCollisionByIndex(e,b,c,!1);d&&this.calculateFaces(c)},setCollisionByIndex:function(a,b,c,d){if(void 0===b&&(b=!0),void 0===c&&(c=this.currentLayer),void 0===d&&(d=!0),b)this.collideIndexes.push(a);else{var e=this.collideIndexes.indexOf(a);e>-1&&this.collideIndexes.splice(e,1)}for(var f=0;f<this.layers[c].height;f++)for(var g=0;g<this.layers[c].width;g++){var h=this.layers[c].data[f][g];h&&h.index===a&&(b?h.setCollision(!0,!0,!0,!0):h.resetCollision(),h.faceTop=b,h.faceBottom=b,h.faceLeft=b,h.faceRight=b)}return d&&this.calculateFaces(c),c},getLayer:function(a){return void 0===a?a=this.currentLayer:"string"==typeof a?a=this.getLayerIndex(a):a instanceof c.TilemapLayer&&(a=a.index),a},setPreventRecalculate:function(a){if(a===!0&&this.preventingRecalculate!==!0&&(this.preventingRecalculate=!0,this.needToRecalculate={}),a===!1&&this.preventingRecalculate===!0){this.preventingRecalculate=!1;for(var b in this.needToRecalculate)this.calculateFaces(b);this.needToRecalculate=!1}},calculateFaces:function(a){if(this.preventingRecalculate)return void(this.needToRecalculate[a]=!0);for(var b=null,c=null,d=null,e=null,f=0,g=this.layers[a].height;g>f;f++)for(var h=0,i=this.layers[a].width;i>h;h++){var j=this.layers[a].data[f][h];j&&(b=this.getTileAbove(a,h,f),c=this.getTileBelow(a,h,f),d=this.getTileLeft(a,h,f),e=this.getTileRight(a,h,f),j.collides&&(j.faceTop=!0,j.faceBottom=!0,j.faceLeft=!0,j.faceRight=!0),b&&b.collides&&(j.faceTop=!1),c&&c.collides&&(j.faceBottom=!1),d&&d.collides&&(j.faceLeft=!1),e&&e.collides&&(j.faceRight=!1))}},getTileAbove:function(a,b,c){return c>0?this.layers[a].data[c-1][b]:null},getTileBelow:function(a,b,c){return c<this.layers[a].height-1?this.layers[a].data[c+1][b]:null},getTileLeft:function(a,b,c){return b>0?this.layers[a].data[c][b-1]:null},getTileRight:function(a,b,c){return b<this.layers[a].width-1?this.layers[a].data[c][b+1]:null},setLayer:function(a){a=this.getLayer(a),this.layers[a]&&(this.currentLayer=a)},hasTile:function(a,b,c){return c=this.getLayer(c),this.layers[c].data[b][a].index>-1},removeTile:function(a,b,d){if(d=this.getLayer(d),a>=0&&a<this.layers[d].width&&b>=0&&b<this.layers[d].height&&this.hasTile(a,b,d)){var e=this.layers[d].data[b][a];return this.layers[d].data[b][a]=new c.Tile(this.layers[d],-1,a,b,this.tileWidth,this.tileHeight),this.layers[d].dirty=!0,this.calculateFaces(d),e}},removeTileWorldXY:function(a,b,c,d,e){return e=this.getLayer(e),a=this.game.math.snapToFloor(a,c)/c,b=this.game.math.snapToFloor(b,d)/d,this.removeTile(a,b,e)},putTile:function(a,b,d,e){if(null===a)return this.removeTile(b,d,e);if(e=this.getLayer(e),b>=0&&b<this.layers[e].width&&d>=0&&d<this.layers[e].height){var f;return a instanceof c.Tile?(f=a.index,this.hasTile(b,d,e)?this.layers[e].data[d][b].copy(a):this.layers[e].data[d][b]=new c.Tile(e,f,b,d,a.width,a.height)):(f=a,this.hasTile(b,d,e)?this.layers[e].data[d][b].index=f:this.layers[e].data[d][b]=new c.Tile(this.layers[e],f,b,d,this.tileWidth,this.tileHeight)),this.collideIndexes.indexOf(f)>-1?this.layers[e].data[d][b].setCollision(!0,!0,!0,!0):this.layers[e].data[d][b].resetCollision(),this.layers[e].dirty=!0,this.calculateFaces(e),this.layers[e].data[d][b]}return null},putTileWorldXY:function(a,b,c,d,e,f){return f=this.getLayer(f),b=this.game.math.snapToFloor(b,d)/d,c=this.game.math.snapToFloor(c,e)/e,this.putTile(a,b,c,f)},searchTileIndex:function(a,b,c,d){void 0===b&&(b=0),void 0===c&&(c=!1),d=this.getLayer(d);var e=0;if(c){for(var f=this.layers[d].height-1;f>=0;f--)for(var g=this.layers[d].width-1;g>=0;g--)if(this.layers[d].data[f][g].index===a){if(e===b)return this.layers[d].data[f][g];e++}}else for(var f=0;f<this.layers[d].height;f++)for(var g=0;g<this.layers[d].width;g++)if(this.layers[d].data[f][g].index===a){if(e===b)return this.layers[d].data[f][g];e++}return null},getTile:function(a,b,c,d){return void 0===d&&(d=!1),c=this.getLayer(c),a>=0&&a<this.layers[c].width&&b>=0&&b<this.layers[c].height?-1===this.layers[c].data[b][a].index?d?this.layers[c].data[b][a]:null:this.layers[c].data[b][a]:null},getTileWorldXY:function(a,b,c,d,e,f){return void 0===c&&(c=this.tileWidth),void 0===d&&(d=this.tileHeight),e=this.getLayer(e),a=this.game.math.snapToFloor(a,c)/c,b=this.game.math.snapToFloor(b,d)/d,this.getTile(a,b,e,f)},copy:function(a,b,c,d,e){if(e=this.getLayer(e),!this.layers[e])return void(this._results.length=0);void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c=this.layers[e].width),void 0===d&&(d=this.layers[e].height),0>a&&(a=0),0>b&&(b=0),c>this.layers[e].width&&(c=this.layers[e].width),d>this.layers[e].height&&(d=this.layers[e].height),this._results.length=0,this._results.push({x:a,y:b,width:c,height:d,layer:e});for(var f=b;b+d>f;f++)for(var g=a;a+c>g;g++)this._results.push(this.layers[e].data[f][g]);return this._results},paste:function(a,b,c,d){if(void 0===a&&(a=0),void 0===b&&(b=0),d=this.getLayer(d),c&&!(c.length<2)){for(var e=a-c[1].x,f=b-c[1].y,g=1;g<c.length;g++)this.layers[d].data[f+c[g].y][e+c[g].x].copy(c[g]);this.layers[d].dirty=!0,this.calculateFaces(d)}},swap:function(a,b,c,d,e,f,g){g=this.getLayer(g),this.copy(c,d,e,f,g),this._results.length<2||(this._tempA=a,this._tempB=b,this._results.forEach(this.swapHandler,this),this.paste(c,d,this._results,g))},swapHandler:function(a){a.index===this._tempA?a.index=this._tempB:a.index===this._tempB&&(a.index=this._tempA)},forEach:function(a,b,c,d,e,f,g){g=this.getLayer(g),this.copy(c,d,e,f,g),this._results.length<2||(this._results.forEach(a,b),this.paste(c,d,this._results,g))},replace:function(a,b,c,d,e,f,g){if(g=this.getLayer(g),this.copy(c,d,e,f,g),!(this._results.length<2)){for(var h=1;h<this._results.length;h++)this._results[h].index===a&&(this._results[h].index=b);this.paste(c,d,this._results,g)}},random:function(a,b,c,d,e){if(e=this.getLayer(e),this.copy(a,b,c,d,e),!(this._results.length<2)){for(var f=[],g=1;g<this._results.length;g++)if(this._results[g].index){var h=this._results[g].index;-1===f.indexOf(h)&&f.push(h)}for(var i=1;i<this._results.length;i++)this._results[i].index=this.game.rnd.pick(f);this.paste(a,b,this._results,e)}},shuffle:function(a,b,d,e,f){if(f=this.getLayer(f),this.copy(a,b,d,e,f),!(this._results.length<2)){for(var g=[],h=1;h<this._results.length;h++)this._results[h].index&&g.push(this._results[h].index);c.Utils.shuffle(g);for(var i=1;i<this._results.length;i++)this._results[i].index=g[i-1];this.paste(a,b,this._results,f)}},fill:function(a,b,c,d,e,f){if(f=this.getLayer(f),this.copy(b,c,d,e,f),!(this._results.length<2)){for(var g=1;g<this._results.length;g++)this._results[g].index=a;this.paste(b,c,this._results,f)}},removeAllLayers:function(){this.layers.length=0,this.currentLayer=0},dump:function(){for(var a="",b=[""],c=0;c<this.layers[this.currentLayer].height;c++){for(var d=0;d<this.layers[this.currentLayer].width;d++)a+="%c  ",b.push(this.layers[this.currentLayer].data[c][d]>1?this.debugMap[this.layers[this.currentLayer].data[c][d]]?"background: "+this.debugMap[this.layers[this.currentLayer].data[c][d]]:"background: #ffffff":"background: rgb(0, 0, 0)");a+="\n"}b[0]=a,console.log.apply(console,b)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},c.Tilemap.prototype.constructor=c.Tilemap,Object.defineProperty(c.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(a){a!==this.currentLayer&&this.setLayer(a)}}),c.TilemapLayer=function(a,b,d,e,f){e|=0,f|=0,c.Sprite.call(this,a,0,0),this.map=b,this.index=d,this.layer=b.layers[d],this.canvas=c.Canvas.create(e,f),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas))),this.type=c.TILEMAPLAYER,this.physicsType=c.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!1,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:b.tileWidth,tileHeight:b.tileHeight,cw:b.tileWidth,ch:b.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this._results=[],a.device.canvasBitBltShift||(this.renderSettings.copyCanvas=c.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},c.TilemapLayer.prototype=Object.create(c.Sprite.prototype),c.TilemapLayer.prototype.constructor=c.TilemapLayer,c.TilemapLayer.prototype.preUpdateCore=c.Component.Core.preUpdate,c.TilemapLayer.sharedCopyCanvas=null,c.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=c.Canvas.create(2,2)),this.sharedCopyCanvas},c.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},c.TilemapLayer.prototype.postUpdate=function(){c.Component.FixedToCamera.postUpdate.call(this);var a=this.game.camera;this.scrollX=a.x*this.scrollFactorX/this.scale.x,this.scrollY=a.y*this.scrollFactorY/this.scale.y,this.render()},c.TilemapLayer.prototype.resize=function(a,b){this.canvas.width=a,this.canvas.height=b,this.texture.frame.resize(a,b),this.texture.width=a,this.texture.height=b,this.texture.crop.width=a,this.texture.crop.height=b,this.texture.baseTexture.width=a,this.texture.baseTexture.height=b,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},c.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},c.TilemapLayer.prototype._fixX=function(a){return 0>a&&(a=0),1===this.scrollFactorX?a:this._scrollX+(a-this._scrollX/this.scrollFactorX)},c.TilemapLayer.prototype._unfixX=function(a){return 1===this.scrollFactorX?a:this._scrollX/this.scrollFactorX+(a-this._scrollX)},c.TilemapLayer.prototype._fixY=function(a){return 0>a&&(a=0),1===this.scrollFactorY?a:this._scrollY+(a-this._scrollY/this.scrollFactorY)},c.TilemapLayer.prototype._unfixY=function(a){return 1===this.scrollFactorY?a:this._scrollY/this.scrollFactorY+(a-this._scrollY)},c.TilemapLayer.prototype.getTileX=function(a){return Math.floor(this._fixX(a)/this._mc.tileWidth)},c.TilemapLayer.prototype.getTileY=function(a){return Math.floor(this._fixY(a)/this._mc.tileHeight)},c.TilemapLayer.prototype.getTileXY=function(a,b,c){return c.x=this.getTileX(a),c.y=this.getTileY(b),c},c.TilemapLayer.prototype.getRayCastTiles=function(a,b,c,d){b||(b=this.rayStepRate),void 0===c&&(c=!1),void 0===d&&(d=!1);var e=this.getTiles(a.x,a.y,a.width,a.height,c,d);if(0===e.length)return[];for(var f=a.coordinatesOnLine(b),g=[],h=0;h<e.length;h++)for(var i=0;i<f.length;i++){var j=e[h],k=f[i];if(j.containsPoint(k[0],k[1])){g.push(j);break}}return g},c.TilemapLayer.prototype.getTiles=function(a,b,c,d,e,f){void 0===e&&(e=!1),void 0===f&&(f=!1);var g=!(e||f);a=this._fixX(a),b=this._fixY(b);for(var h=Math.floor(a/(this._mc.cw*this.scale.x)),i=Math.floor(b/(this._mc.ch*this.scale.y)),j=Math.ceil((a+c)/(this._mc.cw*this.scale.x))-h,k=Math.ceil((b+d)/(this._mc.ch*this.scale.y))-i;this._results.length;)this._results.pop();for(var l=i;i+k>l;l++)for(var m=h;h+j>m;m++){var n=this.layer.data[l];n&&n[m]&&(g||n[m].isInteresting(e,f))&&this._results.push(n[m])}return this._results.slice()},c.TilemapLayer.prototype.resolveTileset=function(a){var b=this._mc.tilesets;if(2e3>a)for(;b.length<a;)b.push(void 0);var c=this.map.tiles[a]&&this.map.tiles[a][2];if(null!=c){var d=this.map.tilesets[c];if(d&&d.containsTileIndex(a))return b[a]=d}return b[a]=null},c.TilemapLayer.prototype.resetTilesetCache=function(){for(var a=this._mc.tilesets;a.length;)a.pop()},c.TilemapLayer.prototype.setScale=function(a,b){a=a||1,b=b||a;for(var c=0;c<this.layer.data.length;c++)for(var d=this.layer.data[c],e=0;e<d.length;e++){var f=d[e];f.width=this.map.tileWidth*a,f.height=this.map.tileHeight*b,f.worldX=f.x*f.width,f.worldY=f.y*f.height}this.scale.setTo(a,b)},c.TilemapLayer.prototype.shiftCanvas=function(a,b,c){var d=a.canvas,e=d.width-Math.abs(b),f=d.height-Math.abs(c),g=0,h=0,i=b,j=c;0>b&&(g=-b,i=0),0>c&&(h=-c,j=0);var k=this.renderSettings.copyCanvas;if(k){(k.width<e||k.height<f)&&(k.width=e,k.height=f);var l=k.getContext("2d");l.clearRect(0,0,e,f),l.drawImage(d,g,h,e,f,0,0,e,f),a.clearRect(i,j,e,f),a.drawImage(k,0,0,e,f,i,j,e,f)}else a.save(),a.globalCompositeOperation="copy",a.drawImage(d,g,h,e,f,i,j,e,f),a.restore()},c.TilemapLayer.prototype.renderRegion=function(a,b,c,d,e,f){var g=this.context,h=this.layer.width,i=this.layer.height,j=this._mc.tileWidth,k=this._mc.tileHeight,l=this._mc.tilesets,m=0/0;this._wrap||(e>=c&&(c=Math.max(0,c),e=Math.min(h-1,e)),f>=d&&(d=Math.max(0,d),f=Math.min(i-1,f)));var n,o,p,q,r,s,t=c*j-a,u=d*k-b,v=(c+(1<<20)*h)%h,w=(d+(1<<20)*i)%i;for(g.fillStyle=this.tileColor,q=w,s=f-d,o=u;s>=0;q++,s--,o+=k){q>=i&&(q-=i);var x=this.layer.data[q];for(p=v,r=e-c,n=t;r>=0;p++,r--,n+=j){p>=h&&(p-=h);var y=x[p];if(y&&!(y.index<0)){var z=y.index,A=l[z];void 0===A&&(A=this.resolveTileset(z)),y.alpha===m||this.debug||(g.globalAlpha=y.alpha,m=y.alpha),A?y.rotation||y.flipped?(g.save(),g.translate(n+y.centerX,o+y.centerY),g.rotate(y.rotation),y.flipped&&g.scale(-1,1),A.draw(g,-y.centerX,-y.centerY,z),g.restore()):A.draw(g,n,o,z):this.debugSettings.missingImageFill&&(g.fillStyle=this.debugSettings.missingImageFill,g.fillRect(n,o,j,k)),y.debug&&this.debugSettings.debuggedTileOverfill&&(g.fillStyle=this.debugSettings.debuggedTileOverfill,g.fillRect(n,o,j,k))}}}},c.TilemapLayer.prototype.renderDeltaScroll=function(a,b){var c=this._mc.scrollX,d=this._mc.scrollY,e=this.canvas.width,f=this.canvas.height,g=this._mc.tileWidth,h=this._mc.tileHeight,i=0,j=-g,k=0,l=-h;if(0>a?(i=e+a,j=e-1):a>0&&(j=a),0>b?(k=f+b,l=f-1):b>0&&(l=b),this.shiftCanvas(this.context,a,b),i=Math.floor((i+c)/g),j=Math.floor((j+c)/g),k=Math.floor((k+d)/h),l=Math.floor((l+d)/h),j>=i){this.context.clearRect(i*g-c,0,(j-i+1)*g,f);var m=Math.floor((0+d)/h),n=Math.floor((f-1+d)/h);
-this.renderRegion(c,d,i,m,j,n)}if(l>=k){this.context.clearRect(0,k*h-d,e,(l-k+1)*h);var o=Math.floor((0+c)/g),p=Math.floor((e-1+c)/g);this.renderRegion(c,d,o,k,p,l)}},c.TilemapLayer.prototype.renderFull=function(){var a=this._mc.scrollX,b=this._mc.scrollY,c=this.canvas.width,d=this.canvas.height,e=this._mc.tileWidth,f=this._mc.tileHeight,g=Math.floor(a/e),h=Math.floor((c-1+a)/e),i=Math.floor(b/f),j=Math.floor((d-1+b)/f);this.context.clearRect(0,0,c,d),this.renderRegion(a,b,g,i,h,j)},c.TilemapLayer.prototype.render=function(){var a=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,a=!0);var b=this.canvas.width,c=this.canvas.height,d=0|this._scrollX,e=0|this._scrollY,f=this._mc,g=f.scrollX-d,h=f.scrollY-e;if(a||0!==g||0!==h||f.renderWidth!==b||f.renderHeight!==c)return this.context.save(),f.scrollX=d,f.scrollY=e,(f.renderWidth!==b||f.renderHeight!==c)&&(f.renderWidth=b,f.renderHeight=c),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(a=!0)),!a&&this.renderSettings.enableScrollDelta&&Math.abs(g)+Math.abs(h)<Math.min(b,c)?this.renderDeltaScroll(g,h):this.renderFull(),this.debug&&(this.context.globalAlpha=1,this.renderDebug()),this.texture.baseTexture.dirty(),this.dirty=!1,this.context.restore(),!0}},c.TilemapLayer.prototype.renderDebug=function(){var a,b,c,d,e,f,g=this._mc.scrollX,h=this._mc.scrollY,i=this.context,j=this.canvas.width,k=this.canvas.height,l=this.layer.width,m=this.layer.height,n=this._mc.tileWidth,o=this._mc.tileHeight,p=Math.floor(g/n),q=Math.floor((j-1+g)/n),r=Math.floor(h/o),s=Math.floor((k-1+h)/o),t=p*n-g,u=r*o-h,v=(p+(1<<20)*l)%l,w=(r+(1<<20)*m)%m;for(i.strokeStyle=this.debugSettings.facingEdgeStroke,d=w,f=s-r,b=u;f>=0;d++,f--,b+=o){d>=m&&(d-=m);var x=this.layer.data[d];for(c=v,e=q-p,a=t;e>=0;c++,e--,a+=n){c>=l&&(c-=l);var y=x[c];!y||y.index<0||!y.collides||(this.debugSettings.collidingTileOverfill&&(i.fillStyle=this.debugSettings.collidingTileOverfill,i.fillRect(a,b,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(i.beginPath(),y.faceTop&&(i.moveTo(a,b),i.lineTo(a+this._mc.cw,b)),y.faceBottom&&(i.moveTo(a,b+this._mc.ch),i.lineTo(a+this._mc.cw,b+this._mc.ch)),y.faceLeft&&(i.moveTo(a,b),i.lineTo(a,b+this._mc.ch)),y.faceRight&&(i.moveTo(a+this._mc.cw,b),i.lineTo(a+this._mc.cw,b+this._mc.ch)),i.stroke()))}}},Object.defineProperty(c.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(a){this._wrap=a,this.dirty=!0}}),Object.defineProperty(c.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(a){this._scrollX=a}}),Object.defineProperty(c.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(a){this._scrollY=a}}),Object.defineProperty(c.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(a){this._mc.cw=0|a,this.dirty=!0}}),Object.defineProperty(c.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(a){this._mc.ch=0|a,this.dirty=!0}}),c.TilemapParser={parse:function(a,b,d,e,f,g){if(void 0===d&&(d=32),void 0===e&&(e=32),void 0===f&&(f=10),void 0===g&&(g=10),void 0===b)return this.getEmptyData();if(null===b)return this.getEmptyData(d,e,f,g);var h=a.cache.getTilemapData(b);if(h){if(h.format===c.Tilemap.CSV)return this.parseCSV(b,h.data,d,e);if(!h.format||h.format===c.Tilemap.TILED_JSON)return this.parseTiledJSON(h.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+b)},parseCSV:function(a,b,d,e){var f=this.getEmptyData();b=b.trim();for(var g=[],h=b.split("\n"),i=h.length,j=0,k=0;k<h.length;k++){g[k]=[];for(var l=h[k].split(","),m=0;m<l.length;m++)g[k][m]=new c.Tile(f.layers[0],parseInt(l[m],10),m,k,d,e);0===j&&(j=l.length)}return f.format=c.Tilemap.CSV,f.name=a,f.width=j,f.height=i,f.tileWidth=d,f.tileHeight=e,f.widthInPixels=j*d,f.heightInPixels=i*e,f.layers[0].width=j,f.layers[0].height=i,f.layers[0].widthInPixels=f.widthInPixels,f.layers[0].heightInPixels=f.heightInPixels,f.layers[0].data=g,f},getEmptyData:function(a,b,c,d){var e={};e.width=0,e.height=0,e.tileWidth=0,e.tileHeight=0,"undefined"!=typeof a&&null!==a&&(e.tileWidth=a),"undefined"!=typeof b&&null!==b&&(e.tileHeight=b),"undefined"!=typeof c&&null!==c&&(e.width=c),"undefined"!=typeof d&&null!==d&&(e.height=d),e.orientation="orthogonal",e.version="1",e.properties={},e.widthInPixels=0,e.heightInPixels=0;var f=[],g={name:"layer",x:0,y:0,width:0,height:0,widthInPixels:0,heightInPixels:0,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:[]};return f.push(g),e.layers=f,e.images=[],e.objects={},e.collision={},e.tilesets=[],e.tiles=[],e},parseTiledJSON:function(a){function b(a,b){var c={};for(var d in b){var e=b[d];"undefined"!=typeof a[e]&&(c[e]=a[e])}return c}if("orthogonal"!==a.orientation)return console.warn("TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser"),null;var d={};d.width=a.width,d.height=a.height,d.tileWidth=a.tilewidth,d.tileHeight=a.tileheight,d.orientation=a.orientation,d.format=c.Tilemap.TILED_JSON,d.version=a.version,d.properties=a.properties,d.widthInPixels=d.width*d.tileWidth,d.heightInPixels=d.height*d.tileHeight;for(var e=[],f=0;f<a.layers.length;f++)if("tilelayer"===a.layers[f].type){var g={name:a.layers[f].name,x:a.layers[f].x,y:a.layers[f].y,width:a.layers[f].width,height:a.layers[f].height,widthInPixels:a.layers[f].width*a.tilewidth,heightInPixels:a.layers[f].height*a.tileheight,alpha:a.layers[f].opacity,visible:a.layers[f].visible,properties:{},indexes:[],callbacks:[],bodies:[]};a.layers[f].properties&&(g.properties=a.layers[f].properties);for(var h,i,j,k,l=0,m=[],n=[],o=0,p=a.layers[f].data.length;p>o;o++){if(h=0,i=!1,k=a.layers[f].data[o],k>536870912)switch(j=0,k>2147483648&&(k-=2147483648,j+=4),k>1073741824&&(k-=1073741824,j+=2),k>536870912&&(k-=536870912,j+=1),j){case 5:h=Math.PI/2;break;case 6:h=Math.PI;break;case 3:h=3*Math.PI/2;break;case 4:h=0,i=!0;break;case 7:h=Math.PI/2,i=!0;break;case 2:h=Math.PI,i=!0;break;case 1:h=3*Math.PI/2,i=!0}k>0?(m.push(new c.Tile(g,k,l,n.length,a.tilewidth,a.tileheight)),m[m.length-1].rotation=h,m[m.length-1].flipped=i):m.push(new c.Tile(g,-1,l,n.length,a.tilewidth,a.tileheight)),l++,l===a.layers[f].width&&(n.push(m),l=0,m=[])}g.data=n,e.push(g)}d.layers=e;for(var q=[],f=0;f<a.layers.length;f++)if("imagelayer"===a.layers[f].type){var r={name:a.layers[f].name,image:a.layers[f].image,x:a.layers[f].x,y:a.layers[f].y,alpha:a.layers[f].opacity,visible:a.layers[f].visible,properties:{}};a.layers[f].properties&&(r.properties=a.layers[f].properties),q.push(r)}d.images=q;for(var s=[],t=[],f=0;f<a.tilesets.length;f++){var u=a.tilesets[f];if(u.image){var v=new c.Tileset(u.name,u.firstgid,u.tilewidth,u.tileheight,u.margin,u.spacing,u.properties);u.tileproperties&&(v.tileProperties=u.tileproperties),v.updateTileData(u.imagewidth,u.imageheight),s.push(v)}else{var w=new c.ImageCollection(u.name,u.firstgid,u.tilewidth,u.tileheight,u.margin,u.spacing,u.properties);for(var f in u.tiles){var r=u.tiles[f].image,k=u.firstgid+parseInt(f,10);w.addImage(k,r)}t.push(w)}}d.tilesets=s,d.imagecollections=t;for(var x={},y={},f=0;f<a.layers.length;f++)if("objectgroup"===a.layers[f].type){x[a.layers[f].name]=[],y[a.layers[f].name]=[];for(var z=0,p=a.layers[f].objects.length;p>z;z++)if(a.layers[f].objects[z].gid){var A={gid:a.layers[f].objects[z].gid,name:a.layers[f].objects[z].name,type:a.layers[f].objects[z].hasOwnProperty("type")?a.layers[f].objects[z].type:"",x:a.layers[f].objects[z].x,y:a.layers[f].objects[z].y,visible:a.layers[f].objects[z].visible,properties:a.layers[f].objects[z].properties};a.layers[f].objects[z].rotation&&(A.rotation=a.layers[f].objects[z].rotation),x[a.layers[f].name].push(A)}else if(a.layers[f].objects[z].polyline){var A={name:a.layers[f].objects[z].name,type:a.layers[f].objects[z].type,x:a.layers[f].objects[z].x,y:a.layers[f].objects[z].y,width:a.layers[f].objects[z].width,height:a.layers[f].objects[z].height,visible:a.layers[f].objects[z].visible,properties:a.layers[f].objects[z].properties};a.layers[f].objects[z].rotation&&(A.rotation=a.layers[f].objects[z].rotation),A.polyline=[];for(var B=0;B<a.layers[f].objects[z].polyline.length;B++)A.polyline.push([a.layers[f].objects[z].polyline[B].x,a.layers[f].objects[z].polyline[B].y]);y[a.layers[f].name].push(A),x[a.layers[f].name].push(A)}else if(a.layers[f].objects[z].polygon){var A=b(a.layers[f].objects[z],["name","type","x","y","visible","rotation","properties"]);A.polygon=[];for(var B=0;B<a.layers[f].objects[z].polygon.length;B++)A.polygon.push([a.layers[f].objects[z].polygon[B].x,a.layers[f].objects[z].polygon[B].y]);x[a.layers[f].name].push(A)}else if(a.layers[f].objects[z].ellipse){var A=b(a.layers[f].objects[z],["name","type","ellipse","x","y","width","height","visible","rotation","properties"]);x[a.layers[f].name].push(A)}else{var A=b(a.layers[f].objects[z],["name","type","x","y","width","height","visible","rotation","properties"]);A.rectangle=!0,x[a.layers[f].name].push(A)}}d.objects=x,d.collision=y,d.tiles=[];for(var f=0;f<d.tilesets.length;f++)for(var u=d.tilesets[f],l=u.tileMargin,C=u.tileMargin,D=0,E=0,F=0,o=u.firstgid;o<u.firstgid+u.total&&(d.tiles[o]=[l,C,f],l+=u.tileWidth+u.tileSpacing,D++,D!==u.total)&&(E++,E!==u.columns||(l=u.tileMargin,C+=u.tileHeight+u.tileSpacing,E=0,F++,F!==u.rows));o++);for(var g,G,H,u,f=0;f<d.layers.length;f++){g=d.layers[f];for(var I=0;I<g.data.length;I++){m=g.data[I];for(var J=0;J<m.length;J++)G=m[J],G.index<0||(H=d.tiles[G.index][2],u=d.tilesets[H],u.tileProperties&&u.tileProperties[G.index-u.firstgid]&&(G.properties=c.Utils.mixin(u.tileProperties[G.index-u.firstgid],G.properties)))}}return d}},c.Tileset=function(a,b,c,d,e,f,g){(void 0===c||0>=c)&&(c=32),(void 0===d||0>=d)&&(d=32),void 0===e&&(e=0),void 0===f&&(f=0),this.name=a,this.firstgid=0|b,this.tileWidth=0|c,this.tileHeight=0|d,this.tileMargin=0|e,this.tileSpacing=0|f,this.properties=g||{},this.image=null,this.rows=0,this.columns=0,this.total=0,this.drawCoords=[]},c.Tileset.prototype={draw:function(a,b,c,d){var e=d-this.firstgid<<1;e>=0&&e+1<this.drawCoords.length&&a.drawImage(this.image,this.drawCoords[e],this.drawCoords[e+1],this.tileWidth,this.tileHeight,b,c,this.tileWidth,this.tileHeight)},containsTileIndex:function(a){return a>=this.firstgid&&a<this.firstgid+this.total},setImage:function(a){this.image=a,this.updateTileData(a.width,a.height)},setSpacing:function(a,b){this.tileMargin=0|a,this.tileSpacing=0|b,this.image&&this.updateTileData(this.image.width,this.image.height)},updateTileData:function(a,b){var c=(b-2*this.tileMargin+this.tileSpacing)/(this.tileHeight+this.tileSpacing),d=(a-2*this.tileMargin+this.tileSpacing)/(this.tileWidth+this.tileSpacing);(c%1!==0||d%1!==0)&&console.warn("Phaser.Tileset - image tile area is not an even multiple of tile size"),c=Math.floor(c),d=Math.floor(d),(this.rows&&this.rows!==c||this.columns&&this.columns!==d)&&console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ"),this.rows=c,this.columns=d,this.total=c*d,this.drawCoords.length=0;for(var e=this.tileMargin,f=this.tileMargin,g=0;g<this.rows;g++){for(var h=0;h<this.columns;h++)this.drawCoords.push(e),this.drawCoords.push(f),e+=this.tileWidth+this.tileSpacing;e=this.tileMargin,f+=this.tileHeight+this.tileSpacing}}},c.Tileset.prototype.constructor=c.Tileset,c.Particles=function(a){this.game=a,this.emitters={},this.ID=0},c.Particles.prototype={add:function(a){return this.emitters[a.name]=a,a},remove:function(a){delete this.emitters[a.name]},update:function(){for(var a in this.emitters)this.emitters[a].exists&&this.emitters[a].update()}},c.Particles.prototype.constructor=c.Particles,c.Particles.Arcade={},c.Particles.Arcade.Emitter=function(a,b,d,e){this.maxParticles=e||50,c.Group.call(this,a),this.name="emitter"+this.game.particles.ID++,this.type=c.EMITTER,this.physicsType=c.GROUP,this.area=new c.Rectangle(b,d,1,1),this.minParticleSpeed=new c.Point(-100,-100),this.maxParticleSpeed=new c.Point(100,100),this.minParticleScale=1,this.maxParticleScale=1,this.scaleData=null,this.minRotation=-360,this.maxRotation=360,this.minParticleAlpha=1,this.maxParticleAlpha=1,this.alphaData=null,this.gravity=100,this.particleClass=c.Particle,this.particleDrag=new c.Point,this.angularDrag=0,this.frequency=100,this.lifespan=2e3,this.bounce=new c.Point,this.on=!1,this.particleAnchor=new c.Point(.5,.5),this.blendMode=c.blendModes.NORMAL,this.emitX=b,this.emitY=d,this.autoScale=!1,this.autoAlpha=!1,this.particleBringToTop=!1,this.particleSendToBack=!1,this._minParticleScale=new c.Point(1,1),this._maxParticleScale=new c.Point(1,1),this._quantity=0,this._timer=0,this._counter=0,this._flowQuantity=0,this._flowTotal=0,this._explode=!0,this._frames=null},c.Particles.Arcade.Emitter.prototype=Object.create(c.Group.prototype),c.Particles.Arcade.Emitter.prototype.constructor=c.Particles.Arcade.Emitter,c.Particles.Arcade.Emitter.prototype.update=function(){if(this.on&&this.game.time.time>=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(var a=0;a<this._flowQuantity;a++)if(this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._quantity>0&&this._counter>=this._quantity&&(this.on=!1));for(var a=this.children.length;a--;)this.children[a].exists&&this.children[a].update()},c.Particles.Arcade.Emitter.prototype.makeParticles=function(a,b,c,d,e){void 0===b&&(b=0),void 0===c&&(c=this.maxParticles),void 0===d&&(d=!1),void 0===e&&(e=!1);var f,g=0,h=a,i=b;for(this._frames=b,c>this.maxParticles&&(this.maxParticles=c);c>g;)Array.isArray(a)&&(h=this.game.rnd.pick(a)),Array.isArray(b)&&(i=this.game.rnd.pick(b)),f=new this.particleClass(this.game,0,0,h,i),this.game.physics.arcade.enable(f,!1),d?(f.body.checkCollision.any=!0,f.body.checkCollision.none=!1):f.body.checkCollision.none=!0,f.body.collideWorldBounds=e,f.body.skipQuadTree=!0,f.exists=!1,f.visible=!1,f.anchor.copyFrom(this.particleAnchor),this.add(f),g++;return this},c.Particles.Arcade.Emitter.prototype.kill=function(){this.on=!1,this.alive=!1,this.exists=!1},c.Particles.Arcade.Emitter.prototype.revive=function(){this.alive=!0,this.exists=!0},c.Particles.Arcade.Emitter.prototype.explode=function(a,b){this._flowTotal=0,this.start(!0,a,0,b,!1)},c.Particles.Arcade.Emitter.prototype.flow=function(a,b,c,d,e){(void 0===c||0===c)&&(c=1),void 0===d&&(d=-1),void 0===e&&(e=!0),c>this.maxParticles&&(c=this.maxParticles),this._counter=0,this._flowQuantity=c,this._flowTotal=d,e?(this.start(!0,a,b,c),this._counter+=c,this.on=!0,this._timer=this.game.time.time+b*this.game.time.slowMotion):this.start(!1,a,b,c)},c.Particles.Arcade.Emitter.prototype.start=function(a,b,c,d,e){if(void 0===a&&(a=!0),void 0===b&&(b=0),(void 0===c||null===c)&&(c=250),void 0===d&&(d=0),void 0===e&&(e=!1),d>this.maxParticles&&(d=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=b,this.frequency=c,a||e)for(var f=0;d>f;f++)this.emitParticle();else this.on=!0,this._quantity+=d,this._counter=0,this._timer=this.game.time.time+c*this.game.time.slowMotion},c.Particles.Arcade.Emitter.prototype.emitParticle=function(){var a=this.getFirstExists(!1);return null===a?!1:(this.width>1||this.height>1?a.reset(this.game.rnd.integerInRange(this.left,this.right),this.game.rnd.integerInRange(this.top,this.bottom)):a.reset(this.emitX,this.emitY),a.angle=0,a.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(a):this.particleSendToBack&&this.sendToBack(a),this.autoScale?a.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?a.scale.set(this.game.rnd.realInRange(this.minParticleScale,this.maxParticleScale)):(this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y)&&a.scale.set(this.game.rnd.realInRange(this._minParticleScale.x,this._maxParticleScale.x),this.game.rnd.realInRange(this._minParticleScale.y,this._maxParticleScale.y)),a.frame=Array.isArray("object"===this._frames)?this.game.rnd.pick(this._frames):this._frames,this.autoAlpha?a.setAlphaData(this.alphaData):a.alpha=this.game.rnd.realInRange(this.minParticleAlpha,this.maxParticleAlpha),a.blendMode=this.blendMode,a.body.updateBounds(),a.body.bounce.setTo(this.bounce.x,this.bounce.y),a.body.velocity.x=this.game.rnd.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),a.body.velocity.y=this.game.rnd.between(this.minParticleSpeed.y,this.maxParticleSpeed.y),a.body.angularVelocity=this.game.rnd.between(this.minRotation,this.maxRotation),a.body.gravity.y=this.gravity,a.body.drag.x=this.particleDrag.x,a.body.drag.y=this.particleDrag.y,a.body.angularDrag=this.angularDrag,a.onEmit(),!0)},c.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),c.Group.prototype.destroy.call(this,!0,!1)},c.Particles.Arcade.Emitter.prototype.setSize=function(a,b){this.area.width=a,this.area.height=b},c.Particles.Arcade.Emitter.prototype.setXSpeed=function(a,b){a=a||0,b=b||0,this.minParticleSpeed.x=a,this.maxParticleSpeed.x=b},c.Particles.Arcade.Emitter.prototype.setYSpeed=function(a,b){a=a||0,b=b||0,this.minParticleSpeed.y=a,this.maxParticleSpeed.y=b},c.Particles.Arcade.Emitter.prototype.setRotation=function(a,b){a=a||0,b=b||0,this.minRotation=a,this.maxRotation=b},c.Particles.Arcade.Emitter.prototype.setAlpha=function(a,b,d,e,f){if(void 0===a&&(a=1),void 0===b&&(b=1),void 0===d&&(d=0),void 0===e&&(e=c.Easing.Linear.None),void 0===f&&(f=!1),this.minParticleAlpha=a,this.maxParticleAlpha=b,this.autoAlpha=!1,d>0&&a!==b){var g={v:a},h=this.game.make.tween(g).to({v:b},d,e);h.yoyo(f),this.alphaData=h.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}},c.Particles.Arcade.Emitter.prototype.setScale=function(a,b,d,e,f,g,h){if(void 0===a&&(a=1),void 0===b&&(b=1),void 0===d&&(d=1),void 0===e&&(e=1),void 0===f&&(f=0),void 0===g&&(g=c.Easing.Linear.None),void 0===h&&(h=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(a,d),this._maxParticleScale.set(b,e),this.autoScale=!1,f>0&&(a!==b||d!==e)){var i={x:a,y:d},j=this.game.make.tween(i).to({x:b,y:e},f,g);j.yoyo(h),this.scaleData=j.generateData(60),this.scaleData.reverse(),this.autoScale=!0}},c.Particles.Arcade.Emitter.prototype.at=function(a){a.center?(this.emitX=a.center.x,this.emitY=a.center.y):(this.emitX=a.world.x+a.anchor.x*a.width,this.emitY=a.world.y+a.anchor.y*a.height)},Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(a){this.area.width=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(a){this.area.height=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(a){this.emitX=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(a){this.emitY=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),c.Video=function(a,b,d){if(void 0===b&&(b=null),void 0===d&&(d=null),this.game=a,this.key=b,this.width=0,this.height=0,this.type=c.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new c.Signal,this.onChangeSource=new c.Signal,this.onComplete=new c.Signal,this.onAccess=new c.Signal,this.onError=new c.Signal,this.onTimeout=new c.Signal,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._autoplay=!1,b&&this.game.cache.checkVideoKey(b)){var e=this.game.cache.getVideo(b);e.isBlob?this.createVideoFromBlob(e.data):this.video=e.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else d&&this.createVideoFromURL(d,!1);this.video&&!d?(this.baseTexture=new PIXI.BaseTexture(this.video),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(PIXI.TextureCache.__default.baseTexture.source),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new c.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==b&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,c.BitmapData&&(this.snapshot=new c.BitmapData(this.game,"",this.width,this.height)),!this.game.device.cocoonJS&&(this.game.device.iOS||this.game.device.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock?this.setTouchLock():e&&(e.locked=!1)},c.Video.prototype={connectToMediaStream:function(a,b){return a&&b&&(this.video=a,this.videoStream=b,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(a,b,c){if(void 0===a&&(a=!1),void 0===b&&(b=null),void 0===c&&(c=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&this.videoStream.stop(),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==b&&(this.video.width=b),null!==c&&(this.video.height=c),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:a,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(d){this.getUserMediaError(d)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(a){clearTimeout(this._timeOutID),this.onError.dispatch(this,a)},getUserMediaSuccess:function(a){clearTimeout(this._timeOutID),this.videoStream=a,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=a:this.video.src=window.URL&&window.URL.createObjectURL(a)||a;var b=this;this.video.onloadeddata=function(){function a(){if(c>0)if(b.video.videoWidth>0){var d=b.video.videoWidth,e=b.video.videoHeight;isNaN(b.video.videoHeight)&&(e=d/(4/3)),b.video.play(),b.isStreaming=!0,b.baseTexture.source=b.video,b.updateTexture(null,d,e),b.onAccess.dispatch(b)}else window.setTimeout(a,500);else console.warn("Unable to connect to video stream. Webcam error?");c--}var c=10;a()}},createVideoFromBlob:function(a){var b=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(a){b.updateTexture(a)},!0),this.video.src=window.URL.createObjectURL(a),this.video.canplay=!0,this},createVideoFromURL:function(a,b){return void 0===b&&(b=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,b&&this.video.setAttribute("autoplay","autoplay"),this.video.src=a,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=a,this},updateTexture:function(a,b,c){var d=!1;(void 0===b||null===b)&&(b=this.video.videoWidth,d=!0),(void 0===c||null===c)&&(c=this.video.videoHeight),this.width=b,this.height=c,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(b,c),this.texture.frame.resize(b,c),this.texture.width=b,this.texture.height=c,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(b,c),d&&null!==this.key&&(this.onChangeSource.dispatch(this,b,c),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(a,b){return void 0===a&&(a=!1),void 0===b&&(b=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this.video.addEventListener("ended",this.complete.bind(this),!0),this.video.loop=a?"loop":"",this.video.playbackRate=b,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):this.video.addEventListener("playing",this.playHandler.bind(this),!0)),this.video.play(),this.onPlay.dispatch(this,a,b)),this},playHandler:function(){this.video.removeEventListener("playing",this.playHandler.bind(this)),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this.complete.bind(this)),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(a){if(Array.isArray(a))for(var b=0;b<a.length;b++)a[b].loadTexture&&a[b].loadTexture(this);else a.loadTexture(this);return this},addToWorld:function(a,b,c,d,e,f){e=e||1,f=f||1;var g=this.game.add.image(a,b,this);return g.anchor.set(c,d),g.scale.set(e,f),g},render:function(){!this.disableTextureUpload&&this.playing&&this.baseTexture.dirty()},setMute:function(){this._muted||(this._muted=!0,this.video.muted=!0)},unsetMute:function(){this._muted&&!this._codeMuted&&(this._muted=!1,this.video.muted=!1)},setPause:function(){this._paused||this.touchLocked||(this._paused=!0,this.video.pause())},setResume:function(){!this._paused||this._codePaused||this.touchLocked||(this._paused=!1,this.video.ended||this.video.play())},changeSource:function(a,b){return void 0===b&&(b=!0),this.texture.valid=!1,this.video.pause(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.video.src=a,this.video.load(),this._autoplay=b,b||(this.paused=!0),this},checkVideoProgress:function(){4===this.video.readyState?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming))},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate),this.key){var a=this.game.cache.getVideo(this.key);a&&!a.isBlob&&(a.locked=!1)}return!0},grab:function(a,b,c){return void 0===a&&(a=!1),void 0===b&&(b=1),void 0===c&&(c=null),null===this.snapshot?void console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable"):(a&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,b,c),this.snapshot)},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(c.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(a){this.video.currentTime=a}}),Object.defineProperty(c.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(c.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(c.Video.prototype,"mute",{get:function(){return this._muted},set:function(a){if(a=a||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(c.Video.prototype,"paused",{get:function(){return this._paused},set:function(a){if(a=a||null,!this.touchLocked)if(a){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(c.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(a){0>a?a=0:a>1&&(a=1),this.video&&(this.video.volume=a)}}),Object.defineProperty(c.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(a){this.video&&(this.video.playbackRate=a)}}),Object.defineProperty(c.Video.prototype,"loop",{get:function(){return this.video?this.video.loop:!1},set:function(a){a&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(c.Video.prototype,"playing",{get:function(){return!(this.video.paused&&this.video.ended)}}),c.Video.prototype.constructor=c.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=c.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=c.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new PIXI.Matrix),void 0===PIXI.RenderTexture.tempMatrix&&(PIXI.RenderTexture.tempMatrix=new PIXI.Matrix),void 0===PIXI.Graphics.POLY&&(PIXI.Graphics.POLY=c.POLYGON,PIXI.Graphics.RECT=c.RECTANGLE,PIXI.Graphics.CIRC=c.CIRCLE,PIXI.Graphics.ELIP=c.ELLIPSE,PIXI.Graphics.RREC=c.ROUNDEDRECTANGLE),PIXI.TextureSilentFail=!0,"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=c),exports.Phaser=c):"undefined"!=typeof define&&define.amd?define("Phaser",function(){return b.Phaser=c}()):b.Phaser=c,c}.call(this);
-//# sourceMappingURL=phaser.map
\ No newline at end of file
diff --git a/js/phaser/phaser.js b/js/phaser/phaser.js
new file mode 100644
index 0000000..ede24af
--- /dev/null
+++ b/js/phaser/phaser.js
@@ -0,0 +1,95198 @@
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*
+* @overview
+*
+* Phaser - http://phaser.io
+*
+* v2.4.2 "Altara" - Built: Wed Jul 29 2015 14:59:16
+*
+* By Richard Davey http://www.photonstorm.com @photonstorm
+*
+* Phaser is a fun, free and fast 2D game framework for making HTML5 games
+* for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
+*
+* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
+* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
+* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
+*
+* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser
+* and my love of framework development originate.
+*
+* Follow development at http://phaser.io and on our forum
+*
+* "If you want your children to be intelligent,  read them fairy tales."
+* "If you want them to be more intelligent, read them more fairy tales."
+*                                                     -- Albert Einstein
+*/
+
+/**
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2015 p2.js authors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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(_dereq_,module,exports){
+var Scalar = _dereq_('./Scalar');
+
+module.exports = Line;
+
+/**
+ * Container for line-related functions
+ * @class Line
+ */
+function Line(){};
+
+/**
+ * Compute the intersection between two lines.
+ * @static
+ * @method lineInt
+ * @param  {Array}  l1          Line vector 1
+ * @param  {Array}  l2          Line vector 2
+ * @param  {Number} precision   Precision to use when checking if the lines are parallel
+ * @return {Array}              The intersection point.
+ */
+Line.lineInt = function(l1,l2,precision){
+    precision = precision || 0;
+    var i = [0,0]; // point
+    var a1, b1, c1, a2, b2, c2, det; // scalars
+    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)) { // lines are not parallel
+        i[0] = (b2 * c1 - b1 * c2) / det;
+        i[1] = (a1 * c2 - a2 * c1) / det;
+    }
+    return i;
+};
+
+/**
+ * Checks if two line segments intersects.
+ * @method segmentsIntersect
+ * @param {Array} p1 The start vertex of the first line segment.
+ * @param {Array} p2 The end vertex of the first line segment.
+ * @param {Array} q1 The start vertex of the second line segment.
+ * @param {Array} q2 The end vertex of the second line segment.
+ * @return {Boolean} True if the two line segments intersect
+ */
+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];
+
+   // segments are parallel
+   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(_dereq_,module,exports){
+module.exports = Point;
+
+/**
+ * Point related functions
+ * @class Point
+ */
+function Point(){};
+
+/**
+ * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order.
+ * @static
+ * @method area
+ * @param  {Array} a
+ * @param  {Array} b
+ * @param  {Array} c
+ * @return {Number}
+ */
+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 = [];
+
+/**
+ * Check if three points are collinear
+ * @method collinear
+ * @param  {Array} a
+ * @param  {Array} b
+ * @param  {Array} c
+ * @param  {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision.
+ * @return {Boolean}
+ */
+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(_dereq_,module,exports){
+var Line = _dereq_("./Line")
+,   Point = _dereq_("./Point")
+,   Scalar = _dereq_("./Scalar")
+
+module.exports = Polygon;
+
+/**
+ * Polygon class.
+ * @class Polygon
+ * @constructor
+ */
+function Polygon(){
+
+    /**
+     * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..]
+     * @property vertices
+     * @type {Array}
+     */
+    this.vertices = [];
+}
+
+/**
+ * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle.
+ * @method at
+ * @param  {Number} i
+ * @return {Array}
+ */
+Polygon.prototype.at = function(i){
+    var v = this.vertices,
+        s = v.length;
+    return v[i < 0 ? i % s + s : i % s];
+};
+
+/**
+ * Get first vertex
+ * @method first
+ * @return {Array}
+ */
+Polygon.prototype.first = function(){
+    return this.vertices[0];
+};
+
+/**
+ * Get last vertex
+ * @method last
+ * @return {Array}
+ */
+Polygon.prototype.last = function(){
+    return this.vertices[this.vertices.length-1];
+};
+
+/**
+ * Clear the polygon data
+ * @method clear
+ * @return {Array}
+ */
+Polygon.prototype.clear = function(){
+    this.vertices.length = 0;
+};
+
+/**
+ * Append points "from" to "to"-1 from an other polygon "poly" onto this one.
+ * @method append
+ * @param {Polygon} poly The polygon to get points from.
+ * @param {Number}  from The vertex index in "poly".
+ * @param {Number}  to The end vertex index in "poly". Note that this vertex is NOT included when appending.
+ * @return {Array}
+ */
+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]);
+    }
+};
+
+/**
+ * Make sure that the polygon vertices are ordered counter-clockwise.
+ * @method makeCCW
+ */
+Polygon.prototype.makeCCW = function(){
+    var br = 0,
+        v = this.vertices;
+
+    // find bottom right point
+    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;
+        }
+    }
+
+    // reverse poly if clockwise
+    if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) {
+        this.reverse();
+    }
+};
+
+/**
+ * Reverse the vertices in the polygon
+ * @method 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;
+};
+
+/**
+ * Check if a point in the polygon is a reflex point
+ * @method isReflex
+ * @param  {Number}  i
+ * @return {Boolean}
+ */
+Polygon.prototype.isReflex = function(i){
+    return Point.right(this.at(i - 1), this.at(i), this.at(i + 1));
+};
+
+var tmpLine1=[],
+    tmpLine2=[];
+
+/**
+ * Check if two vertices in the polygon can see each other
+ * @method canSee
+ * @param  {Number} a Vertex index 1
+ * @param  {Number} b Vertex index 2
+ * @return {Boolean}
+ */
+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) { // for each edge
+        if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges
+            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))) { // if diag intersects an edge
+            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) { // if edge is blocking visibility to b
+                return false;
+            }
+        }
+    }
+
+    return true;
+};
+
+/**
+ * Copy the polygon from vertex i to vertex j.
+ * @method copy
+ * @param  {Number} i
+ * @param  {Number} j
+ * @param  {Polygon} [targetPoly]   Optional target polygon to save in.
+ * @return {Polygon}                The resulting copy.
+ */
+Polygon.prototype.copy = function(i,j,targetPoly){
+    var p = targetPoly || new Polygon();
+    p.clear();
+    if (i < j) {
+        // Insert all vertices from i to j
+        for(var k=i; k<=j; k++)
+            p.vertices.push(this.vertices[k]);
+
+    } else {
+
+        // Insert vertices 0 to j
+        for(var k=0; k<=j; k++)
+            p.vertices.push(this.vertices[k]);
+
+        // Insert vertices i to end
+        for(var k=i; k<this.vertices.length; k++)
+            p.vertices.push(this.vertices[k]);
+    }
+
+    return p;
+};
+
+/**
+ * Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon.
+ * Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices.
+ * @method getCutEdges
+ * @return {Array}
+ */
+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;
+};
+
+/**
+ * Decomposes the polygon into one or more convex sub-Polygons.
+ * @method decomp
+ * @return {Array} An array or Polygon objects.
+ */
+Polygon.prototype.decomp = function(){
+    var edges = this.getCutEdges();
+    if(edges.length > 0)
+        return this.slice(edges);
+    else
+        return [this];
+};
+
+/**
+ * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons.
+ * @method slice
+ * @param {Array} cutEdges A list of edges, as returned by .getCutEdges()
+ * @return {Array}
+ */
+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];
+            // Cut all polys
+            for(var j=0; j<polys.length; j++){
+                var poly = polys[j];
+                var result = poly.slice(cutEdge);
+                if(result){
+                    // Found poly! Cut and quit
+                    polys.splice(j,1);
+                    polys.push(result[0],result[1]);
+                    break;
+                }
+            }
+        }
+
+        return polys;
+    } else {
+
+        // Was given one edge
+        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;
+        }
+    }
+};
+
+/**
+ * Checks that the line segments of this polygon do not intersect each other.
+ * @method isSimple
+ * @param  {Array} path An array of vertices e.g. [[0,0],[0,1],...]
+ * @return {Boolean}
+ * @todo Should it check all segments with all others?
+ */
+Polygon.prototype.isSimple = function(){
+    var path = this.vertices;
+    // Check
+    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;
+            }
+        }
+    }
+
+    // Check the segment between the last and the first point to all others
+    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]
+}
+
+/**
+ * Quickly decompose the Polygon into convex sub-polygons.
+ * @method quickDecomp
+ * @param  {Array} result
+ * @param  {Array} [reflexVertices]
+ * @param  {Array} [steinerPoints]
+ * @param  {Number} [delta]
+ * @param  {Number} [maxlevel]
+ * @param  {Number} [level]
+ * @return {Array}
+ */
+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]; // Points
+    var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars
+    var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers
+    var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons
+    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))) { // if line intersects with an edge
+                    p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection
+                    if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly
+                        d = Point.sqdist(poly.vertices[i], p);
+                        if (d < lowerDist) { // keep only the closest intersection
+                            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 there are no vertices to connect to, choose a point in the middle
+            if (lowerIndex == (upperIndex + 1) % this.vertices.length) {
+                //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")");
+                p[0] = (lowerInt[0] + upperInt[0]) / 2;
+                p[1] = (lowerInt[1] + upperInt[1]) / 2;
+                steinerPoints.push(p);
+
+                if (i < upperIndex) {
+                    //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1);
+                    lowerPoly.append(poly, i, upperIndex+1);
+                    lowerPoly.vertices.push(p);
+                    upperPoly.vertices.push(p);
+                    if (lowerIndex != 0){
+                        //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end());
+                        upperPoly.append(poly,lowerIndex,poly.vertices.length);
+                    }
+                    //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
+                    upperPoly.append(poly,0,i+1);
+                } else {
+                    if (i != 0){
+                        //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
+                        lowerPoly.append(poly,i,poly.vertices.length);
+                    }
+                    //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1);
+                    lowerPoly.append(poly,0,upperIndex+1);
+                    lowerPoly.vertices.push(p);
+                    upperPoly.vertices.push(p);
+                    //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1);
+                    upperPoly.append(poly,lowerIndex,i+1);
+                }
+            } else {
+                // connect to the closest point within the triangle
+                //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n");
+
+                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);
+                }
+            }
+
+            // solve smallest poly first
+            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;
+};
+
+/**
+ * Remove collinear points in the polygon.
+ * @method removeCollinearPoints
+ * @param  {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision.
+ * @return {Number}           The number of points removed
+ */
+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)){
+            // Remove the middle point
+            this.vertices.splice(i%this.vertices.length,1);
+            i--; // Jump one point forward. Otherwise we may get a chain removal
+            num++;
+        }
+    }
+    return num;
+};
+
+},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){
+module.exports = Scalar;
+
+/**
+ * Scalar functions
+ * @class Scalar
+ */
+function Scalar(){}
+
+/**
+ * Check if two scalars are equal
+ * @static
+ * @method eq
+ * @param  {Number} a
+ * @param  {Number} b
+ * @param  {Number} [precision]
+ * @return {Boolean}
+ */
+Scalar.eq = function(a,b,precision){
+    precision = precision || 0;
+    return Math.abs(a-b) < precision;
+};
+
+},{}],5:[function(_dereq_,module,exports){
+module.exports = {
+    Polygon : _dereq_("./Polygon"),
+    Point : _dereq_("./Point"),
+};
+
+},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){
+module.exports={
+  "name": "p2",
+  "version": "0.7.0",
+  "description": "A JavaScript 2D physics engine.",
+  "author": "Stefan Hedman <schteppe@gmail.com> (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.0"
+  }
+}
+
+},{}],7:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   Utils = _dereq_('../utils/Utils');
+
+module.exports = AABB;
+
+/**
+ * Axis aligned bounding box class.
+ * @class AABB
+ * @constructor
+ * @param {Object}  [options]
+ * @param {Array}   [options.upperBound]
+ * @param {Array}   [options.lowerBound]
+ */
+function AABB(options){
+
+    /**
+     * The lower bound of the bounding box.
+     * @property lowerBound
+     * @type {Array}
+     */
+    this.lowerBound = vec2.create();
+    if(options && options.lowerBound){
+        vec2.copy(this.lowerBound, options.lowerBound);
+    }
+
+    /**
+     * The upper bound of the bounding box.
+     * @property upperBound
+     * @type {Array}
+     */
+    this.upperBound = vec2.create();
+    if(options && options.upperBound){
+        vec2.copy(this.upperBound, options.upperBound);
+    }
+}
+
+var tmp = vec2.create();
+
+/**
+ * Set the AABB bounds from a set of points, transformed by the given position and angle.
+ * @method setFromPoints
+ * @param {Array} points An array of vec2's.
+ * @param {Array} position
+ * @param {number} angle
+ * @param {number} skinSize Some margin to be added to the AABB.
+ */
+AABB.prototype.setFromPoints = function(points, position, angle, skinSize){
+    var l = this.lowerBound,
+        u = this.upperBound;
+
+    if(typeof(angle) !== "number"){
+        angle = 0;
+    }
+
+    // Set to the first point
+    if(angle !== 0){
+        vec2.rotate(l, points[0], angle);
+    } else {
+        vec2.copy(l, points[0]);
+    }
+    vec2.copy(u, l);
+
+    // Compute cosines and sines just once
+    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];
+            }
+        }
+    }
+
+    // Add offset
+    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;
+    }
+};
+
+/**
+ * Copy bounds from an AABB to this AABB
+ * @method copy
+ * @param  {AABB} aabb
+ */
+AABB.prototype.copy = function(aabb){
+    vec2.copy(this.lowerBound, aabb.lowerBound);
+    vec2.copy(this.upperBound, aabb.upperBound);
+};
+
+/**
+ * Extend this AABB so that it covers the given AABB too.
+ * @method extend
+ * @param  {AABB} aabb
+ */
+AABB.prototype.extend = function(aabb){
+    // Loop over x and y
+    var i = 2;
+    while(i--){
+        // Extend lower bound
+        var l = aabb.lowerBound[i];
+        if(this.lowerBound[i] > l){
+            this.lowerBound[i] = l;
+        }
+
+        // Upper
+        var u = aabb.upperBound[i];
+        if(this.upperBound[i] < u){
+            this.upperBound[i] = u;
+        }
+    }
+};
+
+/**
+ * Returns true if the given AABB overlaps this AABB.
+ * @method overlaps
+ * @param  {AABB} aabb
+ * @return {Boolean}
+ */
+AABB.prototype.overlaps = function(aabb){
+    var l1 = this.lowerBound,
+        u1 = this.upperBound,
+        l2 = aabb.lowerBound,
+        u2 = aabb.upperBound;
+
+    //      l2        u2
+    //      |---------|
+    // |--------|
+    // l1       u1
+
+    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]));
+};
+
+/**
+ * @method containsPoint
+ * @param  {Array} point
+ * @return {boolean}
+ */
+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];
+};
+
+/**
+ * Check if the AABB is hit by a ray.
+ * @method overlapsRay
+ * @param  {Ray} ray
+ * @return {number} -1 if no hit, a number between 0 and 1 if hit.
+ */
+AABB.prototype.overlapsRay = function(ray){
+    var t = 0;
+
+    // ray.direction is unit direction vector of ray
+    var dirFracX = 1 / ray.direction[0];
+    var dirFracY = 1 / ray.direction[1];
+
+    // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
+    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, ray (line) is intersecting AABB, but whole AABB is behing us
+    if (tmax < 0){
+        //t = tmax;
+        return -1;
+    }
+
+    // if tmin > tmax, ray doesn't intersect AABB
+    if (tmin > tmax){
+        //t = tmax;
+        return -1;
+    }
+
+    return tmin;
+};
+},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2');
+var Body = _dereq_('../objects/Body');
+
+module.exports = Broadphase;
+
+/**
+ * Base class for broadphase implementations.
+ * @class Broadphase
+ * @constructor
+ */
+function Broadphase(type){
+
+    this.type = type;
+
+    /**
+     * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs().
+     * @property result
+     * @type {Array}
+     */
+    this.result = [];
+
+    /**
+     * The world to search for collision pairs in. To change it, use .setWorld()
+     * @property world
+     * @type {World}
+     * @readOnly
+     */
+    this.world = null;
+
+    /**
+     * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE.
+     * @property {Number} boundingVolumeType
+     */
+    this.boundingVolumeType = Broadphase.AABB;
+}
+
+/**
+ * Axis aligned bounding box type.
+ * @static
+ * @property {Number} AABB
+ */
+Broadphase.AABB = 1;
+
+/**
+ * Bounding circle type.
+ * @static
+ * @property {Number} BOUNDING_CIRCLE
+ */
+Broadphase.BOUNDING_CIRCLE = 2;
+
+/**
+ * Set the world that we are searching for collision pairs in.
+ * @method setWorld
+ * @param  {World} world
+ */
+Broadphase.prototype.setWorld = function(world){
+    this.world = world;
+};
+
+/**
+ * Get all potential intersecting body pairs.
+ * @method getCollisionPairs
+ * @param  {World} world The world to search in.
+ * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d).
+ */
+Broadphase.prototype.getCollisionPairs = function(world){};
+
+var dist = vec2.create();
+
+/**
+ * Check whether the bounding radius of two bodies overlap.
+ * @method  boundingRadiusCheck
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {Boolean}
+ */
+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;
+};
+
+/**
+ * Check whether the bounding radius of two bodies overlap.
+ * @method  boundingRadiusCheck
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {Boolean}
+ */
+Broadphase.aabbCheck = function(bodyA, bodyB){
+    return bodyA.getAABB().overlaps(bodyB.getAABB());
+};
+
+/**
+ * Check whether the bounding radius of two bodies overlap.
+ * @method  boundingRadiusCheck
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {Boolean}
+ */
+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;
+};
+
+/**
+ * Check whether two bodies are allowed to collide at all.
+ * @method  canCollide
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {Boolean}
+ */
+Broadphase.canCollide = function(bodyA, bodyB){
+    var KINEMATIC = Body.KINEMATIC;
+    var STATIC = Body.STATIC;
+
+    // Cannot collide static bodies
+    if(bodyA.type === STATIC && bodyB.type === STATIC){
+        return false;
+    }
+
+    // Cannot collide static vs kinematic bodies
+    if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) ||
+        (bodyA.type === STATIC    && bodyB.type === KINEMATIC)){
+        return false;
+    }
+
+    // Cannot collide kinematic vs kinematic
+    if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){
+        return false;
+    }
+
+    // Cannot collide both sleeping bodies
+    if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){
+        return false;
+    }
+
+    // Cannot collide if one is static and the other is sleeping
+    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(_dereq_,module,exports){
+var Circle = _dereq_('../shapes/Circle'),
+    Plane = _dereq_('../shapes/Plane'),
+    Shape = _dereq_('../shapes/Shape'),
+    Particle = _dereq_('../shapes/Particle'),
+    Broadphase = _dereq_('../collision/Broadphase'),
+    vec2 = _dereq_('../math/vec2');
+
+module.exports = NaiveBroadphase;
+
+/**
+ * Naive broadphase implementation. Does N^2 tests.
+ *
+ * @class NaiveBroadphase
+ * @constructor
+ * @extends Broadphase
+ */
+function NaiveBroadphase(){
+    Broadphase.call(this, Broadphase.NAIVE);
+}
+NaiveBroadphase.prototype = new Broadphase();
+NaiveBroadphase.prototype.constructor = NaiveBroadphase;
+
+/**
+ * Get the colliding pairs
+ * @method getCollisionPairs
+ * @param  {World} world
+ * @return {Array}
+ */
+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;
+};
+
+/**
+ * Returns all the bodies within an AABB.
+ * @method aabbQuery
+ * @param  {World} world
+ * @param  {AABB} aabb
+ * @param {array} result An array to store resulting bodies in.
+ * @return {array}
+ */
+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":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   sub = vec2.sub
+,   add = vec2.add
+,   dot = vec2.dot
+,   Utils = _dereq_('../utils/Utils')
+,   ContactEquationPool = _dereq_('../utils/ContactEquationPool')
+,   FrictionEquationPool = _dereq_('../utils/FrictionEquationPool')
+,   TupleDictionary = _dereq_('../utils/TupleDictionary')
+,   Equation = _dereq_('../equations/Equation')
+,   ContactEquation = _dereq_('../equations/ContactEquation')
+,   FrictionEquation = _dereq_('../equations/FrictionEquation')
+,   Circle = _dereq_('../shapes/Circle')
+,   Convex = _dereq_('../shapes/Convex')
+,   Shape = _dereq_('../shapes/Shape')
+,   Body = _dereq_('../objects/Body')
+,   Box = _dereq_('../shapes/Box');
+
+module.exports = Narrowphase;
+
+// Temp things
+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 = [];
+
+/**
+ * Narrowphase. Creates contacts and friction given shapes and transforms.
+ * @class Narrowphase
+ * @constructor
+ */
+function Narrowphase(){
+
+    /**
+     * @property contactEquations
+     * @type {Array}
+     */
+    this.contactEquations = [];
+
+    /**
+     * @property frictionEquations
+     * @type {Array}
+     */
+    this.frictionEquations = [];
+
+    /**
+     * Whether to make friction equations in the upcoming contacts.
+     * @property enableFriction
+     * @type {Boolean}
+     */
+    this.enableFriction = true;
+
+    /**
+     * Whether to make equations enabled in upcoming contacts.
+     * @property enabledEquations
+     * @type {Boolean}
+     */
+    this.enabledEquations = true;
+
+    /**
+     * The friction slip force to use when creating friction equations.
+     * @property slipForce
+     * @type {Number}
+     */
+    this.slipForce = 10.0;
+
+    /**
+     * The friction value to use in the upcoming friction equations.
+     * @property frictionCoefficient
+     * @type {Number}
+     */
+    this.frictionCoefficient = 0.3;
+
+    /**
+     * Will be the .relativeVelocity in each produced FrictionEquation.
+     * @property {Number} surfaceVelocity
+     */
+    this.surfaceVelocity = 0;
+
+    /**
+     * Keeps track of the allocated ContactEquations.
+     * @property {ContactEquationPool} contactEquationPool
+     *
+     * @example
+     *
+     *     // Allocate a few equations before starting the simulation.
+     *     // This way, no contact objects need to be created on the fly in the game loop.
+     *     world.narrowphase.contactEquationPool.resize(1024);
+     *     world.narrowphase.frictionEquationPool.resize(1024);
+     */
+    this.contactEquationPool = new ContactEquationPool({ size: 32 });
+
+    /**
+     * Keeps track of the allocated ContactEquations.
+     * @property {FrictionEquationPool} frictionEquationPool
+     */
+    this.frictionEquationPool = new FrictionEquationPool({ size: 64 });
+
+    /**
+     * The restitution value to use in the next contact equations.
+     * @property restitution
+     * @type {Number}
+     */
+    this.restitution = 0;
+
+    /**
+     * The stiffness value to use in the next contact equations.
+     * @property {Number} stiffness
+     */
+    this.stiffness = Equation.DEFAULT_STIFFNESS;
+
+    /**
+     * The stiffness value to use in the next contact equations.
+     * @property {Number} stiffness
+     */
+    this.relaxation = Equation.DEFAULT_RELAXATION;
+
+    /**
+     * The stiffness value to use in the next friction equations.
+     * @property frictionStiffness
+     * @type {Number}
+     */
+    this.frictionStiffness = Equation.DEFAULT_STIFFNESS;
+
+    /**
+     * The relaxation value to use in the next friction equations.
+     * @property frictionRelaxation
+     * @type {Number}
+     */
+    this.frictionRelaxation = Equation.DEFAULT_RELAXATION;
+
+    /**
+     * Enable reduction of friction equations. If disabled, a box on a plane will generate 2 contact equations and 2 friction equations. If enabled, there will be only one friction equation. Same kind of simplifications are made  for all collision types.
+     * @property enableFrictionReduction
+     * @type {Boolean}
+     * @deprecated This flag will be removed when the feature is stable enough.
+     * @default true
+     */
+    this.enableFrictionReduction = true;
+
+    /**
+     * Keeps track of the colliding bodies last step.
+     * @private
+     * @property collidingBodiesLastStep
+     * @type {TupleDictionary}
+     */
+    this.collidingBodiesLastStep = new TupleDictionary();
+
+    /**
+     * Contact skin size value to use in the next contact equations.
+     * @property {Number} contactSkinSize
+     * @default 0.01
+     */
+    this.contactSkinSize = 0.01;
+}
+
+var bodiesOverlap_shapePositionA = vec2.create();
+var bodiesOverlap_shapePositionB = vec2.create();
+
+/**
+ * @method bodiesOverlap
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {Boolean}
+ * @todo shape world transforms are wrong
+ */
+Narrowphase.prototype.bodiesOverlap = function(bodyA, bodyB){
+    var shapePositionA = bodiesOverlap_shapePositionA;
+    var shapePositionB = bodiesOverlap_shapePositionB;
+
+    // Loop over all shapes of bodyA
+    for(var k=0, Nshapesi=bodyA.shapes.length; k!==Nshapesi; k++){
+        var shapeA = bodyA.shapes[k];
+
+        bodyA.toWorldFrame(shapePositionA, shapeA.position);
+
+        // All shapes of body j
+        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;
+};
+
+/**
+ * Check if the bodies were in contact since the last reset().
+ * @method collidedLastStep
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {Boolean}
+ */
+Narrowphase.prototype.collidedLastStep = function(bodyA, bodyB){
+    var id1 = bodyA.id|0,
+        id2 = bodyB.id|0;
+    return !!this.collidingBodiesLastStep.get(id1, id2);
+};
+
+/**
+ * Throws away the old equations and gets ready to create new
+ * @method reset
+ */
+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]);
+    }
+
+    // Reset
+    this.contactEquations.length = this.frictionEquations.length = 0;
+};
+
+/**
+ * Creates a ContactEquation, either by reusing an existing object or creating a new one.
+ * @method createContactEquation
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {ContactEquation}
+ */
+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;
+};
+
+/**
+ * Creates a FrictionEquation, either by reusing an existing object or creating a new one.
+ * @method createFrictionEquation
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {FrictionEquation}
+ */
+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;
+};
+
+/**
+ * Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal.
+ * @method createFrictionFromContact
+ * @param  {ContactEquation} contactEquation
+ * @return {FrictionEquation}
+ */
+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;
+};
+
+// Take the average N latest contact point on the plane.
+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;
+};
+
+/**
+ * Convex/line narrowphase
+ * @method convexLine
+ * @param  {Body}       convexBody
+ * @param  {Convex}     convexShape
+ * @param  {Array}      convexOffset
+ * @param  {Number}     convexAngle
+ * @param  {Body}       lineBody
+ * @param  {Line}       lineShape
+ * @param  {Array}      lineOffset
+ * @param  {Number}     lineAngle
+ * @param {boolean}     justTest
+ * @todo Implement me!
+ */
+Narrowphase.prototype[Shape.LINE | Shape.CONVEX] =
+Narrowphase.prototype.convexLine = function(
+    convexBody,
+    convexShape,
+    convexOffset,
+    convexAngle,
+    lineBody,
+    lineShape,
+    lineOffset,
+    lineAngle,
+    justTest
+){
+    // TODO
+    if(justTest){
+        return false;
+    } else {
+        return 0;
+    }
+};
+
+/**
+ * Line/box narrowphase
+ * @method lineBox
+ * @param  {Body}       lineBody
+ * @param  {Line}       lineShape
+ * @param  {Array}      lineOffset
+ * @param  {Number}     lineAngle
+ * @param  {Body}       boxBody
+ * @param  {Box}  boxShape
+ * @param  {Array}      boxOffset
+ * @param  {Number}     boxAngle
+ * @param  {Boolean}    justTest
+ * @todo Implement me!
+ */
+Narrowphase.prototype[Shape.LINE | Shape.BOX] =
+Narrowphase.prototype.lineBox = function(
+    lineBody,
+    lineShape,
+    lineOffset,
+    lineAngle,
+    boxBody,
+    boxShape,
+    boxOffset,
+    boxAngle,
+    justTest
+){
+    // TODO
+    if(justTest){
+        return false;
+    } else {
+        return 0;
+    }
+};
+
+function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){
+    vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius);
+    vec2.set(convexShape.vertices[1],  capsuleShape.length * 0.5, -capsuleShape.radius);
+    vec2.set(convexShape.vertices[2],  capsuleShape.length * 0.5,  capsuleShape.radius);
+    vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5,  capsuleShape.radius);
+}
+
+var convexCapsule_tempRect = new Box({ width: 1, height: 1 }),
+    convexCapsule_tempVec = vec2.create();
+
+/**
+ * Convex/capsule narrowphase
+ * @method convexCapsule
+ * @param  {Body}       convexBody
+ * @param  {Convex}     convexShape
+ * @param  {Array}      convexPosition
+ * @param  {Number}     convexAngle
+ * @param  {Body}       capsuleBody
+ * @param  {Capsule}    capsuleShape
+ * @param  {Array}      capsulePosition
+ * @param  {Number}     capsuleAngle
+ */
+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
+){
+
+    // Check the circles
+    // Add offsets!
+    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;
+    }
+
+    // Check center rect
+    var r = convexCapsule_tempRect;
+    setConvexToCapsuleShapeMiddle(r,capsuleShape);
+    var result = this.convexConvex(convexBody,convexShape,convexPosition,convexAngle, capsuleBody,r,capsulePosition,capsuleAngle, justTest);
+
+    return result + result1 + result2;
+};
+
+/**
+ * Capsule/line narrowphase
+ * @method lineCapsule
+ * @param  {Body}       lineBody
+ * @param  {Line}       lineShape
+ * @param  {Array}      linePosition
+ * @param  {Number}     lineAngle
+ * @param  {Body}       capsuleBody
+ * @param  {Capsule}    capsuleShape
+ * @param  {Array}      capsulePosition
+ * @param  {Number}     capsuleAngle
+ * @todo Implement me!
+ */
+Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] =
+Narrowphase.prototype.lineCapsule = function(
+    lineBody,
+    lineShape,
+    linePosition,
+    lineAngle,
+    capsuleBody,
+    capsuleShape,
+    capsulePosition,
+    capsuleAngle,
+    justTest
+){
+    // TODO
+    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 });
+
+/**
+ * Capsule/capsule narrowphase
+ * @method capsuleCapsule
+ * @param  {Body}       bi
+ * @param  {Capsule}    si
+ * @param  {Array}      xi
+ * @param  {Number}     ai
+ * @param  {Body}       bj
+ * @param  {Capsule}    sj
+ * @param  {Array}      xj
+ * @param  {Number}     aj
+ */
+Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] =
+Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
+
+    var enableFrictionBefore;
+
+    // Check the circles
+    // Add offsets!
+    var circlePosi = capsuleCapsule_tempVec1,
+        circlePosj = capsuleCapsule_tempVec2;
+
+    var numContacts = 0;
+
+
+    // Need 4 circle checks, between all
+    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);
+
+            // Temporarily turn off friction
+            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){
+        // Temporarily turn off friction
+        enableFrictionBefore = this.enableFriction;
+        this.enableFriction = false;
+    }
+
+    // Check circles against the center boxs
+    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){
+        // Temporarily turn off friction
+        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;
+};
+
+/**
+ * Line/line narrowphase
+ * @method lineLine
+ * @param  {Body}       bodyA
+ * @param  {Line}       shapeA
+ * @param  {Array}      positionA
+ * @param  {Number}     angleA
+ * @param  {Body}       bodyB
+ * @param  {Line}       shapeB
+ * @param  {Array}      positionB
+ * @param  {Number}     angleB
+ * @todo Implement me!
+ */
+Narrowphase.prototype[Shape.LINE | Shape.LINE] =
+Narrowphase.prototype.lineLine = function(
+    bodyA,
+    shapeA,
+    positionA,
+    angleA,
+    bodyB,
+    shapeB,
+    positionB,
+    angleB,
+    justTest
+){
+    // TODO
+    if(justTest){
+        return false;
+    } else {
+        return 0;
+    }
+};
+
+/**
+ * Plane/line Narrowphase
+ * @method planeLine
+ * @param  {Body}   planeBody
+ * @param  {Plane}  planeShape
+ * @param  {Array}  planeOffset
+ * @param  {Number} planeAngle
+ * @param  {Body}   lineBody
+ * @param  {Line}   lineShape
+ * @param  {Array}  lineOffset
+ * @param  {Number} lineAngle
+ */
+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;
+
+    // Get start and end points
+    vec2.set(worldVertex0, -lineShape.length/2, 0);
+    vec2.set(worldVertex1,  lineShape.length/2, 0);
+
+    // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
+    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);
+
+    // Get vector along the line
+    sub(worldEdge, worldVertex1, worldVertex0);
+    vec2.normalize(worldEdgeUnit, worldEdge);
+
+    // Get tangent to the edge.
+    vec2.rotate90cw(worldTangent, worldEdgeUnit);
+
+    vec2.rotate(worldNormal, yAxis, planeAngle);
+
+    // Check line ends
+    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);
+
+            // distance vector along plane normal
+            vec2.scale(dist, worldNormal, d);
+
+            // Vector from plane center to contact
+            sub(c.contactPointA, v, dist);
+            sub(c.contactPointA, c.contactPointA, planeBody.position);
+
+            // From line center to contact
+            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);
+};
+
+/**
+ * Circle/line Narrowphase
+ * @method circleLine
+ * @param  {Body} circleBody
+ * @param  {Circle} circleShape
+ * @param  {Array} circleOffset
+ * @param  {Number} circleAngle
+ * @param  {Body} lineBody
+ * @param  {Line} lineShape
+ * @param  {Array} lineOffset
+ * @param  {Number} lineAngle
+ * @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations.
+ * @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules.
+ * @param {Number} circleRadius If set, this value overrides the circle shape radius.
+ */
+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;
+
+    // Get start and end points
+    vec2.set(worldVertex0, -lineShape.length/2, 0);
+    vec2.set(worldVertex1,  lineShape.length/2, 0);
+
+    // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
+    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);
+
+    // Get vector along the line
+    sub(worldEdge, worldVertex1, worldVertex0);
+    vec2.normalize(worldEdgeUnit, worldEdge);
+
+    // Get tangent to the edge.
+    vec2.rotate90cw(worldTangent, worldEdgeUnit);
+
+    // Check distance from the plane spanned by the edge vs the circle
+    sub(dist, circleOffset, worldVertex0);
+    var d = dot(dist, worldTangent); // Distance from center of line to circle center
+    sub(centerDist, worldVertex0, lineOffset);
+
+    sub(lineToCircle, circleOffset, lineOffset);
+
+    var radiusSum = circleRadius + lineRadius;
+
+    if(Math.abs(d) < radiusSum){
+
+        // Now project the circle onto the edge
+        vec2.scale(orthoDist, worldTangent, d);
+        sub(projectedPoint, circleOffset, orthoDist);
+
+        // Add the missing line radius
+        vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle));
+        vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit);
+        vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius);
+        add(projectedPoint,projectedPoint,lineToCircleOrthoUnit);
+
+        // Check if the point is within the edge span
+        var pos =  dot(worldEdgeUnit, projectedPoint);
+        var pos0 = dot(worldEdgeUnit, worldVertex0);
+        var pos1 = dot(worldEdgeUnit, worldVertex1);
+
+        if(pos > pos0 && pos < pos1){
+            // We got contact!
+
+            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;
+        }
+    }
+
+    // Add corner
+    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);
+
+            // Vector from circle to contact point is the normal times the circle radius
+            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;
+};
+
+/**
+ * Circle/capsule Narrowphase
+ * @method circleCapsule
+ * @param  {Body}   bi
+ * @param  {Circle} si
+ * @param  {Array}  xi
+ * @param  {Number} ai
+ * @param  {Body}   bj
+ * @param  {Line}   sj
+ * @param  {Array}  xj
+ * @param  {Number} aj
+ */
+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);
+};
+
+/**
+ * Circle/convex Narrowphase.
+ * @method circleConvex
+ * @param  {Body} circleBody
+ * @param  {Circle} circleShape
+ * @param  {Array} circleOffset
+ * @param  {Number} circleAngle
+ * @param  {Body} convexBody
+ * @param  {Convex} convexShape
+ * @param  {Array} convexOffset
+ * @param  {Number} convexAngle
+ * @param  {Boolean} justTest
+ * @param  {Number} circleRadius
+ */
+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;
+
+    // New algorithm:
+    // 1. Check so center of circle is not inside the polygon. If it is, this wont work...
+    // 2. For each edge
+    // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
+    // 2. 2. Check if point is inside.
+
+    var verts = convexShape.vertices;
+
+    // Check all edges first
+    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);
+
+        // Get tangent to the edge. Points out of the Convex
+        vec2.rotate90cw(worldNormal, worldEdgeUnit);
+
+        // Get point on circle, closest to the polygon
+        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;
+    }
+
+    // Check all vertices
+    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);
+
+                // Vector from circle to contact point is the normal times the circle radius
+                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();
+
+/*
+ * Check if a point is in a polygon
+ */
+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];
+
+        // Transform vertices to world
+        // @todo The point should be transformed to local coordinates in the convex, no need to transform each vertex
+        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 we got a different sign of the distance vector, the point is out of the polygon
+        if(cross*lastCross <= 0){
+            return false;
+        }
+        lastCross = cross;
+    }
+    return true;
+}
+
+/**
+ * Particle/convex Narrowphase
+ * @method particleConvex
+ * @param  {Body} particleBody
+ * @param  {Particle} particleShape
+ * @param  {Array} particleOffset
+ * @param  {Number} particleAngle
+ * @param  {Body} convexBody
+ * @param  {Convex} convexShape
+ * @param  {Array} convexOffset
+ * @param  {Number} convexAngle
+ * @param {Boolean} justTest
+ * @todo use pointInConvex and code more similar to circleConvex
+ * @todo don't transform each vertex, but transform the particle position to convex-local instead
+ */
+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, // vector from particle to vertex0
+        r1 = tmp15,
+        localPoint = tmp16,
+        candidateDist = tmp17,
+        minEdgeNormal = tmp18,
+        minCandidateDistance = Number.MAX_VALUE;
+
+    var numReported = 0,
+        found = false,
+        verts = convexShape.vertices;
+
+    // Check if the particle is in the polygon at all
+    if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){
+        return 0;
+    }
+
+    if(justTest){
+        return true;
+    }
+
+    // Check edges first
+    var lastCross = null;
+    for(var i=0; i!==verts.length+1; i++){
+        var v0 = verts[i%verts.length],
+            v1 = verts[(i+1)%verts.length];
+
+        // Transform vertices to world
+        vec2.rotate(worldVertex0, v0, convexAngle);
+        vec2.rotate(worldVertex1, v1, convexAngle);
+        add(worldVertex0, worldVertex0, convexOffset);
+        add(worldVertex1, worldVertex1, convexOffset);
+
+        // Get world edge
+        sub(worldEdge, worldVertex1, worldVertex0);
+        vec2.normalize(worldEdgeUnit, worldEdge);
+
+        // Get tangent to the edge. Points out of the Convex
+        vec2.rotate90cw(worldTangent, worldEdgeUnit);
+
+        // Check distance from the infinite line (spanned by the edge) to the particle
+        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);
+
+        // Particle has no extent to the contact point
+        vec2.set(c.contactPointA,  0, 0);
+        add(c.contactPointA, c.contactPointA, particleOffset);
+        sub(c.contactPointA, c.contactPointA, particleBody.position);
+
+        // From convex center to point
+        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;
+};
+
+/**
+ * Circle/circle Narrowphase
+ * @method circleCircle
+ * @param  {Body} bodyA
+ * @param  {Circle} shapeA
+ * @param  {Array} offsetA
+ * @param  {Number} angleA
+ * @param  {Body} bodyB
+ * @param  {Circle} shapeB
+ * @param  {Array} offsetB
+ * @param  {Number} angleB
+ * @param {Boolean} justTest
+ * @param {Number} [radiusA] Optional radius to use for shapeA
+ * @param {Number} [radiusB] Optional radius to use for shapeB
+ */
+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;
+};
+
+/**
+ * Plane/Convex Narrowphase
+ * @method planeConvex
+ * @param  {Body} planeBody
+ * @param  {Plane} planeShape
+ * @param  {Array} planeOffset
+ * @param  {Number} planeAngle
+ * @param  {Body} convexBody
+ * @param  {Convex} convexShape
+ * @param  {Array} convexOffset
+ * @param  {Number} convexAngle
+ * @param {Boolean} justTest
+ */
+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;
+            }
+
+            // Found vertex
+            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);
+
+            // rj is from convex center to contact
+            sub(c.contactPointB, worldVertex, convexBody.position);
+
+
+            // ri is from plane center to contact
+            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 for particle vs plane
+ * @method particlePlane
+ * @param  {Body}       particleBody
+ * @param  {Particle}   particleShape
+ * @param  {Array}      particleOffset
+ * @param  {Number}     particleAngle
+ * @param  {Body}       planeBody
+ * @param  {Plane}      planeShape
+ * @param  {Array}      planeOffset
+ * @param  {Number}     planeAngle
+ * @param {Boolean}     justTest
+ */
+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 );
+    // dist is now the distance vector in the normal direction
+
+    // ri is the particle position projected down onto the plane, from the plane center
+    sub( c.contactPointA, particleOffset, dist);
+    sub( c.contactPointA, c.contactPointA, planeBody.position);
+
+    // rj is from the body center to the particle center
+    sub( c.contactPointB, particleOffset, particleBody.position );
+
+    this.contactEquations.push(c);
+
+    if(this.enableFriction){
+        this.frictionEquations.push(this.createFrictionFromContact(c));
+    }
+    return 1;
+};
+
+/**
+ * Circle/Particle Narrowphase
+ * @method circleParticle
+ * @param  {Body} circleBody
+ * @param  {Circle} circleShape
+ * @param  {Array} circleOffset
+ * @param  {Number} circleAngle
+ * @param  {Body} particleBody
+ * @param  {Particle} particleShape
+ * @param  {Array} particleOffset
+ * @param  {Number} particleAngle
+ * @param  {Boolean} justTest
+ */
+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);
+
+    // Vector from circle to contact point is the normal times the circle radius
+    vec2.scale(c.contactPointA, c.normalA, circleShape.radius);
+    add(c.contactPointA, c.contactPointA, circleOffset);
+    sub(c.contactPointA, c.contactPointA, circleBody.position);
+
+    // Vector from particle center to contact point is zero
+    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();
+
+/**
+ * @method planeCapsule
+ * @param  {Body} planeBody
+ * @param  {Circle} planeShape
+ * @param  {Array} planeOffset
+ * @param  {Number} planeAngle
+ * @param  {Body} capsuleBody
+ * @param  {Particle} capsuleShape
+ * @param  {Array} capsuleOffset
+ * @param  {Number} capsuleAngle
+ * @param {Boolean} justTest
+ */
+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;
+
+    // Compute world end positions
+    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;
+
+    // Temporarily turn off friction
+    if(this.enableFrictionReduction){
+        enableFrictionBefore = this.enableFriction;
+        this.enableFriction = false;
+    }
+
+    // Do Narrowphase as two circles
+    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);
+
+    // Restore friction
+    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;
+    }
+};
+
+/**
+ * Creates ContactEquations and FrictionEquations for a collision.
+ * @method circlePlane
+ * @param  {Body}    bi     The first body that should be connected to the equations.
+ * @param  {Circle}  si     The circle shape participating in the collision.
+ * @param  {Array}   xi     Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none.
+ * @param  {Body}    bj     The second body that should be connected to the equations.
+ * @param  {Plane}   sj     The Plane shape that is participating
+ * @param  {Array}   xj     Extra offset for the plane shape.
+ * @param  {Number}  aj     Extra angle to apply to the plane
+ */
+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, // Offset from body center, rotated!
+        planeBody = bj,
+        shapeB = sj,
+        planeOffset = xj,
+        planeAngle = aj;
+
+    planeAngle = planeAngle || 0;
+
+    // Vector from plane to circle
+    var planeToCircle = tmp1,
+        worldNormal = tmp2,
+        temp = tmp3;
+
+    sub(planeToCircle, circleOffset, planeOffset);
+
+    // World plane normal
+    vec2.rotate(worldNormal, yAxis, planeAngle);
+
+    // Normal direction distance
+    var d = dot(worldNormal, planeToCircle);
+
+    if(d > circleShape.radius){
+        return 0; // No overlap. Abort.
+    }
+
+    if(justTest){
+        return true;
+    }
+
+    // Create contact
+    var contact = this.createContactEquation(planeBody,circleBody,sj,si);
+
+    // ni is the plane world normal
+    vec2.copy(contact.normalA, worldNormal);
+
+    // rj is the vector from circle center to the contact point
+    vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius);
+    add(contact.contactPointB, contact.contactPointB, circleOffset);
+    sub(contact.contactPointB, contact.contactPointB, circleBody.position);
+
+    // ri is the distance from plane center to contact.
+    vec2.scale(temp, contact.normalA, d);
+    sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector
+    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;
+};
+
+/**
+ * Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info.
+ * @method convexConvex
+ * @param  {Body} bi
+ * @param  {Convex} si
+ * @param  {Array} xi
+ * @param  {Number} ai
+ * @param  {Body} bj
+ * @param  {Convex} sj
+ * @param  {Array} xj
+ * @param  {Number} aj
+ */
+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;
+    }
+
+    // Make sure the separating axis is directed from shape i to shape j
+    sub(dist,xj,xi);
+    if(dot(sepAxis,dist) > 0){
+        vec2.scale(sepAxis,sepAxis,-1);
+    }
+
+    // Find edges with normals closest to the separating axis
+    var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis
+        closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis);
+
+    if(closestEdge1 === -1 || closestEdge2 === -1){
+        return 0;
+    }
+
+    // Loop over the shapes
+    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){
+            // Swap!
+            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;
+        }
+
+        // Loop over 2 points in convex B
+        for(var j=closestEdgeB; j<closestEdgeB+2; j++){
+
+            // Get world point
+            var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length];
+            vec2.rotate(worldPoint, v, angleB);
+            add(worldPoint, worldPoint, offsetB);
+
+            var insideNumEdges = 0;
+
+            // Loop over the 3 closest edges in convex A
+            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];
+
+                // Construct the edge
+                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); // Normal points out of convex 1
+                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;
+                }
+
+                // worldPoint was on the "inside" side of each of the 3 checked edges.
+                // Project it to the center edge and use the projection direction as normal
+
+                // Create contact
+                var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB);
+                numContacts++;
+
+                // Get center edge from body A
+                var v0 = shapeA.vertices[(closestEdgeA)   % shapeA.vertices.length],
+                    v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length];
+
+                // Construct the edge
+                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); // Normal points out of convex A
+                vec2.normalize(c.normalA,c.normalA);
+
+                sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point
+                var d = dot(c.normalA,dist);             // Penetration
+                vec2.scale(penetrationVec, c.normalA, d);     // Vector penetration
+
+                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);
+
+                // Todo reduce to 1 friction equation if we have 2 contact points
+                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;
+};
+
+// .projectConvex is called by other functions, need local tmp vectors
+var pcoa_tmp1 = vec2.fromValues(0,0);
+
+/**
+ * Project a Convex onto a world-oriented axis
+ * @method projectConvexOntoAxis
+ * @static
+ * @param  {Convex} convexShape
+ * @param  {Array} convexOffset
+ * @param  {Number} convexAngle
+ * @param  {Array} worldAxis
+ * @param  {Array} result
+ */
+Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){
+    var max=null,
+        min=null,
+        v,
+        value,
+        localAxis = pcoa_tmp1;
+
+    // Convert the axis to local coords of the body
+    vec2.rotate(localAxis, worldAxis, -convexAngle);
+
+    // Get projected position of all vertices
+    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;
+    }
+
+    // Project the position of the body onto the axis - need to add this to the result
+    var offset = dot(convexOffset, worldAxis);
+
+    vec2.set( result, min + offset, max + offset);
+};
+
+// .findSeparatingAxis is called by other functions, need local tmp vectors
+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);
+
+/**
+ * Find a separating axis between the shapes, that maximizes the separating distance between them.
+ * @method findSeparatingAxis
+ * @static
+ * @param  {Convex}     c1
+ * @param  {Array}      offset1
+ * @param  {Number}     angle1
+ * @param  {Convex}     c2
+ * @param  {Array}      offset2
+ * @param  {Number}     angle2
+ * @param  {Array}      sepAxis     The resulting axis
+ * @return {Boolean}                Whether the axis could be found.
+ */
+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++){
+
+                // Get the world edge
+                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);
+                }
+
+                // Project hulls onto that normal
+                Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
+                Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
+
+                // Order by span position
+                var a=span1,
+                    b=span2,
+                    swapped = false;
+                if(span1[0] > span2[0]){
+                    b=span1;
+                    a=span2;
+                    swapped = true;
+                }
+
+                // Get separating distance
+                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++){
+                // Get the world edge
+                vec2.rotate(worldPoint0, c.vertices[i], angle);
+                vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle);
+
+                sub(edge, worldPoint1, worldPoint0);
+
+                // Get normal - just rotate 90 degrees since vertices are given in CCW
+                vec2.rotate90cw(normal, edge);
+                vec2.normalize(normal,normal);
+
+                // Project hulls onto that normal
+                Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
+                Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
+
+                // Order by span position
+                var a=span1,
+                    b=span2,
+                    swapped = false;
+                if(span1[0] > span2[0]){
+                    b=span1;
+                    a=span2;
+                    swapped = true;
+                }
+
+                // Get separating distance
+                var dist = b[0] - a[1];
+                overlap = (dist <= 0);
+
+                if(maxDist===null || dist > maxDist){
+                    vec2.copy(sepAxis, normal);
+                    maxDist = dist;
+                    found = overlap;
+                }
+            }
+        }
+    }
+
+
+    /*
+    // Needs to be tested some more
+    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.axes.length; i++){
+
+            var normal = c.axes[i];
+
+            // Project hulls onto that normal
+            Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1);
+            Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2);
+
+            // Order by span position
+            var a=span1,
+                b=span2,
+                swapped = false;
+            if(span1[0] > span2[0]){
+                b=span1;
+                a=span2;
+                swapped = true;
+            }
+
+            // Get separating distance
+            var dist = b[0] - a[1];
+            overlap = (dist <= Narrowphase.convexPrecision);
+
+            if(maxDist===null || dist > maxDist){
+                vec2.copy(sepAxis, normal);
+                maxDist = dist;
+                found = overlap;
+            }
+        }
+    }
+    */
+
+    return found;
+};
+
+// .getClosestEdge is called by other functions, need local tmp vectors
+var gce_tmp1 = vec2.fromValues(0,0)
+,   gce_tmp2 = vec2.fromValues(0,0)
+,   gce_tmp3 = vec2.fromValues(0,0);
+
+/**
+ * Get the edge that has a normal closest to an axis.
+ * @method getClosestEdge
+ * @static
+ * @param  {Convex}     c
+ * @param  {Number}     angle
+ * @param  {Array}      axis
+ * @param  {Boolean}    flip
+ * @return {Number}             Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed.
+ */
+Narrowphase.getClosestEdge = function(c,angle,axis,flip){
+    var localAxis = gce_tmp1,
+        edge = gce_tmp2,
+        normal = gce_tmp3;
+
+    // Convert the axis to local coords of the body
+    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++){
+        // Get the edge
+        sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]);
+
+        // Get normal - just rotate 90 degrees since vertices are given in CCW
+        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();
+
+/**
+ * @method circleHeightfield
+ * @param  {Body}           bi
+ * @param  {Circle}         si
+ * @param  {Array}          xi
+ * @param  {Body}           bj
+ * @param  {Heightfield}    sj
+ * @param  {Array}          xj
+ * @param  {Number}         aj
+ */
+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;
+
+    // Get the index of the points to test against
+    var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ),
+        idxB = Math.ceil(  (circlePos[0] + radius - hfPos[0]) / w );
+
+    /*if(idxB < 0 || idxA >= data.length)
+        return justTest ? false : 0;*/
+
+    if(idxA < 0){
+        idxA = 0;
+    }
+    if(idxB >= data.length){
+        idxB = data.length-1;
+    }
+
+    // Get max and min
+    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;
+    }
+
+    /*
+    if(circlePos[1]+radius < min){
+        // Below the minimum point... We can just guess.
+        // TODO
+    }
+    */
+
+    // 1. Check so center of circle is not inside the field. If it is, this wont work...
+    // 2. For each edge
+    // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
+    // 2. 2. Check if point is inside.
+
+    var found = false;
+
+    // Check all edges first
+    for(var i=idxA; i<idxB; i++){
+
+        // Get points
+        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);
+
+        // Get normal
+        vec2.sub(worldNormal, v1, v0);
+        vec2.rotate(worldNormal, worldNormal, Math.PI/2);
+        vec2.normalize(worldNormal,worldNormal);
+
+        // Get point on circle, closest to the edge
+        vec2.scale(candidate,worldNormal,-radius);
+        vec2.add(candidate,candidate,circlePos);
+
+        // Distance from v0 to the candidate point
+        vec2.sub(dist,candidate,v0);
+
+        // Check if it is in the element "stick"
+        var d = vec2.dot(dist,worldNormal);
+        if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){
+
+            if(justTest){
+                return true;
+            }
+
+            found = true;
+
+            // Store the candidate point, projected to the edge
+            vec2.scale(dist,worldNormal,-d);
+            vec2.add(minCandidate,candidate,dist);
+            vec2.copy(minCandidateNormal,worldNormal);
+
+            var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
+
+            // Normal is out of the heightfield
+            vec2.copy(c.normalA, minCandidateNormal);
+
+            // Vector from circle to heightfield
+            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) );
+            }
+        }
+    }
+
+    // Check all vertices
+    found = false;
+    if(radius > 0){
+        for(var i=idxA; i<=idxB; i++){
+
+            // Get point
+            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);
+
+                // Construct normal - out of heightfield
+                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()] });
+/**
+ * @method circleHeightfield
+ * @param  {Body}           bi
+ * @param  {Circle}         si
+ * @param  {Array}          xi
+ * @param  {Body}           bj
+ * @param  {Heightfield}    sj
+ * @param  {Array}          xj
+ * @param  {Number}         aj
+ */
+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;
+
+    // Get the index of the points to test against
+    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;
+    }
+
+    // Get max and min
+    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;
+
+    // Loop over all edges
+    // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape)
+    for(var i=idxA; i<idxB; i++){
+
+        // Get points
+        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);
+
+        // Construct a convex
+        var tileHeight = 100; // todo
+        vec2.set(tilePos, (v1[0] + v0[0])*0.5, (v1[1] + v0[1] - tileHeight)*0.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;
+
+        // Do convex collision
+        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":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(_dereq_,module,exports){
+module.exports = Ray;
+
+var vec2 = _dereq_('../math/vec2');
+var RaycastResult = _dereq_('../collision/RaycastResult');
+var Shape = _dereq_('../shapes/Shape');
+var AABB = _dereq_('../collision/AABB');
+
+/**
+ * A line with a start and end point that is used to intersect shapes. For an example, see {{#crossLink "World/raycast:method"}}World.raycast{{/crossLink}}
+ * @class Ray
+ * @constructor
+ * @param {object} [options]
+ * @param {array} [options.from]
+ * @param {array} [options.to]
+ * @param {boolean} [options.checkCollisionResponse=true]
+ * @param {boolean} [options.skipBackfaces=false]
+ * @param {number} [options.collisionMask=-1]
+ * @param {number} [options.collisionGroup=-1]
+ * @param {number} [options.mode=Ray.ANY]
+ * @param {number} [options.callback]
+ */
+function Ray(options){
+    options = options || {};
+
+    /**
+     * Ray start point.
+     * @property {array} from
+     */
+    this.from = options.from ? vec2.fromValues(options.from[0], options.from[1]) : vec2.create();
+
+    /**
+     * Ray end point
+     * @property {array} to
+     */
+    this.to = options.to ? vec2.fromValues(options.to[0], options.to[1]) : vec2.create();
+
+    /**
+     * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
+     * @property {Boolean} checkCollisionResponse
+     */
+    this.checkCollisionResponse = options.checkCollisionResponse !== undefined ? options.checkCollisionResponse : true;
+
+    /**
+     * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
+     * @property {Boolean} skipBackfaces
+     */
+    this.skipBackfaces = !!options.skipBackfaces;
+
+    /**
+     * @property {number} collisionMask
+     * @default -1
+     */
+    this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : -1;
+
+    /**
+     * @property {number} collisionGroup
+     * @default -1
+     */
+    this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : -1;
+
+    /**
+     * The intersection mode. Should be {{#crossLink "Ray/ANY:property"}}Ray.ANY{{/crossLink}}, {{#crossLink "Ray/ALL:property"}}Ray.ALL{{/crossLink}} or {{#crossLink "Ray/CLOSEST:property"}}Ray.CLOSEST{{/crossLink}}.
+     * @property {number} mode
+     */
+    this.mode = options.mode !== undefined ? options.mode : Ray.ANY;
+
+    /**
+     * Current, user-provided result callback. Will be used if mode is Ray.ALL.
+     * @property {Function} callback
+     */
+    this.callback = options.callback || function(result){};
+
+    /**
+     * @readOnly
+     * @property {array} direction
+     */
+    this.direction = vec2.create();
+
+    /**
+     * Length of the ray
+     * @readOnly
+     * @property {number} length
+     */
+    this.length = 1;
+
+    this.update();
+}
+Ray.prototype.constructor = Ray;
+
+/**
+ * This raycasting mode will make the Ray traverse through all intersection points and only return the closest one.
+ * @static
+ * @property {Number} CLOSEST
+ */
+Ray.CLOSEST = 1;
+
+/**
+ * This raycasting mode will make the Ray stop when it finds the first intersection point.
+ * @static
+ * @property {Number} ANY
+ */
+Ray.ANY = 2;
+
+/**
+ * This raycasting mode will traverse all intersection points and executes a callback for each one.
+ * @static
+ * @property {Number} ALL
+ */
+Ray.ALL = 4;
+
+/**
+ * Should be called if you change the from or to point.
+ * @method update
+ */
+Ray.prototype.update = function(){
+
+    // Update .direction and .length
+    var d = this.direction;
+    vec2.sub(d, this.to, this.from);
+    this.length = vec2.length(d);
+    vec2.normalize(d, d);
+
+};
+
+/**
+ * @method intersectBodies
+ * @param {Array} bodies An array of Body objects.
+ */
+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();
+
+/**
+ * Shoot a ray at a body, get back information about the hit.
+ * @method intersectBody
+ * @private
+ * @param {Body} body
+ */
+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; // Skip
+        }
+
+        if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){
+            continue;
+        }
+
+        // Get world angle and position of the shape
+        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;
+        }
+    }
+};
+
+/**
+ * @method intersectShape
+ * @private
+ * @param {Shape} shape
+ * @param {number} angle
+ * @param {array} position
+ * @param {Body} body
+ */
+Ray.prototype.intersectShape = function(result, shape, angle, position, body){
+    var from = this.from;
+
+    // Checking radius
+    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;
+};
+
+/**
+ * Get the AABB of the ray.
+ * @method getAABB
+ * @param  {AABB} aabb
+ */
+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();
+
+/**
+ * @method reportIntersection
+ * @private
+ * @param  {number} fraction
+ * @param  {array} normal
+ * @param  {number} [faceIndex=-1]
+ * @return {boolean} True if the intersections should continue
+ */
+Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){
+    var from = this.from;
+    var to = this.to;
+    var shape = this._currentShape;
+    var body = this._currentBody;
+
+    // Skip back faces?
+    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:
+
+        // Store if closer than current closest
+        if(fraction < result.fraction || !result.hasHit()){
+            result.set(
+                normal,
+                shape,
+                body,
+                fraction,
+                faceIndex
+            );
+        }
+        break;
+
+    case Ray.ANY:
+
+        // Report and stop.
+        result.set(
+            normal,
+            shape,
+            body,
+            fraction,
+            faceIndex
+        );
+        break;
+    }
+};
+
+var v0 = vec2.create(),
+    intersect = vec2.create();
+function distanceFromIntersectionSquared(from, direction, position) {
+
+    // v0 is vector from from to position
+    vec2.sub(v0, position, from);
+    var dot = vec2.dot(v0, direction);
+
+    // intersect = direction * dot + from
+    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":45}],12:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2');
+var Ray = _dereq_('../collision/Ray');
+
+module.exports = RaycastResult;
+
+/**
+ * Storage for Ray casting hit data.
+ * @class RaycastResult
+ * @constructor
+ */
+function RaycastResult(){
+
+	/**
+	 * The normal of the hit, oriented in world space.
+	 * @property {array} normal
+	 */
+	this.normal = vec2.create();
+
+	/**
+	 * The hit shape, or null.
+	 * @property {Shape} shape
+	 */
+	this.shape = null;
+
+	/**
+	 * The hit body, or null.
+	 * @property {Body} body
+	 */
+	this.body = null;
+
+	/**
+	 * The index of the hit triangle, if the hit shape was indexable.
+	 * @property {number} faceIndex
+	 * @default -1
+	 */
+	this.faceIndex = -1;
+
+	/**
+	 * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet.
+	 * @property {number} fraction
+	 * @default -1
+	 */
+	this.fraction = -1;
+
+	/**
+	 * If the ray should stop traversing.
+	 * @readonly
+	 * @property {Boolean} isStopped
+	 */
+	this.isStopped = false;
+}
+
+/**
+ * Reset all result data. Must be done before re-using the result object.
+ * @method reset
+ */
+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;
+};
+
+/**
+ * Get the distance to the hit point.
+ * @method getHitDistance
+ * @param {Ray} ray
+ */
+RaycastResult.prototype.getHitDistance = function (ray) {
+	return vec2.distance(ray.from, ray.to) * this.fraction;
+};
+
+/**
+ * Returns true if the ray hit something since the last reset().
+ * @method hasHit
+ */
+RaycastResult.prototype.hasHit = function () {
+	return this.fraction !== -1;
+};
+
+/**
+ * Get world hit point.
+ * @method getHitPoint
+ * @param {array} out
+ * @param {Ray} ray
+ */
+RaycastResult.prototype.getHitPoint = function (out, ray) {
+	vec2.lerp(out, ray.from, ray.to, this.fraction);
+};
+
+/**
+ * Can be called while iterating over hits to stop searching for hit points.
+ * @method stop
+ */
+RaycastResult.prototype.stop = function(){
+	this.isStopped = true;
+};
+
+/**
+ * @method shouldStop
+ * @private
+ * @param {Ray} ray
+ * @return {boolean}
+ */
+RaycastResult.prototype.shouldStop = function(ray){
+	return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY);
+};
+
+/**
+ * @method set
+ * @private
+ * @param {array} normal
+ * @param {Shape} shape
+ * @param {Body} body
+ * @param {number} fraction
+ */
+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(_dereq_,module,exports){
+var Utils = _dereq_('../utils/Utils')
+,   Broadphase = _dereq_('../collision/Broadphase');
+
+module.exports = SAPBroadphase;
+
+/**
+ * Sweep and prune broadphase along one axis.
+ *
+ * @class SAPBroadphase
+ * @constructor
+ * @extends Broadphase
+ */
+function SAPBroadphase(){
+    Broadphase.call(this,Broadphase.SAP);
+
+    /**
+     * List of bodies currently in the broadphase.
+     * @property axisList
+     * @type {Array}
+     */
+    this.axisList = [];
+
+    /**
+     * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance.
+     * @property axisIndex
+     * @type {Number}
+     */
+    this.axisIndex = 0;
+
+    var that = this;
+    this._addBodyHandler = function(e){
+        that.axisList.push(e.body);
+    };
+
+    this._removeBodyHandler = function(e){
+        // Remove from list
+        var idx = that.axisList.indexOf(e.body);
+        if(idx !== -1){
+            that.axisList.splice(idx,1);
+        }
+    };
+}
+SAPBroadphase.prototype = new Broadphase();
+SAPBroadphase.prototype.constructor = SAPBroadphase;
+
+/**
+ * Change the world
+ * @method setWorld
+ * @param {World} world
+ */
+SAPBroadphase.prototype.setWorld = function(world){
+    // Clear the old axis array
+    this.axisList.length = 0;
+
+    // Add all bodies from the new world
+    Utils.appendArray(this.axisList, world.bodies);
+
+    // Remove old handlers, if any
+    world
+        .off("addBody",this._addBodyHandler)
+        .off("removeBody",this._removeBodyHandler);
+
+    // Add handlers to update the list of bodies.
+    world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);
+
+    this.world = world;
+};
+
+/**
+ * Sorts bodies along an axis.
+ * @method sortAxisList
+ * @param {Array} a
+ * @param {number} axisIndex
+ * @return {Array}
+ */
+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;
+
+    // Sort the lists
+    SAPBroadphase.sortAxisList(bodies, axisIndex);
+};
+
+/**
+ * Get the colliding pairs
+ * @method getCollisionPairs
+ * @param  {World} world
+ * @return {Array}
+ */
+SAPBroadphase.prototype.getCollisionPairs = function(world){
+    var bodies = this.axisList,
+        result = this.result,
+        axisIndex = this.axisIndex;
+
+    result.length = 0;
+
+    // Update all AABBs if needed
+    var l = bodies.length;
+    while(l--){
+        var b = bodies[l];
+        if(b.aabbNeedsUpdate){
+            b.updateAABB();
+        }
+    }
+
+    // Sort the lists
+    this.sortList();
+
+    // Look through the X list
+    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];
+
+            // Bounds overlap?
+            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;
+};
+
+/**
+ * Returns all the bodies within an AABB.
+ * @method aabbQuery
+ * @param  {World} world
+ * @param  {AABB} aabb
+ * @param {array} result An array to store resulting bodies in.
+ * @return {array}
+ */
+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":57}],14:[function(_dereq_,module,exports){
+module.exports = Constraint;
+
+var Utils = _dereq_('../utils/Utils');
+
+/**
+ * Base constraint class.
+ *
+ * @class Constraint
+ * @constructor
+ * @author schteppe
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Number} type
+ * @param {Object} [options]
+ * @param {Object} [options.collideConnected=true]
+ */
+function Constraint(bodyA, bodyB, type, options){
+
+    /**
+     * The type of constraint. May be one of Constraint.DISTANCE, Constraint.GEAR, Constraint.LOCK, Constraint.PRISMATIC or Constraint.REVOLUTE.
+     * @property {number} type
+     */
+    this.type = type;
+
+    options = Utils.defaults(options,{
+        collideConnected : true,
+        wakeUpBodies : true,
+    });
+
+    /**
+     * Equations to be solved in this constraint
+     *
+     * @property equations
+     * @type {Array}
+     */
+    this.equations = [];
+
+    /**
+     * First body participating in the constraint.
+     * @property bodyA
+     * @type {Body}
+     */
+    this.bodyA = bodyA;
+
+    /**
+     * Second body participating in the constraint.
+     * @property bodyB
+     * @type {Body}
+     */
+    this.bodyB = bodyB;
+
+    /**
+     * Set to true if you want the connected bodies to collide.
+     * @property collideConnected
+     * @type {Boolean}
+     * @default true
+     */
+    this.collideConnected = options.collideConnected;
+
+    // Wake up bodies when connected
+    if(options.wakeUpBodies){
+        if(bodyA){
+            bodyA.wakeUp();
+        }
+        if(bodyB){
+            bodyB.wakeUp();
+        }
+    }
+}
+
+/**
+ * Updates the internal constraint parameters before solve.
+ * @method update
+ */
+Constraint.prototype.update = function(){
+    throw new Error("method update() not implmemented in this Constraint subclass!");
+};
+
+/**
+ * @static
+ * @property {number} DISTANCE
+ */
+Constraint.DISTANCE = 1;
+
+/**
+ * @static
+ * @property {number} GEAR
+ */
+Constraint.GEAR = 2;
+
+/**
+ * @static
+ * @property {number} LOCK
+ */
+Constraint.LOCK = 3;
+
+/**
+ * @static
+ * @property {number} PRISMATIC
+ */
+Constraint.PRISMATIC = 4;
+
+/**
+ * @static
+ * @property {number} REVOLUTE
+ */
+Constraint.REVOLUTE = 5;
+
+/**
+ * Set stiffness for this constraint.
+ * @method setStiffness
+ * @param {Number} stiffness
+ */
+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;
+    }
+};
+
+/**
+ * Set relaxation for this constraint.
+ * @method setRelaxation
+ * @param {Number} relaxation
+ */
+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":57}],15:[function(_dereq_,module,exports){
+var Constraint = _dereq_('./Constraint')
+,   Equation = _dereq_('../equations/Equation')
+,   vec2 = _dereq_('../math/vec2')
+,   Utils = _dereq_('../utils/Utils');
+
+module.exports = DistanceConstraint;
+
+/**
+ * Constraint that tries to keep the distance between two bodies constant.
+ *
+ * @class DistanceConstraint
+ * @constructor
+ * @author schteppe
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {object} [options]
+ * @param {number} [options.distance] The distance to keep between the anchor points. Defaults to the current distance between the bodies.
+ * @param {Array} [options.localAnchorA] The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
+ * @param {Array} [options.localAnchorB] The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
+ * @param {object} [options.maxForce=Number.MAX_VALUE] Maximum force to apply.
+ * @extends Constraint
+ *
+ * @example
+ *     // If distance is not given as an option, then the current distance between the bodies is used.
+ *     // In this example, the bodies will be constrained to have a distance of 2 between their centers.
+ *     var bodyA = new Body({ mass: 1, position: [-1, 0] });
+ *     var bodyB = new Body({ mass: 1, position: [1, 0] });
+ *     var constraint = new DistanceConstraint(bodyA, bodyB);
+ *     world.addConstraint(constraint);
+ *
+ * @example
+ *     // Manually set the distance and anchors
+ *     var constraint = new DistanceConstraint(bodyA, bodyB, {
+ *         distance: 1,          // Distance to keep between the points
+ *         localAnchorA: [1, 0], // Point on bodyA
+ *         localAnchorB: [-1, 0] // Point on bodyB
+ *     });
+ *     world.addConstraint(constraint);
+ */
+function DistanceConstraint(bodyA,bodyB,options){
+    options = Utils.defaults(options,{
+        localAnchorA:[0,0],
+        localAnchorB:[0,0]
+    });
+
+    Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options);
+
+    /**
+     * Local anchor in body A.
+     * @property localAnchorA
+     * @type {Array}
+     */
+    this.localAnchorA = vec2.fromValues(options.localAnchorA[0], options.localAnchorA[1]);
+
+    /**
+     * Local anchor in body B.
+     * @property localAnchorB
+     * @type {Array}
+     */
+    this.localAnchorB = vec2.fromValues(options.localAnchorB[0], options.localAnchorB[1]);
+
+    var localAnchorA = this.localAnchorA;
+    var localAnchorB = this.localAnchorB;
+
+    /**
+     * The distance to keep.
+     * @property distance
+     * @type {Number}
+     */
+    this.distance = 0;
+
+    if(typeof(options.distance) === 'number'){
+        this.distance = options.distance;
+    } else {
+        // Use the current world distance between the world anchor points.
+        var worldAnchorA = vec2.create(),
+            worldAnchorB = vec2.create(),
+            r = vec2.create();
+
+        // Transform local anchors to world
+        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); // Just in the normal direction
+    this.equations = [ normal ];
+
+    /**
+     * Max force to apply.
+     * @property {number} maxForce
+     */
+    this.maxForce = maxForce;
+
+    // g = (xi - xj).dot(n)
+    // dg/dt = (vi - vj).dot(n) = G*W = [n 0 -n 0] * [vi wi vj wj]'
+
+    // ...and if we were to include offset points:
+    // g =
+    //      (xj + rj - xi - ri).dot(n) - distance
+    //
+    // dg/dt =
+    //      (vj + wj x rj - vi - wi x ri).dot(n) =
+    //      { term 2 is near zero } =
+    //      [-n   -ri x n   n   rj x n] * [vi wi vj wj]' =
+    //      G * W
+    //
+    // => G = [-n -rixn n rjxn]
+
+    var r = vec2.create();
+    var ri = vec2.create(); // worldAnchorA
+    var rj = vec2.create(); // worldAnchorB
+    var that = this;
+    normal.computeGq = function(){
+        var bodyA = this.bodyA,
+            bodyB = this.bodyB,
+            xi = bodyA.position,
+            xj = bodyB.position;
+
+        // Transform local anchors to world
+        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);
+
+        //vec2.sub(r, bodyB.position, bodyA.position);
+        return vec2.length(r) - that.distance;
+    };
+
+    // Make the contact constraint bilateral
+    this.setMaxForce(maxForce);
+
+    /**
+     * If the upper limit is enabled or not.
+     * @property {Boolean} upperLimitEnabled
+     */
+    this.upperLimitEnabled = false;
+
+    /**
+     * The upper constraint limit.
+     * @property {number} upperLimit
+     */
+    this.upperLimit = 1;
+
+    /**
+     * If the lower limit is enabled or not.
+     * @property {Boolean} lowerLimitEnabled
+     */
+    this.lowerLimitEnabled = false;
+
+    /**
+     * The lower constraint limit.
+     * @property {number} lowerLimit
+     */
+    this.lowerLimit = 0;
+
+    /**
+     * Current constraint position. This is equal to the current distance between the world anchor points.
+     * @property {number} position
+     */
+    this.position = 0;
+}
+DistanceConstraint.prototype = new Constraint();
+DistanceConstraint.prototype.constructor = DistanceConstraint;
+
+/**
+ * Update the constraint equations. Should be done if any of the bodies changed position, before solving.
+ * @method update
+ */
+var n = vec2.create();
+var ri = vec2.create(); // worldAnchorA
+var rj = vec2.create(); // worldAnchorB
+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;
+
+    // Transform local anchors to world
+    vec2.rotate(ri, this.localAnchorA, bodyA.angle);
+    vec2.rotate(rj, this.localAnchorB, bodyB.angle);
+
+    // Get world anchor points and normal
+    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){
+        // No constraint needed.
+        normalEquation.enabled = false;
+        return;
+    }
+
+    normalEquation.enabled = true;
+
+    vec2.normalize(n,n);
+
+    // Caluclate cross products
+    var rixn = vec2.crossLength(ri, n),
+        rjxn = vec2.crossLength(rj, n);
+
+    // G = [-n -rixn n rjxn]
+    G[0] = -n[0];
+    G[1] = -n[1];
+    G[2] = -rixn;
+    G[3] = n[0];
+    G[4] = n[1];
+    G[5] = rjxn;
+};
+
+/**
+ * Set the max force to be used
+ * @method setMaxForce
+ * @param {Number} maxForce
+ */
+DistanceConstraint.prototype.setMaxForce = function(maxForce){
+    var normal = this.equations[0];
+    normal.minForce = -maxForce;
+    normal.maxForce =  maxForce;
+};
+
+/**
+ * Get the max force
+ * @method getMaxForce
+ * @return {Number}
+ */
+DistanceConstraint.prototype.getMaxForce = function(){
+    var normal = this.equations[0];
+    return normal.maxForce;
+};
+
+},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){
+var Constraint = _dereq_('./Constraint')
+,   Equation = _dereq_('../equations/Equation')
+,   AngleLockEquation = _dereq_('../equations/AngleLockEquation')
+,   vec2 = _dereq_('../math/vec2');
+
+module.exports = GearConstraint;
+
+/**
+ * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB.
+ * @class GearConstraint
+ * @constructor
+ * @author schteppe
+ * @param {Body}            bodyA
+ * @param {Body}            bodyB
+ * @param {Object}          [options]
+ * @param {Number}          [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for).
+ * @param {Number}          [options.ratio=1] Gear ratio.
+ * @param {Number}          [options.maxTorque] Maximum torque to apply.
+ * @extends Constraint
+ *
+ * @example
+ *     var constraint = new GearConstraint(bodyA, bodyB);
+ *     world.addConstraint(constraint);
+ *
+ * @example
+ *     var constraint = new GearConstraint(bodyA, bodyB, {
+ *         ratio: 2,
+ *         maxTorque: 1000
+ *     });
+ *     world.addConstraint(constraint);
+ */
+function GearConstraint(bodyA, bodyB, options){
+    options = options || {};
+
+    Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options);
+
+    /**
+     * The gear ratio.
+     * @property ratio
+     * @type {Number}
+     */
+    this.ratio = options.ratio !== undefined ? options.ratio : 1;
+
+    /**
+     * The relative angle
+     * @property angle
+     * @type {Number}
+     */
+    this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle;
+
+    // Send same parameters to the equation
+    options.angle = this.angle;
+    options.ratio = this.ratio;
+
+    this.equations = [
+        new AngleLockEquation(bodyA,bodyB,options),
+    ];
+
+    // Set max torque
+    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;
+};
+
+/**
+ * Set the max torque for the constraint.
+ * @method setMaxTorque
+ * @param {Number} torque
+ */
+GearConstraint.prototype.setMaxTorque = function(torque){
+    this.equations[0].setMaxTorque(torque);
+};
+
+/**
+ * Get the max torque for the constraint.
+ * @method getMaxTorque
+ * @return {Number}
+ */
+GearConstraint.prototype.getMaxTorque = function(torque){
+    return this.equations[0].maxForce;
+};
+},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){
+var Constraint = _dereq_('./Constraint')
+,   vec2 = _dereq_('../math/vec2')
+,   Equation = _dereq_('../equations/Equation');
+
+module.exports = LockConstraint;
+
+/**
+ * Locks the relative position and rotation between two bodies.
+ *
+ * @class LockConstraint
+ * @constructor
+ * @author schteppe
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Object} [options]
+ * @param {Array}  [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions.
+ * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles.
+ * @param {number} [options.maxForce]
+ * @extends Constraint
+ *
+ * @example
+ *     // Locks the relative position and rotation between bodyA and bodyB
+ *     var constraint = new LockConstraint(bodyA, bodyB);
+ *     world.addConstraint(constraint);
+ */
+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;
+
+    // Use 3 equations:
+    // gx =   (xj - xi - l) * xhat = 0
+    // gy =   (xj - xi - l) * yhat = 0
+    // gr =   (xi - xj + r) * that = 0
+    //
+    // ...where:
+    //   l is the localOffsetB vector rotated to world in bodyA frame
+    //   r is the same vector but reversed and rotated from bodyB frame
+    //   xhat, yhat are world axis vectors
+    //   that is the tangent of r
+    //
+    // For the first two constraints, we get
+    // G*W = (vj - vi - ldot  ) * xhat
+    //     = (vj - vi - wi x l) * xhat
+    //
+    // Since (wi x l) * xhat = (l x xhat) * wi, we get
+    // G*W = [ -1   0   (-l x xhat)  1   0   0] * [vi wi vj wj]
+    //
+    // The last constraint gives
+    // GW = (vi - vj + wj x r) * that
+    //    = [  that   0  -that  (r x t) ]
+
+    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);
+    };
+
+    /**
+     * The offset of bodyB in bodyA's frame.
+     * @property {Array} localOffsetB
+     */
+    this.localOffsetB = vec2.create();
+    if(options.localOffsetB){
+        vec2.copy(this.localOffsetB, options.localOffsetB);
+    } else {
+        // Construct from current positions
+        vec2.sub(this.localOffsetB, bodyB.position, bodyA.position);
+        vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle);
+    }
+
+    /**
+     * The offset angle of bodyB in bodyA's frame.
+     * @property {Number} localAngleB
+     */
+    this.localAngleB = 0;
+    if(typeof(options.localAngleB) === 'number'){
+        this.localAngleB = options.localAngleB;
+    } else {
+        // Construct
+        this.localAngleB = bodyB.angle - bodyA.angle;
+    }
+
+    this.equations.push(x, y, rot);
+    this.setMaxForce(maxForce);
+}
+LockConstraint.prototype = new Constraint();
+LockConstraint.prototype.constructor = LockConstraint;
+
+/**
+ * Set the maximum force to be applied.
+ * @method setMaxForce
+ * @param {Number} force
+ */
+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;
+    }
+};
+
+/**
+ * Get the max force.
+ * @method getMaxForce
+ * @return {Number}
+ */
+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(_dereq_,module,exports){
+var Constraint = _dereq_('./Constraint')
+,   ContactEquation = _dereq_('../equations/ContactEquation')
+,   Equation = _dereq_('../equations/Equation')
+,   vec2 = _dereq_('../math/vec2')
+,   RotationalLockEquation = _dereq_('../equations/RotationalLockEquation');
+
+module.exports = PrismaticConstraint;
+
+/**
+ * Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>. Also called "slider constraint".
+ *
+ * @class PrismaticConstraint
+ * @constructor
+ * @extends Constraint
+ * @author schteppe
+ * @param {Body}    bodyA
+ * @param {Body}    bodyB
+ * @param {Object}  [options]
+ * @param {Number}  [options.maxForce]                Max force to be applied by the constraint
+ * @param {Array}   [options.localAnchorA]            Body A's anchor point, defined in its own local frame.
+ * @param {Array}   [options.localAnchorB]            Body B's anchor point, defined in its own local frame.
+ * @param {Array}   [options.localAxisA]              An axis, defined in body A frame, that body B's anchor point may slide along.
+ * @param {Boolean} [options.disableRotationalLock]   If set to true, bodyB will be free to rotate around its anchor point.
+ * @param {Number}  [options.upperLimit]
+ * @param {Number}  [options.lowerLimit]
+ * @todo Ability to create using only a point and a worldAxis
+ */
+function PrismaticConstraint(bodyA, bodyB, options){
+    options = options || {};
+    Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options);
+
+    // Get anchors
+    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); }
+
+    /**
+     * @property localAnchorA
+     * @type {Array}
+     */
+    this.localAnchorA = localAnchorA;
+
+    /**
+     * @property localAnchorB
+     * @type {Array}
+     */
+    this.localAnchorB = localAnchorB;
+
+    /**
+     * @property localAxisA
+     * @type {Array}
+     */
+    this.localAxisA = localAxisA;
+
+    /*
+
+    The constraint violation for the common axis point is
+
+        g = ( xj + rj - xi - ri ) * t   :=  gg*t
+
+    where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame.
+
+        gdot =  ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t )
+
+    Note the use of the chain rule. Now we identify the jacobian
+
+        G*W = [ -t      -ri x t + t x gg     t    rj x t ] * [vi wi vj wj]
+
+    The rotational part is just a rotation lock.
+
+     */
+
+    var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE;
+
+    // Translational part
+    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(){
+        // g = ( xj + rj - xi - ri ) * t
+        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);
+
+    // Rotational part
+    if(!options.disableRotationalLock){
+        var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce);
+        this.equations.push(rot);
+    }
+
+    /**
+     * The position of anchor A relative to anchor B, along the constraint axis.
+     * @property position
+     * @type {Number}
+     */
+    this.position = 0;
+
+    // Is this one used at all?
+    this.velocity = 0;
+
+    /**
+     * Set to true to enable lower limit.
+     * @property lowerLimitEnabled
+     * @type {Boolean}
+     */
+    this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false;
+
+    /**
+     * Set to true to enable upper limit.
+     * @property upperLimitEnabled
+     * @type {Boolean}
+     */
+    this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false;
+
+    /**
+     * Lower constraint limit. The constraint position is forced to be larger than this value.
+     * @property lowerLimit
+     * @type {Number}
+     */
+    this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0;
+
+    /**
+     * Upper constraint limit. The constraint position is forced to be smaller than this value.
+     * @property upperLimit
+     * @type {Number}
+     */
+    this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1;
+
+    // Equations used for limits
+    this.upperLimitEquation = new ContactEquation(bodyA,bodyB);
+    this.lowerLimitEquation = new ContactEquation(bodyA,bodyB);
+
+    // Set max/min forces
+    this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0;
+    this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce;
+
+    /**
+     * Equation used for the motor.
+     * @property motorEquation
+     * @type {Equation}
+     */
+    this.motorEquation = new Equation(bodyA,bodyB);
+
+    /**
+     * The current motor state. Enable or disable the motor using .enableMotor
+     * @property motorEnabled
+     * @type {Boolean}
+     */
+    this.motorEnabled = false;
+
+    /**
+     * Set the target speed for the motor.
+     * @property motorSpeed
+     * @type {Number}
+     */
+    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();
+
+/**
+ * Update the constraint equations. Should be done if any of the bodies changed position, before solving.
+ * @method update
+ */
+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();
+
+    // Transform local things to world
+    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);
+
+    // Motor
+    if(this.motorEnabled){
+        // G = [ a     a x ri   -a   -a x rj ]
+        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);
+    }
+
+    /*
+        Limits strategy:
+        Add contact equation, with normal along the constraint axis.
+        min/maxForce is set so the constraint is repulsive in the correct direction.
+        Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit.
+
+                 ^
+                 |
+      upperLimit x
+                 |    ------
+         anchorB x<---|  B |
+                 |    |    |
+        ------   |    ------
+        |    |   |
+        |  A |-->x anchorA
+        ------   |
+                 x lowerLimit
+                 |
+                axis
+     */
+
+
+    if(this.upperLimitEnabled && relPosition > upperLimit){
+        // Update contact constraint normal, etc
+        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){
+        // Update contact constraint normal, etc
+        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);
+        }
+    }
+};
+
+/**
+ * Enable the motor
+ * @method enableMotor
+ */
+PrismaticConstraint.prototype.enableMotor = function(){
+    if(this.motorEnabled){
+        return;
+    }
+    this.equations.push(this.motorEquation);
+    this.motorEnabled = true;
+};
+
+/**
+ * Disable the rotational motor
+ * @method disableMotor
+ */
+PrismaticConstraint.prototype.disableMotor = function(){
+    if(!this.motorEnabled){
+        return;
+    }
+    var i = this.equations.indexOf(this.motorEquation);
+    this.equations.splice(i,1);
+    this.motorEnabled = false;
+};
+
+/**
+ * Set the constraint limits.
+ * @method setLimits
+ * @param {number} lower Lower limit.
+ * @param {number} upper Upper limit.
+ */
+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(_dereq_,module,exports){
+var Constraint = _dereq_('./Constraint')
+,   Equation = _dereq_('../equations/Equation')
+,   RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation')
+,   RotationalLockEquation = _dereq_('../equations/RotationalLockEquation')
+,   vec2 = _dereq_('../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();
+
+/**
+ * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
+ * @class RevoluteConstraint
+ * @constructor
+ * @author schteppe
+ * @param {Body}    bodyA
+ * @param {Body}    bodyB
+ * @param {Object}  [options]
+ * @param {Array}   [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
+ * @param {Array}   [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to.
+ * @param {Array}   [options.localPivotB] See localPivotA.
+ * @param {Number}  [options.maxForce] The maximum force that should be applied to constrain the bodies.
+ * @extends Constraint
+ *
+ * @example
+ *     // This will create a revolute constraint between two bodies with pivot point in between them.
+ *     var bodyA = new Body({ mass: 1, position: [-1, 0] });
+ *     var bodyB = new Body({ mass: 1, position: [1, 0] });
+ *     var constraint = new RevoluteConstraint(bodyA, bodyB, {
+ *         worldPivot: [0, 0]
+ *     });
+ *     world.addConstraint(constraint);
+ *
+ *     // Using body-local pivot points, the constraint could have been constructed like this:
+ *     var constraint = new RevoluteConstraint(bodyA, bodyB, {
+ *         localPivotA: [1, 0],
+ *         localPivotB: [-1, 0]
+ *     });
+ */
+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;
+
+    /**
+     * @property {Array} pivotA
+     */
+    this.pivotA = vec2.create();
+
+    /**
+     * @property {Array} pivotB
+     */
+    this.pivotB = vec2.create();
+
+    if(options.worldPivot){
+        // Compute pivotA and pivotB
+        vec2.sub(this.pivotA, options.worldPivot, bodyA.position);
+        vec2.sub(this.pivotB, options.worldPivot, bodyB.position);
+        // Rotate to local coordinate system
+        vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle);
+        vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle);
+    } else {
+        // Get pivotA and pivotB
+        vec2.copy(this.pivotA, options.localPivotA);
+        vec2.copy(this.pivotB, options.localPivotB);
+    }
+
+    // Equations to be fed to the solver
+    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);
+
+    /**
+     * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor.
+     * @property {Boolean} motorEnabled
+     * @readOnly
+     */
+    this.motorEnabled = false;
+
+    /**
+     * The constraint position.
+     * @property angle
+     * @type {Number}
+     * @readOnly
+     */
+    this.angle = 0;
+
+    /**
+     * Set to true to enable lower limit
+     * @property lowerLimitEnabled
+     * @type {Boolean}
+     */
+    this.lowerLimitEnabled = false;
+
+    /**
+     * Set to true to enable upper limit
+     * @property upperLimitEnabled
+     * @type {Boolean}
+     */
+    this.upperLimitEnabled = false;
+
+    /**
+     * The lower limit on the constraint angle.
+     * @property lowerLimit
+     * @type {Boolean}
+     */
+    this.lowerLimit = 0;
+
+    /**
+     * The upper limit on the constraint angle.
+     * @property upperLimit
+     * @type {Boolean}
+     */
+    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;
+
+/**
+ * Set the constraint angle limits.
+ * @method setLimits
+ * @param {number} lower Lower angle limit.
+ * @param {number} upper Upper angle limit.
+ */
+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);
+        }
+    }
+
+    /*
+
+    The constraint violation is
+
+        g = xj + rj - xi - ri
+
+    ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate:
+
+        gdot = vj + wj x rj - vi - wi x ri
+
+    We split this into x and y directions. (let x and y be unit vectors along the respective axes)
+
+        gdot * x = ( vj + wj x rj - vi - wi x ri ) * x
+                 = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x
+                 = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi
+                 = [ -x   -(ri x x)   x   (rj x x)] * [vi wi vj wj]
+                 = G*W
+
+    ...and similar for y. We have then identified the jacobian entries for x and y directions:
+
+        Gx = [ x   (rj x x)   -x   -(ri x x)]
+        Gy = [ y   (rj x y)   -y   -(ri x y)]
+
+     */
+
+    vec2.rotate(worldPivotA, pivotA, bodyA.angle);
+    vec2.rotate(worldPivotB, pivotB, bodyB.angle);
+
+    // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc
+
+    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);
+};
+
+/**
+ * Enable the rotational motor
+ * @method enableMotor
+ */
+RevoluteConstraint.prototype.enableMotor = function(){
+    if(this.motorEnabled){
+        return;
+    }
+    this.equations.push(this.motorEquation);
+    this.motorEnabled = true;
+};
+
+/**
+ * Disable the rotational motor
+ * @method disableMotor
+ */
+RevoluteConstraint.prototype.disableMotor = function(){
+    if(!this.motorEnabled){
+        return;
+    }
+    var i = this.equations.indexOf(this.motorEquation);
+    this.equations.splice(i,1);
+    this.motorEnabled = false;
+};
+
+/**
+ * Check if the motor is enabled.
+ * @method motorIsEnabled
+ * @deprecated use property motorEnabled instead.
+ * @return {Boolean}
+ */
+RevoluteConstraint.prototype.motorIsEnabled = function(){
+    return !!this.motorEnabled;
+};
+
+/**
+ * Set the speed of the rotational constraint motor
+ * @method setMotorSpeed
+ * @param  {Number} speed
+ */
+RevoluteConstraint.prototype.setMotorSpeed = function(speed){
+    if(!this.motorEnabled){
+        return;
+    }
+    var i = this.equations.indexOf(this.motorEquation);
+    this.equations[i].relativeVelocity = speed;
+};
+
+/**
+ * Get the speed of the rotational constraint motor
+ * @method getMotorSpeed
+ * @return {Number} The current speed, or false if the motor is not enabled.
+ */
+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(_dereq_,module,exports){
+var Equation = _dereq_("./Equation"),
+    vec2 = _dereq_('../math/vec2');
+
+module.exports = AngleLockEquation;
+
+/**
+ * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
+ *
+ * @class AngleLockEquation
+ * @constructor
+ * @extends Equation
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Object} [options]
+ * @param {Number} [options.angle] Angle to add to the local vector in body A.
+ * @param {Number} [options.ratio] Gear ratio
+ */
+function AngleLockEquation(bodyA, bodyB, options){
+    options = options || {};
+    Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE);
+    this.angle = options.angle || 0;
+
+    /**
+     * The gear ratio.
+     * @property {Number} ratio
+     * @private
+     * @see setRatio
+     */
+    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;
+};
+
+/**
+ * Set the gear ratio for this equation
+ * @method setRatio
+ * @param {Number} ratio
+ */
+AngleLockEquation.prototype.setRatio = function(ratio){
+    var G = this.G;
+    G[2] =  ratio;
+    G[5] = -1;
+    this.ratio = ratio;
+};
+
+/**
+ * Set the max force for the equation.
+ * @method setMaxTorque
+ * @param {Number} torque
+ */
+AngleLockEquation.prototype.setMaxTorque = function(torque){
+    this.maxForce =  torque;
+    this.minForce = -torque;
+};
+
+},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){
+var Equation = _dereq_("./Equation"),
+    vec2 = _dereq_('../math/vec2');
+
+module.exports = ContactEquation;
+
+/**
+ * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive.
+ *
+ * @class ContactEquation
+ * @constructor
+ * @extends Equation
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ */
+function ContactEquation(bodyA, bodyB){
+    Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE);
+
+    /**
+     * Vector from body i center of mass to the contact point.
+     * @property contactPointA
+     * @type {Array}
+     */
+    this.contactPointA = vec2.create();
+    this.penetrationVec = vec2.create();
+
+    /**
+     * World-oriented vector from body A center of mass to the contact point.
+     * @property contactPointB
+     * @type {Array}
+     */
+    this.contactPointB = vec2.create();
+
+    /**
+     * The normal vector, pointing out of body i
+     * @property normalA
+     * @type {Array}
+     */
+    this.normalA = vec2.create();
+
+    /**
+     * The restitution to use (0=no bounciness, 1=max bounciness).
+     * @property restitution
+     * @type {Number}
+     */
+    this.restitution = 0;
+
+    /**
+     * This property is set to true if this is the first impact between the bodies (not persistant contact).
+     * @property firstImpact
+     * @type {Boolean}
+     * @readOnly
+     */
+    this.firstImpact = false;
+
+    /**
+     * The shape in body i that triggered this contact.
+     * @property shapeA
+     * @type {Shape}
+     */
+    this.shapeA = null;
+
+    /**
+     * The shape in body j that triggered this contact.
+     * @property shapeB
+     * @type {Shape}
+     */
+    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;
+
+    // Caluclate cross products
+    var rixn = vec2.crossLength(ri,n),
+        rjxn = vec2.crossLength(rj,n);
+
+    // G = [-n -rixn n rjxn]
+    G[0] = -n[0];
+    G[1] = -n[1];
+    G[2] = -rixn;
+    G[3] = n[0];
+    G[4] = n[1];
+    G[5] = rjxn;
+
+    // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector
+    vec2.add(penetrationVec,xj,rj);
+    vec2.sub(penetrationVec,penetrationVec,xi);
+    vec2.sub(penetrationVec,penetrationVec,ri);
+
+    // Compute iteration
+    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;
+};
+
+},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){
+module.exports = Equation;
+
+var vec2 = _dereq_('../math/vec2'),
+    Utils = _dereq_('../utils/Utils'),
+    Body = _dereq_('../objects/Body');
+
+/**
+ * Base class for constraint equations.
+ * @class Equation
+ * @constructor
+ * @param {Body} bodyA First body participating in the equation
+ * @param {Body} bodyB Second body participating in the equation
+ * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE
+ * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE
+ */
+function Equation(bodyA, bodyB, minForce, maxForce){
+
+    /**
+     * Minimum force to apply when solving.
+     * @property minForce
+     * @type {Number}
+     */
+    this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce;
+
+    /**
+     * Max force to apply when solving.
+     * @property maxForce
+     * @type {Number}
+     */
+    this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce;
+
+    /**
+     * First body participating in the constraint
+     * @property bodyA
+     * @type {Body}
+     */
+    this.bodyA = bodyA;
+
+    /**
+     * Second body participating in the constraint
+     * @property bodyB
+     * @type {Body}
+     */
+    this.bodyB = bodyB;
+
+    /**
+     * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation.
+     * @property stiffness
+     * @type {Number}
+     */
+    this.stiffness = Equation.DEFAULT_STIFFNESS;
+
+    /**
+     * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps.
+     * @property relaxation
+     * @type {Number}
+     */
+    this.relaxation = Equation.DEFAULT_RELAXATION;
+
+    /**
+     * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle).
+     * @property G
+     * @type {Array}
+     */
+    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;
+
+    /**
+     * Indicates if stiffness or relaxation was changed.
+     * @property {Boolean} needsUpdate
+     */
+    this.needsUpdate = true;
+
+    /**
+     * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint.
+     * @property multiplier
+     * @type {Number}
+     */
+    this.multiplier = 0;
+
+    /**
+     * Relative velocity.
+     * @property {Number} relativeVelocity
+     */
+    this.relativeVelocity = 0;
+
+    /**
+     * Whether this equation is enabled or not. If true, it will be added to the solver.
+     * @property {Boolean} enabled
+     */
+    this.enabled = true;
+}
+Equation.prototype.constructor = Equation;
+
+/**
+ * The default stiffness when creating a new Equation.
+ * @static
+ * @property {Number} DEFAULT_STIFFNESS
+ * @default 1e6
+ */
+Equation.DEFAULT_STIFFNESS = 1e6;
+
+/**
+ * The default relaxation when creating a new Equation.
+ * @static
+ * @property {Number} DEFAULT_RELAXATION
+ * @default 4
+ */
+Equation.DEFAULT_RELAXATION = 4;
+
+/**
+ * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>.
+ * @method update
+ */
+Equation.prototype.update = function(){
+    var k = this.stiffness,
+        d = this.relaxation,
+        h = this.timeStep;
+
+    this.a = 4.0 / (h * (1 + 4 * d));
+    this.b = (4.0 * d) / (1 + 4 * d);
+    this.epsilon = 4.0 / (h * h * k * (1 + 4 * d));
+
+    this.needsUpdate = false;
+};
+
+/**
+ * Multiply a jacobian entry with corresponding positions or velocities
+ * @method gmult
+ * @return {Number}
+ */
+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;
+};
+
+/**
+ * Computes the RHS of the SPOOK equation
+ * @method computeB
+ * @return {Number}
+ */
+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;
+};
+
+/**
+ * Computes G\*q, where q are the generalized body coordinates
+ * @method computeGq
+ * @return {Number}
+ */
+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;
+};
+
+/**
+ * Computes G\*W, where W are the body velocities
+ * @method computeGW
+ * @return {Number}
+ */
+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;
+};
+
+/**
+ * Computes G\*Wlambda, where W are the body velocities
+ * @method computeGWlambda
+ * @return {Number}
+ */
+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);
+};
+
+/**
+ * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
+ * @method computeGiMf
+ * @return {Number}
+ */
+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);
+};
+
+/**
+ * Computes G\*inv(M)\*G'
+ * @method computeGiMGt
+ * @return {Number}
+ */
+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();
+
+/**
+ * Add constraint velocity to the bodies.
+ * @method addToWlambda
+ * @param {Number} deltalambda
+ */
+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];
+
+    // Add to linear velocity
+    // v_lambda += inv(M) * delta_lamba * G
+    vec2.scale(temp, Gi, invMassi*deltalambda);
+    vec2.multiply(temp, temp, bi.massMultiplier);
+    vec2.add( bi.vlambda, bi.vlambda, temp);
+    // This impulse is in the offset frame
+    // Also add contribution to angular
+    //bi.wlambda -= vec2.crossLength(temp,ri);
+    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 -= vec2.crossLength(temp,rj);
+    bj.wlambda += invIj * G[5] * deltalambda;
+};
+
+/**
+ * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps
+ * @method computeInvC
+ * @param  {Number} eps
+ * @return {Number}
+ */
+Equation.prototype.computeInvC = function(eps){
+    return 1.0 / (this.computeGiMGt() + eps);
+};
+
+},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   Equation = _dereq_('./Equation')
+,   Utils = _dereq_('../utils/Utils');
+
+module.exports = FrictionEquation;
+
+/**
+ * Constrains the slipping in a contact along a tangent
+ *
+ * @class FrictionEquation
+ * @constructor
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Number} slipForce
+ * @extends Equation
+ */
+function FrictionEquation(bodyA, bodyB, slipForce){
+    Equation.call(this, bodyA, bodyB, -slipForce, slipForce);
+
+    /**
+     * Relative vector from center of body A to the contact point, world oriented.
+     * @property contactPointA
+     * @type {Array}
+     */
+    this.contactPointA = vec2.create();
+
+    /**
+     * Relative vector from center of body B to the contact point, world oriented.
+     * @property contactPointB
+     * @type {Array}
+     */
+    this.contactPointB = vec2.create();
+
+    /**
+     * Tangent vector that the friction force will act along. World oriented.
+     * @property t
+     * @type {Array}
+     */
+    this.t = vec2.create();
+
+    /**
+     * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average.
+     * @property contactEquations
+     * @type {ContactEquation}
+     */
+    this.contactEquations = [];
+
+    /**
+     * The shape in body i that triggered this friction.
+     * @property shapeA
+     * @type {Shape}
+     * @todo Needed? The shape can be looked up via contactEquation.shapeA...
+     */
+    this.shapeA = null;
+
+    /**
+     * The shape in body j that triggered this friction.
+     * @property shapeB
+     * @type {Shape}
+     * @todo Needed? The shape can be looked up via contactEquation.shapeB...
+     */
+    this.shapeB = null;
+
+    /**
+     * The friction coefficient to use.
+     * @property frictionCoefficient
+     * @type {Number}
+     */
+    this.frictionCoefficient = 0.3;
+}
+FrictionEquation.prototype = new Equation();
+FrictionEquation.prototype.constructor = FrictionEquation;
+
+/**
+ * Set the slipping condition for the constraint. The friction force cannot be
+ * larger than this value.
+ * @method setSlipForce
+ * @param  {Number} slipForce
+ */
+FrictionEquation.prototype.setSlipForce = function(slipForce){
+    this.maxForce = slipForce;
+    this.minForce = -slipForce;
+};
+
+/**
+ * Get the max force for the constraint.
+ * @method getSlipForce
+ * @return {Number}
+ */
+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 = [-t -rixt t rjxt]
+    // And remember, this is a pure velocity constraint, g is always zero!
+    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 = /* - g * a  */ - GW * b - h*GiMf;
+
+    return B;
+};
+
+},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){
+var Equation = _dereq_("./Equation"),
+    vec2 = _dereq_('../math/vec2');
+
+module.exports = RotationalLockEquation;
+
+/**
+ * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
+ *
+ * @class RotationalLockEquation
+ * @constructor
+ * @extends Equation
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Object} [options]
+ * @param {Number} [options.angle] Angle to add to the local vector in bodyA.
+ */
+function RotationalLockEquation(bodyA, bodyB, options){
+    options = options || {};
+    Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE);
+
+    /**
+     * @property {number} angle
+     */
+    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(_dereq_,module,exports){
+var Equation = _dereq_("./Equation"),
+    vec2 = _dereq_('../math/vec2');
+
+module.exports = RotationalVelocityEquation;
+
+/**
+ * Syncs rotational velocity of two bodies, or sets a relative velocity (motor).
+ *
+ * @class RotationalVelocityEquation
+ * @constructor
+ * @extends Equation
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ */
+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(_dereq_,module,exports){
+/**
+ * Base class for objects that dispatches events.
+ * @class EventEmitter
+ * @constructor
+ */
+var EventEmitter = function () {};
+
+module.exports = EventEmitter;
+
+EventEmitter.prototype = {
+    constructor: EventEmitter,
+
+    /**
+     * Add an event listener
+     * @method on
+     * @param  {String} type
+     * @param  {Function} listener
+     * @return {EventEmitter} The self object, for chainability.
+     */
+    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;
+    },
+
+    /**
+     * Check if an event listener is added
+     * @method has
+     * @param  {String} type
+     * @param  {Function} listener
+     * @return {Boolean}
+     */
+    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;
+    },
+
+    /**
+     * Remove an event listener
+     * @method off
+     * @param  {String} type
+     * @param  {Function} listener
+     * @return {EventEmitter} The self object, for chainability.
+     */
+    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 an event.
+     * @method emit
+     * @param  {Object} event
+     * @param  {String} event.type
+     * @return {EventEmitter} The self object, for chainability.
+     */
+    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(_dereq_,module,exports){
+var Material = _dereq_('./Material');
+var Equation = _dereq_('../equations/Equation');
+
+module.exports = ContactMaterial;
+
+/**
+ * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters.
+ * @class ContactMaterial
+ * @constructor
+ * @param {Material} materialA
+ * @param {Material} materialB
+ * @param {Object}   [options]
+ * @param {Number}   [options.friction=0.3]       Friction coefficient.
+ * @param {Number}   [options.restitution=0]      Restitution coefficient aka "bounciness".
+ * @param {Number}   [options.stiffness]          ContactEquation stiffness.
+ * @param {Number}   [options.relaxation]         ContactEquation relaxation.
+ * @param {Number}   [options.frictionStiffness]  FrictionEquation stiffness.
+ * @param {Number}   [options.frictionRelaxation] FrictionEquation relaxation.
+ * @param {Number}   [options.surfaceVelocity=0]  Surface velocity.
+ * @author schteppe
+ */
+function ContactMaterial(materialA, materialB, options){
+    options = options || {};
+
+    if(!(materialA instanceof Material) || !(materialB instanceof Material)){
+        throw new Error("First two arguments must be Material instances.");
+    }
+
+    /**
+     * The contact material identifier
+     * @property id
+     * @type {Number}
+     */
+    this.id = ContactMaterial.idCounter++;
+
+    /**
+     * First material participating in the contact material
+     * @property materialA
+     * @type {Material}
+     */
+    this.materialA = materialA;
+
+    /**
+     * Second material participating in the contact material
+     * @property materialB
+     * @type {Material}
+     */
+    this.materialB = materialB;
+
+    /**
+     * Friction to use in the contact of these two materials
+     * @property friction
+     * @type {Number}
+     */
+    this.friction    =  typeof(options.friction)    !== "undefined" ?   Number(options.friction)    : 0.3;
+
+    /**
+     * Restitution to use in the contact of these two materials
+     * @property restitution
+     * @type {Number}
+     */
+    this.restitution =  typeof(options.restitution) !== "undefined" ?   Number(options.restitution) : 0.0;
+
+    /**
+     * Stiffness of the resulting ContactEquation that this ContactMaterial generate
+     * @property stiffness
+     * @type {Number}
+     */
+    this.stiffness =            typeof(options.stiffness)           !== "undefined" ?   Number(options.stiffness)   : Equation.DEFAULT_STIFFNESS;
+
+    /**
+     * Relaxation of the resulting ContactEquation that this ContactMaterial generate
+     * @property relaxation
+     * @type {Number}
+     */
+    this.relaxation =           typeof(options.relaxation)          !== "undefined" ?   Number(options.relaxation)  : Equation.DEFAULT_RELAXATION;
+
+    /**
+     * Stiffness of the resulting FrictionEquation that this ContactMaterial generate
+     * @property frictionStiffness
+     * @type {Number}
+     */
+    this.frictionStiffness =    typeof(options.frictionStiffness)   !== "undefined" ?   Number(options.frictionStiffness)   : Equation.DEFAULT_STIFFNESS;
+
+    /**
+     * Relaxation of the resulting FrictionEquation that this ContactMaterial generate
+     * @property frictionRelaxation
+     * @type {Number}
+     */
+    this.frictionRelaxation =   typeof(options.frictionRelaxation)  !== "undefined" ?   Number(options.frictionRelaxation)  : Equation.DEFAULT_RELAXATION;
+
+    /**
+     * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
+     * @property {Number} surfaceVelocity
+     */
+    this.surfaceVelocity = typeof(options.surfaceVelocity)    !== "undefined" ?   Number(options.surfaceVelocity)    : 0;
+
+    /**
+     * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts".
+     * @property contactSkinSize
+     * @type {Number}
+     */
+    this.contactSkinSize = 0.005;
+}
+
+ContactMaterial.idCounter = 0;
+
+},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){
+module.exports = Material;
+
+/**
+ * Defines a physics material.
+ * @class Material
+ * @constructor
+ * @param {number} id Material identifier
+ * @author schteppe
+ */
+function Material(id){
+    /**
+     * The material identifier
+     * @property id
+     * @type {Number}
+     */
+    this.id = id || Material.idCounter++;
+}
+
+Material.idCounter = 0;
+
+},{}],29:[function(_dereq_,module,exports){
+
+    /*
+        PolyK library
+        url: http://polyk.ivank.net
+        Released under MIT licence.
+
+        Copyright (c) 2012 Ivan Kuckir
+
+        Permission is hereby granted, free of charge, to any person
+        obtaining a copy of this software and associated documentation
+        files (the "Software"), to deal in the Software without
+        restriction, including without limitation the rights to use,
+        copy, modify, merge, publish, distribute, sublicense, and/or sell
+        copies of the Software, and to permit persons to whom the
+        Software is furnished to do so, subject to the following
+        conditions:
+
+        The above copyright notice and this permission notice shall be
+        included in all copies or substantial portions of the Software.
+
+        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+        OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+        NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+        HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+        WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+        FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+        OTHER DEALINGS IN THE SOFTWARE.
+    */
+
+    var PolyK = {};
+
+    /*
+        Is Polygon self-intersecting?
+
+        O(n^2)
+    */
+    /*
+    PolyK.IsSimple = function(p)
+    {
+        var n = p.length>>1;
+        if(n<4) return true;
+        var a1 = new PolyK._P(), a2 = new PolyK._P();
+        var b1 = new PolyK._P(), b2 = new PolyK._P();
+        var c = new PolyK._P();
+
+        for(var i=0; i<n; i++)
+        {
+            a1.x = p[2*i  ];
+            a1.y = p[2*i+1];
+            if(i==n-1)  { a2.x = p[0    ];  a2.y = p[1    ]; }
+            else        { a2.x = p[2*i+2];  a2.y = p[2*i+3]; }
+
+            for(var j=0; j<n; j++)
+            {
+                if(Math.abs(i-j) < 2) continue;
+                if(j==n-1 && i==0) continue;
+                if(i==n-1 && j==0) continue;
+
+                b1.x = p[2*j  ];
+                b1.y = p[2*j+1];
+                if(j==n-1)  { b2.x = p[0    ];  b2.y = p[1    ]; }
+                else        { b2.x = p[2*j+2];  b2.y = p[2*j+3]; }
+
+                if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false;
+            }
+        }
+        return true;
+    }
+
+    PolyK.IsConvex = function(p)
+    {
+        if(p.length<6) return true;
+        var l = p.length - 4;
+        for(var i=0; i<l; i+=2)
+            if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false;
+        if(!PolyK._convex(p[l  ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false;
+        if(!PolyK._convex(p[l+2], p[l+3], p[0  ], p[1  ], p[2], p[3])) return false;
+        return true;
+    }
+    */
+    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 * 0.5;
+    }
+    /*
+    PolyK.GetAABB = function(p)
+    {
+        var minx = Infinity;
+        var miny = Infinity;
+        var maxx = -minx;
+        var maxy = -miny;
+        for(var i=0; i<p.length; i+=2)
+        {
+            minx = Math.min(minx, p[i  ]);
+            maxx = Math.max(maxx, p[i  ]);
+            miny = Math.min(miny, p[i+1]);
+            maxy = Math.max(maxy, p[i+1]);
+        }
+        return {x:minx, y:miny, width:maxx-minx, height:maxy-miny};
+    }
+    */
+
+    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;      // no convex angles :(
+        }
+        tgs.push(avl[0], avl[1], avl[2]);
+        return tgs;
+    }
+    /*
+    PolyK.ContainsPoint = function(p, px, py)
+    {
+        var n = p.length>>1;
+        var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py;
+        var depth = 0;
+        for(var i=0; i<n; i++)
+        {
+            ax = bx;  ay = by;
+            bx = p[2*i  ] - px;
+            by = p[2*i+1] - py;
+            if(ay< 0 && by< 0) continue;    // both "up" or both "donw"
+            if(ay>=0 && by>=0) continue;    // both "up" or both "donw"
+            if(ax< 0 && bx< 0) continue;
+
+            var lx = ax + (bx-ax)*(-ay)/(by-ay);
+            if(lx>0) depth++;
+        }
+        return (depth & 1) == 1;
+    }
+
+    PolyK.Slice = function(p, ax, ay, bx, by)
+    {
+        if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)];
+
+        var a = new PolyK._P(ax, ay);
+        var b = new PolyK._P(bx, by);
+        var iscs = [];  // intersections
+        var ps = [];    // points
+        for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1]));
+
+        for(var i=0; i<ps.length; i++)
+        {
+            var isc = new PolyK._P(0,0);
+            isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc);
+
+            if(isc)
+            {
+                isc.flag = true;
+                iscs.push(isc);
+                ps.splice(i+1,0,isc);
+                i++;
+            }
+        }
+        if(iscs.length == 0) return [p.slice(0)];
+        var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); }
+        iscs.sort(comp);
+
+        var pgs = [];
+        var dir = 0;
+        while(iscs.length > 0)
+        {
+            var n = ps.length;
+            var i0 = iscs[0];
+            var i1 = iscs[1];
+            var ind0 = ps.indexOf(i0);
+            var ind1 = ps.indexOf(i1);
+            var solved = false;
+
+            if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
+            else
+            {
+                i0 = iscs[1];
+                i1 = iscs[0];
+                ind0 = ps.indexOf(i0);
+                ind1 = ps.indexOf(i1);
+                if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
+            }
+            if(solved)
+            {
+                dir--;
+                var pgn = PolyK._getPoints(ps, ind0, ind1);
+                pgs.push(pgn);
+                ps = PolyK._getPoints(ps, ind1, ind0);
+                i0.flag = i1.flag = false;
+                iscs.splice(0,2);
+                if(iscs.length == 0) pgs.push(ps);
+            }
+            else { dir++; iscs.reverse(); }
+            if(dir>1) break;
+        }
+        var result = [];
+        for(var i=0; i<pgs.length; i++)
+        {
+            var pg = pgs[i];
+            var npg = [];
+            for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y);
+            result.push(npg);
+        }
+        return result;
+    }
+
+    PolyK.Raycast = function(p, x, y, dx, dy, isc)
+    {
+        var l = p.length - 2;
+        var tp = PolyK._tp;
+        var a1 = tp[0], a2 = tp[1],
+        b1 = tp[2], b2 = tp[3], c = tp[4];
+        a1.x = x; a1.y = y;
+        a2.x = x+dx; a2.y = y+dy;
+
+        if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}};
+        isc.dist = Infinity;
+
+        for(var i=0; i<l; i+=2)
+        {
+            b1.x = p[i  ];  b1.y = p[i+1];
+            b2.x = p[i+2];  b2.y = p[i+3];
+            var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
+            if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc);
+        }
+        b1.x = b2.x;  b1.y = b2.y;
+        b2.x = p[0];  b2.y = p[1];
+        var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
+        if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc);
+
+        return (isc.dist != Infinity) ? isc : null;
+    }
+
+    PolyK.ClosestEdge = function(p, x, y, isc)
+    {
+        var l = p.length - 2;
+        var tp = PolyK._tp;
+        var a1 = tp[0],
+        b1 = tp[2], b2 = tp[3], c = tp[4];
+        a1.x = x; a1.y = y;
+
+        if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}};
+        isc.dist = Infinity;
+
+        for(var i=0; i<l; i+=2)
+        {
+            b1.x = p[i  ];  b1.y = p[i+1];
+            b2.x = p[i+2];  b2.y = p[i+3];
+            PolyK._pointLineDist(a1, b1, b2, i>>1, isc);
+        }
+        b1.x = b2.x;  b1.y = b2.y;
+        b2.x = p[0];  b2.y = p[1];
+        PolyK._pointLineDist(a1, b1, b2, l>>1, isc);
+
+        var idst = 1/isc.dist;
+        isc.norm.x = (x-isc.point.x)*idst;
+        isc.norm.y = (y-isc.point.y)*idst;
+        return isc;
+    }
+
+    PolyK._pointLineDist = function(p, a, b, edge, isc)
+    {
+        var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
+
+        var A = x - x1;
+        var B = y - y1;
+        var C = x2 - x1;
+        var D = y2 - y1;
+
+        var dot = A * C + B * D;
+        var len_sq = C * C + D * D;
+        var param = dot / len_sq;
+
+        var xx, yy;
+
+        if (param < 0 || (x1 == x2 && y1 == y2)) {
+            xx = x1;
+            yy = y1;
+        }
+        else if (param > 1) {
+            xx = x2;
+            yy = y2;
+        }
+        else {
+            xx = x1 + param * C;
+            yy = y1 + param * D;
+        }
+
+        var dx = x - xx;
+        var dy = y - yy;
+        var dst = Math.sqrt(dx * dx + dy * dy);
+        if(dst<isc.dist)
+        {
+            isc.dist = dst;
+            isc.edge = edge;
+            isc.point.x = xx;
+            isc.point.y = yy;
+        }
+    }
+
+    PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc)
+    {
+        var nrl = PolyK._P.dist(a1, c);
+        if(nrl<isc.dist)
+        {
+            var ibl = 1/PolyK._P.dist(b1, b2);
+            var nx = -(b2.y-b1.y)*ibl;
+            var ny =  (b2.x-b1.x)*ibl;
+            var ddot = 2*(dx*nx+dy*ny);
+            isc.dist = nrl;
+            isc.norm.x = nx;
+            isc.norm.y = ny;
+            isc.refl.x = -ddot*nx+dx;
+            isc.refl.y = -ddot*ny+dy;
+            isc.edge = edge;
+        }
+    }
+
+    PolyK._getPoints = function(ps, ind0, ind1)
+    {
+        var n = ps.length;
+        var nps = [];
+        if(ind1<ind0) ind1 += n;
+        for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]);
+        return nps;
+    }
+
+    PolyK._firstWithFlag = function(ps, ind)
+    {
+        var n = ps.length;
+        while(true)
+        {
+            ind = (ind+1)%n;
+            if(ps[ind].flag) return ind;
+        }
+    }
+    */
+    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;
+
+        // Check if point is in triangle
+        return (u >= 0) && (v >= 0) && (u + v < 1);
+    }
+    /*
+    PolyK._RayLineIntersection = function(a1, a2, b1, b2, c)
+    {
+        var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
+        var day = (a1.y-a2.y), dby = (b1.y-b2.y);
+
+        var Den = dax*dby - day*dbx;
+        if (Den == 0) return null;  // parallel
+
+        var A = (a1.x * a2.y - a1.y * a2.x);
+        var B = (b1.x * b2.y - b1.y * b2.x);
+
+        var I = c;
+        var iDen = 1/Den;
+        I.x = ( A*dbx - dax*B ) * iDen;
+        I.y = ( A*dby - day*B ) * iDen;
+
+        if(!PolyK._InRect(I, b1, b2)) return null;
+        if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null;
+        if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null;
+        return I;
+    }
+
+    PolyK._GetLineIntersection = function(a1, a2, b1, b2, c)
+    {
+        var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
+        var day = (a1.y-a2.y), dby = (b1.y-b2.y);
+
+        var Den = dax*dby - day*dbx;
+        if (Den == 0) return null;  // parallel
+
+        var A = (a1.x * a2.y - a1.y * a2.x);
+        var B = (b1.x * b2.y - b1.y * b2.x);
+
+        var I = c;
+        I.x = ( A*dbx - dax*B ) / Den;
+        I.y = ( A*dby - day*B ) / Den;
+
+        if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I;
+        return null;
+    }
+
+    PolyK._InRect = function(a, b, c)
+    {
+        if  (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y));
+        if  (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x));
+
+        if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x)
+        && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y))
+        return true;
+        return false;
+    }
+    */
+    PolyK._convex = function(ax, ay, bx, by, cx, cy)
+    {
+        return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0;
+    }
+    /*
+    PolyK._P = function(x,y)
+    {
+        this.x = x;
+        this.y = y;
+        this.flag = false;
+    }
+    PolyK._P.prototype.toString = function()
+    {
+        return "Point ["+this.x+", "+this.y+"]";
+    }
+    PolyK._P.dist = function(a,b)
+    {
+        var dx = b.x-a.x;
+        var dy = b.y-a.y;
+        return Math.sqrt(dx*dx + dy*dy);
+    }
+
+    PolyK._tp = [];
+    for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0));
+        */
+
+module.exports = PolyK;
+
+},{}],30:[function(_dereq_,module,exports){
+/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+  * Redistributions of source code must retain the above copyright notice, this
+    list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright notice,
+    this list of conditions and the following disclaimer in the documentation
+    and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+/**
+ * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
+ * @class vec2
+ */
+
+var vec2 = module.exports = {};
+
+var Utils = _dereq_('../utils/Utils');
+
+/**
+ * Make a cross product and only return the z component
+ * @method crossLength
+ * @static
+ * @param  {Array} a
+ * @param  {Array} b
+ * @return {Number}
+ */
+vec2.crossLength = function(a,b){
+    return a[0] * b[1] - a[1] * b[0];
+};
+
+/**
+ * Cross product between a vector and the Z component of a vector
+ * @method crossVZ
+ * @static
+ * @param  {Array} out
+ * @param  {Array} vec
+ * @param  {Number} zcomp
+ * @return {Number}
+ */
+vec2.crossVZ = function(out, vec, zcomp){
+    vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
+    vec2.scale(out,out,zcomp);      // Scale with z
+    return out;
+};
+
+/**
+ * Cross product between a vector and the Z component of a vector
+ * @method crossZV
+ * @static
+ * @param  {Array} out
+ * @param  {Number} zcomp
+ * @param  {Array} vec
+ * @return {Number}
+ */
+vec2.crossZV = function(out, zcomp, vec){
+    vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
+    vec2.scale(out,out,zcomp);      // Scale with z
+    return out;
+};
+
+/**
+ * Rotate a vector by an angle
+ * @method rotate
+ * @static
+ * @param  {Array} out
+ * @param  {Array} a
+ * @param  {Number} angle
+ */
+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];
+    }
+};
+
+/**
+ * Rotate a vector 90 degrees clockwise
+ * @method rotate90cw
+ * @static
+ * @param  {Array} out
+ * @param  {Array} a
+ * @param  {Number} angle
+ */
+vec2.rotate90cw = function(out, a) {
+    var x = a[0];
+    var y = a[1];
+    out[0] = y;
+    out[1] = -x;
+};
+
+/**
+ * Transform a point position to local frame.
+ * @method toLocalFrame
+ * @param  {Array} out
+ * @param  {Array} worldPoint
+ * @param  {Array} framePosition
+ * @param  {Number} frameAngle
+ */
+vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
+    vec2.copy(out, worldPoint);
+    vec2.sub(out, out, framePosition);
+    vec2.rotate(out, out, -frameAngle);
+};
+
+/**
+ * Transform a point position to global frame.
+ * @method toGlobalFrame
+ * @param  {Array} out
+ * @param  {Array} localPoint
+ * @param  {Array} framePosition
+ * @param  {Number} frameAngle
+ */
+vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
+    vec2.copy(out, localPoint);
+    vec2.rotate(out, out, frameAngle);
+    vec2.add(out, out, framePosition);
+};
+
+/**
+ * Transform a vector to local frame.
+ * @method vectorToLocalFrame
+ * @param  {Array} out
+ * @param  {Array} worldVector
+ * @param  {Number} frameAngle
+ */
+vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
+    vec2.rotate(out, worldVector, -frameAngle);
+};
+
+/**
+ * Transform a point position to global frame.
+ * @method toGlobalFrame
+ * @param  {Array} out
+ * @param  {Array} localVector
+ * @param  {Number} frameAngle
+ */
+vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){
+    vec2.rotate(out, localVector, frameAngle);
+};
+
+/**
+ * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
+ * @method centroid
+ * @static
+ * @param  {Array} out
+ * @param  {Array} a
+ * @param  {Array} b
+ * @param  {Array} c
+ * @return  {Array} The out object
+ */
+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;
+};
+
+/**
+ * Creates a new, empty vec2
+ * @static
+ * @method create
+ * @return {Array} a new 2D vector
+ */
+vec2.create = function() {
+    var out = new Utils.ARRAY_TYPE(2);
+    out[0] = 0;
+    out[1] = 0;
+    return out;
+};
+
+/**
+ * Creates a new vec2 initialized with values from an existing vector
+ * @static
+ * @method clone
+ * @param {Array} a vector to clone
+ * @return {Array} a new 2D vector
+ */
+vec2.clone = function(a) {
+    var out = new Utils.ARRAY_TYPE(2);
+    out[0] = a[0];
+    out[1] = a[1];
+    return out;
+};
+
+/**
+ * Creates a new vec2 initialized with the given values
+ * @static
+ * @method fromValues
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @return {Array} a new 2D vector
+ */
+vec2.fromValues = function(x, y) {
+    var out = new Utils.ARRAY_TYPE(2);
+    out[0] = x;
+    out[1] = y;
+    return out;
+};
+
+/**
+ * Copy the values from one vec2 to another
+ * @static
+ * @method copy
+ * @param {Array} out the receiving vector
+ * @param {Array} a the source vector
+ * @return {Array} out
+ */
+vec2.copy = function(out, a) {
+    out[0] = a[0];
+    out[1] = a[1];
+    return out;
+};
+
+/**
+ * Set the components of a vec2 to the given values
+ * @static
+ * @method set
+ * @param {Array} out the receiving vector
+ * @param {Number} x X component
+ * @param {Number} y Y component
+ * @return {Array} out
+ */
+vec2.set = function(out, x, y) {
+    out[0] = x;
+    out[1] = y;
+    return out;
+};
+
+/**
+ * Adds two vec2's
+ * @static
+ * @method add
+ * @param {Array} out the receiving vector
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Array} out
+ */
+vec2.add = function(out, a, b) {
+    out[0] = a[0] + b[0];
+    out[1] = a[1] + b[1];
+    return out;
+};
+
+/**
+ * Subtracts two vec2's
+ * @static
+ * @method subtract
+ * @param {Array} out the receiving vector
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Array} out
+ */
+vec2.subtract = function(out, a, b) {
+    out[0] = a[0] - b[0];
+    out[1] = a[1] - b[1];
+    return out;
+};
+
+/**
+ * Alias for vec2.subtract
+ * @static
+ * @method sub
+ */
+vec2.sub = vec2.subtract;
+
+/**
+ * Multiplies two vec2's
+ * @static
+ * @method multiply
+ * @param {Array} out the receiving vector
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Array} out
+ */
+vec2.multiply = function(out, a, b) {
+    out[0] = a[0] * b[0];
+    out[1] = a[1] * b[1];
+    return out;
+};
+
+/**
+ * Alias for vec2.multiply
+ * @static
+ * @method mul
+ */
+vec2.mul = vec2.multiply;
+
+/**
+ * Divides two vec2's
+ * @static
+ * @method divide
+ * @param {Array} out the receiving vector
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Array} out
+ */
+vec2.divide = function(out, a, b) {
+    out[0] = a[0] / b[0];
+    out[1] = a[1] / b[1];
+    return out;
+};
+
+/**
+ * Alias for vec2.divide
+ * @static
+ * @method div
+ */
+vec2.div = vec2.divide;
+
+/**
+ * Scales a vec2 by a scalar number
+ * @static
+ * @method scale
+ * @param {Array} out the receiving vector
+ * @param {Array} a the vector to scale
+ * @param {Number} b amount to scale the vector by
+ * @return {Array} out
+ */
+vec2.scale = function(out, a, b) {
+    out[0] = a[0] * b;
+    out[1] = a[1] * b;
+    return out;
+};
+
+/**
+ * Calculates the euclidian distance between two vec2's
+ * @static
+ * @method distance
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Number} distance between a and b
+ */
+vec2.distance = function(a, b) {
+    var x = b[0] - a[0],
+        y = b[1] - a[1];
+    return Math.sqrt(x*x + y*y);
+};
+
+/**
+ * Alias for vec2.distance
+ * @static
+ * @method dist
+ */
+vec2.dist = vec2.distance;
+
+/**
+ * Calculates the squared euclidian distance between two vec2's
+ * @static
+ * @method squaredDistance
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Number} squared distance between a and b
+ */
+vec2.squaredDistance = function(a, b) {
+    var x = b[0] - a[0],
+        y = b[1] - a[1];
+    return x*x + y*y;
+};
+
+/**
+ * Alias for vec2.squaredDistance
+ * @static
+ * @method sqrDist
+ */
+vec2.sqrDist = vec2.squaredDistance;
+
+/**
+ * Calculates the length of a vec2
+ * @static
+ * @method length
+ * @param {Array} a vector to calculate length of
+ * @return {Number} length of a
+ */
+vec2.length = function (a) {
+    var x = a[0],
+        y = a[1];
+    return Math.sqrt(x*x + y*y);
+};
+
+/**
+ * Alias for vec2.length
+ * @method len
+ * @static
+ */
+vec2.len = vec2.length;
+
+/**
+ * Calculates the squared length of a vec2
+ * @static
+ * @method squaredLength
+ * @param {Array} a vector to calculate squared length of
+ * @return {Number} squared length of a
+ */
+vec2.squaredLength = function (a) {
+    var x = a[0],
+        y = a[1];
+    return x*x + y*y;
+};
+
+/**
+ * Alias for vec2.squaredLength
+ * @static
+ * @method sqrLen
+ */
+vec2.sqrLen = vec2.squaredLength;
+
+/**
+ * Negates the components of a vec2
+ * @static
+ * @method negate
+ * @param {Array} out the receiving vector
+ * @param {Array} a vector to negate
+ * @return {Array} out
+ */
+vec2.negate = function(out, a) {
+    out[0] = -a[0];
+    out[1] = -a[1];
+    return out;
+};
+
+/**
+ * Normalize a vec2
+ * @static
+ * @method normalize
+ * @param {Array} out the receiving vector
+ * @param {Array} a vector to normalize
+ * @return {Array} out
+ */
+vec2.normalize = function(out, a) {
+    var x = a[0],
+        y = a[1];
+    var len = x*x + y*y;
+    if (len > 0) {
+        //TODO: evaluate use of glm_invsqrt here?
+        len = 1 / Math.sqrt(len);
+        out[0] = a[0] * len;
+        out[1] = a[1] * len;
+    }
+    return out;
+};
+
+/**
+ * Calculates the dot product of two vec2's
+ * @static
+ * @method dot
+ * @param {Array} a the first operand
+ * @param {Array} b the second operand
+ * @return {Number} dot product of a and b
+ */
+vec2.dot = function (a, b) {
+    return a[0] * b[0] + a[1] * b[1];
+};
+
+/**
+ * Returns a string representation of a vector
+ * @static
+ * @method str
+ * @param {Array} vec vector to represent as a string
+ * @return {String} string representation of the vector
+ */
+vec2.str = function (a) {
+    return 'vec2(' + a[0] + ', ' + a[1] + ')';
+};
+
+/**
+ * Linearly interpolate/mix two vectors.
+ * @static
+ * @method lerp
+ * @param {Array} out
+ * @param {Array} a First vector
+ * @param {Array} b Second vector
+ * @param {number} t Lerp factor
+ */
+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;
+};
+
+/**
+ * Reflect a vector along a normal.
+ * @static
+ * @method reflect
+ * @param {Array} out
+ * @param {Array} vector
+ * @param {Array} normal
+ */
+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;
+};
+
+/**
+ * Get the intersection point between two line segments.
+ * @static
+ * @method getLineSegmentsIntersection
+ * @param  {Array} out
+ * @param  {Array} p0
+ * @param  {Array} p1
+ * @param  {Array} p2
+ * @param  {Array} p3
+ * @return {boolean} True if there was an intersection, otherwise false.
+ */
+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;
+    }
+};
+
+/**
+ * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
+ * @static
+ * @method getLineSegmentsIntersectionFraction
+ * @param  {Array} p0
+ * @param  {Array} p1
+ * @param  {Array} p2
+ * @param  {Array} p3
+ * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
+ */
+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) { // Collision detected
+        return t;
+    }
+    return -1; // No collision
+};
+
+},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   decomp = _dereq_('poly-decomp')
+,   Convex = _dereq_('../shapes/Convex')
+,   RaycastResult = _dereq_('../collision/RaycastResult')
+,   Ray = _dereq_('../collision/Ray')
+,   AABB = _dereq_('../collision/AABB')
+,   EventEmitter = _dereq_('../events/EventEmitter');
+
+module.exports = Body;
+
+/**
+ * A rigid body. Has got a center of mass, position, velocity and a number of
+ * shapes that are used for collisions.
+ *
+ * @class Body
+ * @constructor
+ * @extends EventEmitter
+ * @param {Array} [options.force]
+ * @param {Array} [options.position]
+ * @param {Array} [options.velocity]
+ * @param {Boolean} [options.allowSleep]
+ * @param {Boolean} [options.collisionResponse]
+ * @param {Number} [options.angle=0]
+ * @param {Number} [options.angularForce=0]
+ * @param {Number} [options.angularVelocity=0]
+ * @param {Number} [options.ccdIterations=10]
+ * @param {Number} [options.ccdSpeedThreshold=-1]
+ * @param {Number} [options.fixedRotation=false]
+ * @param {Number} [options.gravityScale]
+ * @param {Number} [options.id]
+ * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC.
+ * @param {Number} [options.sleepSpeedLimit]
+ * @param {Number} [options.sleepTimeLimit]
+ * @param {Object} [options]
+ *
+ * @example
+ *
+ *     // Create a typical dynamic body
+ *     var body = new Body({
+ *         mass: 1,
+ *         position: [0, 0],
+ *         angle: 0,
+ *         velocity: [0, 0],
+ *         angularVelocity: 0
+ *     });
+ *
+ *     // Add a circular shape to the body
+ *     body.addShape(new Circle({ radius: 1 }));
+ *
+ *     // Add the body to the world
+ *     world.addBody(body);
+ */
+function Body(options){
+    options = options || {};
+
+    EventEmitter.call(this);
+
+    /**
+     * The body identifyer
+     * @property id
+     * @type {Number}
+     */
+    this.id = options.id || ++Body._idCounter;
+
+    /**
+     * The world that this body is added to. This property is set to NULL if the body is not added to any world.
+     * @property world
+     * @type {World}
+     */
+    this.world = null;
+
+    /**
+     * The shapes of the body.
+     *
+     * @property shapes
+     * @type {Array}
+     */
+    this.shapes = [];
+
+    /**
+     * The mass of the body.
+     * @property mass
+     * @type {number}
+     */
+    this.mass = options.mass || 0;
+
+    /**
+     * The inverse mass of the body.
+     * @property invMass
+     * @type {number}
+     */
+    this.invMass = 0;
+
+    /**
+     * The inertia of the body around the Z axis.
+     * @property inertia
+     * @type {number}
+     */
+    this.inertia = 0;
+
+    /**
+     * The inverse inertia of the body.
+     * @property invInertia
+     * @type {number}
+     */
+    this.invInertia = 0;
+
+    this.invMassSolve = 0;
+    this.invInertiaSolve = 0;
+
+    /**
+     * Set to true if you want to fix the rotation of the body.
+     * @property fixedRotation
+     * @type {Boolean}
+     */
+    this.fixedRotation = !!options.fixedRotation;
+
+    /**
+     * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y.
+     * @property {Boolean} fixedX
+     */
+    this.fixedX = !!options.fixedX;
+
+    /**
+     * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X.
+     * @property {Boolean} fixedY
+     */
+    this.fixedY = !!options.fixedY;
+
+    /**
+     * @private
+     * @property {array} massMultiplier
+     */
+    this.massMultiplier = vec2.create();
+
+    /**
+     * The position of the body
+     * @property position
+     * @type {Array}
+     */
+    this.position = vec2.fromValues(0,0);
+    if(options.position){
+        vec2.copy(this.position, options.position);
+    }
+
+    /**
+     * The interpolated position of the body. Use this for rendering.
+     * @property interpolatedPosition
+     * @type {Array}
+     */
+    this.interpolatedPosition = vec2.fromValues(0,0);
+
+    /**
+     * The interpolated angle of the body. Use this for rendering.
+     * @property interpolatedAngle
+     * @type {Number}
+     */
+    this.interpolatedAngle = 0;
+
+    /**
+     * The previous position of the body.
+     * @property previousPosition
+     * @type {Array}
+     */
+    this.previousPosition = vec2.fromValues(0,0);
+
+    /**
+     * The previous angle of the body.
+     * @property previousAngle
+     * @type {Number}
+     */
+    this.previousAngle = 0;
+
+    /**
+     * The current velocity of the body.
+     * @property velocity
+     * @type {Array}
+     */
+    this.velocity = vec2.fromValues(0,0);
+    if(options.velocity){
+        vec2.copy(this.velocity, options.velocity);
+    }
+
+    /**
+     * Constraint velocity that was added to the body during the last step.
+     * @property vlambda
+     * @type {Array}
+     */
+    this.vlambda = vec2.fromValues(0,0);
+
+    /**
+     * Angular constraint velocity that was added to the body during last step.
+     * @property wlambda
+     * @type {Array}
+     */
+    this.wlambda = 0;
+
+    /**
+     * The angle of the body, in radians.
+     * @property angle
+     * @type {number}
+     * @example
+     *     // The angle property is not normalized to the interval 0 to 2*pi, it can be any value.
+     *     // If you need a value between 0 and 2*pi, use the following function to normalize it.
+     *     function normalizeAngle(angle){
+     *         angle = angle % (2*Math.PI);
+     *         if(angle < 0){
+     *             angle += (2*Math.PI);
+     *         }
+     *         return angle;
+     *     }
+     */
+    this.angle = options.angle || 0;
+
+    /**
+     * The angular velocity of the body, in radians per second.
+     * @property angularVelocity
+     * @type {number}
+     */
+    this.angularVelocity = options.angularVelocity || 0;
+
+    /**
+     * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step.
+     * @property force
+     * @type {Array}
+     *
+     * @example
+     *     // This produces a forcefield of 1 Newton in the positive x direction.
+     *     for(var i=0; i<numSteps; i++){
+     *         body.force[0] = 1;
+     *         world.step(1/60);
+     *     }
+     *
+     * @example
+     *     // This will apply a rotational force on the body
+     *     for(var i=0; i<numSteps; i++){
+     *         body.angularForce = -3;
+     *         world.step(1/60);
+     *     }
+     */
+    this.force = vec2.create();
+    if(options.force){
+        vec2.copy(this.force, options.force);
+    }
+
+    /**
+     * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}.
+     * @property angularForce
+     * @type {number}
+     */
+    this.angularForce = options.angularForce || 0;
+
+    /**
+     * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1.
+     * @property damping
+     * @type {Number}
+     * @default 0.1
+     */
+    this.damping = typeof(options.damping) === "number" ? options.damping : 0.1;
+
+    /**
+     * The angular force acting on the body. Should be a value between 0 and 1.
+     * @property angularDamping
+     * @type {Number}
+     * @default 0.1
+     */
+    this.angularDamping = typeof(options.angularDamping) === "number" ? options.angularDamping : 0.1;
+
+    /**
+     * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}.
+     *
+     * * Static bodies do not move, and they do not respond to forces or collision.
+     * * Dynamic bodies body can move and respond to collisions and forces.
+     * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.
+     *
+     * @property type
+     * @type {number}
+     *
+     * @example
+     *     // Bodies are static by default. Static bodies will never move.
+     *     var body = new Body();
+     *     console.log(body.type == Body.STATIC); // true
+     *
+     * @example
+     *     // By setting the mass of a body to a nonzero number, the body
+     *     // will become dynamic and will move and interact with other bodies.
+     *     var dynamicBody = new Body({
+     *         mass : 1
+     *     });
+     *     console.log(dynamicBody.type == Body.DYNAMIC); // true
+     *
+     * @example
+     *     // Kinematic bodies will only move if you change their velocity.
+     *     var kinematicBody = new Body({
+     *         type: Body.KINEMATIC // Type can be set via the options object.
+     *     });
+     */
+    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;
+    }
+
+    /**
+     * Bounding circle radius.
+     * @property boundingRadius
+     * @type {Number}
+     */
+    this.boundingRadius = 0;
+
+    /**
+     * Bounding box of this body.
+     * @property aabb
+     * @type {AABB}
+     */
+    this.aabb = new AABB();
+
+    /**
+     * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}.
+     * @property aabbNeedsUpdate
+     * @type {Boolean}
+     * @see updateAABB
+     *
+     * @example
+     *     // Force update the AABB
+     *     body.aabbNeedsUpdate = true;
+     *     body.updateAABB();
+     *     console.log(body.aabbNeedsUpdate); // false
+     */
+    this.aabbNeedsUpdate = true;
+
+    /**
+     * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen.
+     * @property allowSleep
+     * @type {Boolean}
+     * @default true
+     */
+    this.allowSleep = options.allowSleep !== undefined ? options.allowSleep : true;
+
+    this.wantsToSleep = false;
+
+    /**
+     * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}.
+     *
+     * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY).
+     *
+     * @property sleepState
+     * @type {Number}
+     * @default Body.AWAKE
+     */
+    this.sleepState = Body.AWAKE;
+
+    /**
+     * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
+     * @property sleepSpeedLimit
+     * @type {Number}
+     * @default 0.2
+     */
+    this.sleepSpeedLimit = options.sleepSpeedLimit !== undefined ? options.sleepSpeedLimit : 0.2;
+
+    /**
+     * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
+     * @property sleepTimeLimit
+     * @type {Number}
+     * @default 1
+     */
+    this.sleepTimeLimit = options.sleepTimeLimit !== undefined ? options.sleepTimeLimit : 1;
+
+    /**
+     * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1.
+     * @property {Number} gravityScale
+     * @default 1
+     */
+    this.gravityScale = options.gravityScale !== undefined ? options.gravityScale : 1;
+
+    /**
+     * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc.
+     * @property {Boolean} collisionResponse
+     */
+    this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
+
+    /**
+     * How long the body has been sleeping.
+     * @property {Number} idleTime
+     */
+    this.idleTime = 0;
+
+    /**
+     * The last time when the body went to SLEEPY state.
+     * @property {Number} timeLastSleepy
+     * @private
+     */
+    this.timeLastSleepy = 0;
+
+    /**
+     * If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body.
+     * @property {number} ccdSpeedThreshold
+     * @default -1
+     */
+    this.ccdSpeedThreshold = options.ccdSpeedThreshold !== undefined ? options.ccdSpeedThreshold : -1;
+
+    /**
+     * The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance.
+     * @property {number} ccdIterations
+     * @default 10
+     */
+    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;
+
+/**
+ * @private
+ * @method updateSolveMassProperties
+ */
+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;
+    }
+};
+
+/**
+ * Set the total density of the body
+ * @method setDensity
+ * @param {number} density
+ */
+Body.prototype.setDensity = function(density) {
+    var totalArea = this.getArea();
+    this.mass = totalArea * density;
+    this.updateMassProperties();
+};
+
+/**
+ * Get the total area of all shapes in the body
+ * @method getArea
+ * @return {Number}
+ */
+Body.prototype.getArea = function() {
+    var totalArea = 0;
+    for(var i=0; i<this.shapes.length; i++){
+        totalArea += this.shapes[i].area;
+    }
+    return totalArea;
+};
+
+/**
+ * Get the AABB from the body. The AABB is updated if necessary.
+ * @method getAABB
+ * @return {AABB} The AABB instance (this.aabb)
+ */
+Body.prototype.getAABB = function(){
+    if(this.aabbNeedsUpdate){
+        this.updateAABB();
+    }
+    return this.aabb;
+};
+
+var shapeAABB = new AABB(),
+    tmp = vec2.create();
+
+/**
+ * Updates the AABB of the Body, and set .aabbNeedsUpdate = false.
+ * @method updateAABB
+ */
+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;
+
+        // Get shape world offset
+        vec2.rotate(offset, shape.position, bodyAngle);
+        vec2.add(offset, offset, this.position);
+
+        // Get shape AABB
+        shape.computeAABB(shapeAABB, offset, angle);
+
+        if(i===0){
+            this.aabb.copy(shapeAABB);
+        } else {
+            this.aabb.extend(shapeAABB);
+        }
+    }
+
+    this.aabbNeedsUpdate = false;
+};
+
+/**
+ * Update the bounding radius of the body (this.boundingRadius). Should be done if any of the shape dimensions or positions are changed.
+ * @method updateBoundingRadius
+ */
+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;
+};
+
+/**
+ * Add a shape to the body. You can pass a local transform when adding a shape,
+ * so that the shape gets an offset and angle relative to the body center of mass.
+ * Will automatically update the mass properties and bounding radius.
+ *
+ * @method addShape
+ * @param  {Shape}              shape
+ * @param  {Array} [offset] Local body offset of the shape.
+ * @param  {Number}             [angle]  Local body angle.
+ *
+ * @example
+ *     var body = new Body(),
+ *         shape = new Circle({ radius: 1 });
+ *
+ *     // Add the shape to the body, positioned in the center
+ *     body.addShape(shape);
+ *
+ *     // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis.
+ *     body.addShape(shape,[1,0]);
+ *
+ *     // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW.
+ *     body.addShape(shape,[0,1],Math.PI/2);
+ */
+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;
+
+    // Copy the offset vector
+    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;
+};
+
+/**
+ * Remove a shape
+ * @method removeShape
+ * @param  {Shape} shape
+ * @return {Boolean} True if the shape was found and removed, else false.
+ */
+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;
+    }
+};
+
+/**
+ * Updates .inertia, .invMass, .invInertia for this Body. Should be called when
+ * changing the structure or mass of the Body.
+ *
+ * @method updateMassProperties
+ *
+ * @example
+ *     body.mass += 1;
+ *     body.updateMassProperties();
+ */
+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;
+        }
+
+        // Inverse mass properties are easy
+        this.invMass = 1 / this.mass;
+
+        vec2.set(
+            this.massMultiplier,
+            this.fixedX ? 0 : 1,
+            this.fixedY ? 0 : 1
+        );
+    }
+};
+
+var Body_applyForce_r = vec2.create();
+
+/**
+ * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero.
+ * @method applyForce
+ * @param {Array} force The force to add.
+ * @param {Array} [relativePoint] A world point to apply the force on.
+ */
+Body.prototype.applyForce = function(force, relativePoint){
+
+    // Add linear force
+    vec2.add(this.force, this.force, force);
+
+    if(relativePoint){
+
+        // Compute produced rotational force
+        var rotForce = vec2.crossLength(relativePoint,force);
+
+        // Add rotational force
+        this.angularForce += rotForce;
+    }
+};
+
+/**
+ * Apply force to a body-local point.
+ * @method applyForceLocal
+ * @param  {Array} localForce The force vector to add, oriented in local body space.
+ * @param  {Array} localPoint A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
+ */
+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);
+};
+
+/**
+ * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
+ * @method applyImpulse
+ * @param  {Array} impulse The impulse vector to add, oriented in world space.
+ * @param  {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
+ */
+var Body_applyImpulse_velo = vec2.create();
+Body.prototype.applyImpulse = function(impulseVector, relativePoint){
+    if(this.type !== Body.DYNAMIC){
+        return;
+    }
+
+    // Compute produced central impulse velocity
+    var velo = Body_applyImpulse_velo;
+    vec2.scale(velo, impulseVector, this.invMass);
+    vec2.multiply(velo, this.massMultiplier, velo);
+
+    // Add linear impulse
+    vec2.add(this.velocity, velo, this.velocity);
+
+    if(relativePoint){
+        // Compute produced rotational impulse velocity
+        var rotVelo = vec2.crossLength(relativePoint, impulseVector);
+        rotVelo *= this.invInertia;
+
+        // Add rotational Impulse
+        this.angularVelocity += rotVelo;
+    }
+};
+
+/**
+ * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
+ * @method applyImpulseLocal
+ * @param  {Array} impulse The impulse vector to add, oriented in world space.
+ * @param  {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
+ */
+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);
+};
+
+/**
+ * Transform a world point to local body frame.
+ * @method toLocalFrame
+ * @param  {Array} out          The vector to store the result in
+ * @param  {Array} worldPoint   The input world point
+ */
+Body.prototype.toLocalFrame = function(out, worldPoint){
+    vec2.toLocalFrame(out, worldPoint, this.position, this.angle);
+};
+
+/**
+ * Transform a local point to world frame.
+ * @method toWorldFrame
+ * @param  {Array} out          The vector to store the result in
+ * @param  {Array} localPoint   The input local point
+ */
+Body.prototype.toWorldFrame = function(out, localPoint){
+    vec2.toGlobalFrame(out, localPoint, this.position, this.angle);
+};
+
+/**
+ * Transform a world point to local body frame.
+ * @method vectorToLocalFrame
+ * @param  {Array} out          The vector to store the result in
+ * @param  {Array} worldVector  The input world vector
+ */
+Body.prototype.vectorToLocalFrame = function(out, worldVector){
+    vec2.vectorToLocalFrame(out, worldVector, this.angle);
+};
+
+/**
+ * Transform a local point to world frame.
+ * @method vectorToWorldFrame
+ * @param  {Array} out          The vector to store the result in
+ * @param  {Array} localVector  The input local vector
+ */
+Body.prototype.vectorToWorldFrame = function(out, localVector){
+    vec2.vectorToGlobalFrame(out, localVector, this.angle);
+};
+
+/**
+ * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.
+ * @method fromPolygon
+ * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes.
+ * @param {Object} [options]
+ * @param {Boolean} [options.optimalDecomp=false]   Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
+ * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself.
+ * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
+ * @return {Boolean} True on success, else false.
+ */
+Body.prototype.fromPolygon = function(path,options){
+    options = options || {};
+
+    // Remove all shapes
+    for(var i=this.shapes.length; i>=0; --i){
+        this.removeShape(this.shapes[i]);
+    }
+
+    var p = new decomp.Polygon();
+    p.vertices = path;
+
+    // Make it counter-clockwise
+    p.makeCCW();
+
+    if(typeof(options.removeCollinearPoints) === "number"){
+        p.removeCollinearPoints(options.removeCollinearPoints);
+    }
+
+    // Check if any line segment intersects the path itself
+    if(typeof(options.skipSimpleCheck) === "undefined"){
+        if(!p.isSimple()){
+            return false;
+        }
+    }
+
+    // Save this path for later
+    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;
+    }
+
+    // Slow or fast decomp?
+    var convexes;
+    if(options.optimalDecomp){
+        convexes = p.decomp();
+    } else {
+        convexes = p.quickDecomp();
+    }
+
+    var cm = vec2.create();
+
+    // Add convexes
+    for(var i=0; i!==convexes.length; i++){
+        // Create convex
+        var c = new Convex({ vertices: convexes[i].vertices });
+
+        // Move all vertices so its center of mass is in the local center of the convex
+        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();
+
+        // Add the shape
+        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);
+
+/**
+ * Moves the shape offsets so their center of mass becomes the body center of mass.
+ * @method adjustCenterOfMass
+ */
+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);
+
+    // Now move all shapes
+    for(var i=0; i!==this.shapes.length; i++){
+        var s = this.shapes[i];
+        vec2.sub(s.position, s.position, cm);
+    }
+
+    // Move the body position too
+    vec2.add(this.position,this.position,cm);
+
+    // And concave path
+    for(var i=0; this.concavePath && i<this.concavePath.length; i++){
+        vec2.sub(this.concavePath[i], this.concavePath[i], cm);
+    }
+
+    this.updateMassProperties();
+    this.updateBoundingRadius();
+};
+
+/**
+ * Sets the force on the body to zero.
+ * @method setZeroForce
+ */
+Body.prototype.setZeroForce = function(){
+    vec2.set(this.force,0.0,0.0);
+    this.angularForce = 0.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;
+};
+
+/**
+ * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details.
+ * @method applyDamping
+ * @param  {number} dt Current time step
+ */
+Body.prototype.applyDamping = function(dt){
+    if(this.type === Body.DYNAMIC){ // Only for dynamic bodies
+        var v = this.velocity;
+        vec2.scale(v, v, Math.pow(1.0 - this.damping,dt));
+        this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt);
+    }
+};
+
+/**
+ * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions.
+ * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before.
+ * @method wakeUp
+ */
+Body.prototype.wakeUp = function(){
+    var s = this.sleepState;
+    this.sleepState = Body.AWAKE;
+    this.idleTime = 0;
+    if(s !== Body.AWAKE){
+        this.emit(Body.wakeUpEvent);
+    }
+};
+
+/**
+ * Force body sleep
+ * @method sleep
+ */
+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);
+};
+
+/**
+ * Called every timestep to update internal sleep timer and change sleep state if needed.
+ * @method sleepTick
+ * @param {number} time The world time in seconds
+ * @param {boolean} dontSleep
+ * @param {number} dt
+ */
+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);
+
+    // Add to idle time
+    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;
+        }
+    }
+};
+
+/**
+ * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken.
+ * @method overlaps
+ * @param  {Body} body
+ * @return {boolean}
+ */
+Body.prototype.overlaps = function(body){
+    return this.world.overlapKeeper.bodiesAreOverlapping(this, body);
+};
+
+var integrate_fhMinv = vec2.create();
+var integrate_velodt = vec2.create();
+
+/**
+ * Move the body forward in time given its current velocity.
+ * @method integrate
+ * @param  {Number} dt
+ */
+Body.prototype.integrate = function(dt){
+    var minv = this.invMass,
+        f = this.force,
+        pos = this.position,
+        velo = this.velocity;
+
+    // Save old position
+    vec2.copy(this.previousPosition, this.position);
+    this.previousAngle = this.angle;
+
+    // Velocity update
+    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);
+
+    // CCD
+    if(!this.integrateToTimeOfImpact(dt)){
+
+        // Regular position update
+        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);
+
+    // Got a start and end point. Approximate time of impact using binary search
+    var iter = 0;
+    var tmin = 0;
+    var tmid = 0;
+    var tmax = timeOfImpact;
+    while (tmax >= tmin && iter < this.ccdIterations) {
+        iter++;
+
+        // calculate the midpoint
+        tmid = (tmax - tmin) / 2;
+
+        // Move the body to that point
+        vec2.scale(integrate_velodt, startToEnd, timeOfImpact);
+        vec2.add(this.position, rememberPosition, integrate_velodt);
+        this.angle = rememberAngle + startToEndAngle * timeOfImpact;
+        this.updateAABB();
+
+        // check overlap
+        var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit);
+
+        if (overlaps) {
+            // change min to search upper interval
+            tmin = tmid;
+        } else {
+            // change max to search lower interval
+            tmax = tmid;
+        }
+    }
+
+    timeOfImpact = tmid;
+
+    vec2.copy(this.position, rememberPosition);
+    this.angle = rememberAngle;
+
+    // move to TOI
+    vec2.scale(integrate_velodt, startToEnd, timeOfImpact);
+    vec2.add(this.position, this.position, integrate_velodt);
+    if(!this.fixedRotation){
+        this.angle += startToEndAngle * timeOfImpact;
+    }
+
+    return true;
+};
+
+/**
+ * Get velocity of a point in the body.
+ * @method getVelocityAtPoint
+ * @param  {Array} result A vector to store the result in
+ * @param  {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from
+ * @return {Array} The result vector
+ */
+Body.prototype.getVelocityAtPoint = function(result, relativePoint){
+    vec2.crossVZ(result, relativePoint, this.angularVelocity);
+    vec2.subtract(result, this.velocity, result);
+    return result;
+};
+
+/**
+ * @event sleepy
+ */
+Body.sleepyEvent = {
+    type: "sleepy"
+};
+
+/**
+ * @event sleep
+ */
+Body.sleepEvent = {
+    type: "sleep"
+};
+
+/**
+ * @event wakeup
+ */
+Body.wakeUpEvent = {
+    type: "wakeup"
+};
+
+/**
+ * Dynamic body.
+ * @property DYNAMIC
+ * @type {Number}
+ * @static
+ */
+Body.DYNAMIC = 1;
+
+/**
+ * Static body.
+ * @property STATIC
+ * @type {Number}
+ * @static
+ */
+Body.STATIC = 2;
+
+/**
+ * Kinematic body.
+ * @property KINEMATIC
+ * @type {Number}
+ * @static
+ */
+Body.KINEMATIC = 4;
+
+/**
+ * @property AWAKE
+ * @type {Number}
+ * @static
+ */
+Body.AWAKE = 0;
+
+/**
+ * @property SLEEPY
+ * @type {Number}
+ * @static
+ */
+Body.SLEEPY = 1;
+
+/**
+ * @property SLEEPING
+ * @type {Number}
+ * @static
+ */
+Body.SLEEPING = 2;
+
+
+},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2');
+var Spring = _dereq_('./Spring');
+var Utils = _dereq_('../utils/Utils');
+
+module.exports = LinearSpring;
+
+/**
+ * A spring, connecting two bodies.
+ *
+ * The Spring explicitly adds force and angularForce to the bodies.
+ *
+ * @class LinearSpring
+ * @extends Spring
+ * @constructor
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Object} [options]
+ * @param {number} [options.restLength]   A number > 0. Default is the current distance between the world anchor points.
+ * @param {number} [options.stiffness=100]  Spring constant (see Hookes Law). A number >= 0.
+ * @param {number} [options.damping=1]      A number >= 0. Default: 1
+ * @param {Array}  [options.worldAnchorA]   Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given.
+ * @param {Array}  [options.worldAnchorB]
+ * @param {Array}  [options.localAnchorA]   Where to hook the spring to body A, in local body coordinates. Defaults to the body center.
+ * @param {Array}  [options.localAnchorB]
+ */
+function LinearSpring(bodyA,bodyB,options){
+    options = options || {};
+
+    Spring.call(this, bodyA, bodyB, options);
+
+    /**
+     * Anchor for bodyA in local bodyA coordinates.
+     * @property localAnchorA
+     * @type {Array}
+     */
+    this.localAnchorA = vec2.fromValues(0,0);
+
+    /**
+     * Anchor for bodyB in local bodyB coordinates.
+     * @property localAnchorB
+     * @type {Array}
+     */
+    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);
+
+    /**
+     * Rest length of the spring.
+     * @property restLength
+     * @type {number}
+     */
+    this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance;
+}
+LinearSpring.prototype = new Spring();
+LinearSpring.prototype.constructor = LinearSpring;
+
+/**
+ * Set the anchor point on body A, using world coordinates.
+ * @method setWorldAnchorA
+ * @param {Array} worldAnchorA
+ */
+LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){
+    this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA);
+};
+
+/**
+ * Set the anchor point on body B, using world coordinates.
+ * @method setWorldAnchorB
+ * @param {Array} worldAnchorB
+ */
+LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){
+    this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB);
+};
+
+/**
+ * Get the anchor point on body A, in world coordinates.
+ * @method getWorldAnchorA
+ * @param {Array} result The vector to store the result in.
+ */
+LinearSpring.prototype.getWorldAnchorA = function(result){
+    this.bodyA.toWorldFrame(result, this.localAnchorA);
+};
+
+/**
+ * Get the anchor point on body B, in world coordinates.
+ * @method getWorldAnchorB
+ * @param {Array} result The vector to store the result in.
+ */
+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();
+
+/**
+ * Apply the spring force to the connected bodies.
+ * @method applyForce
+ */
+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;
+
+    // Get world anchors
+    this.getWorldAnchorA(worldAnchorA);
+    this.getWorldAnchorB(worldAnchorB);
+
+    // Get offset points
+    vec2.sub(ri, worldAnchorA, bodyA.position);
+    vec2.sub(rj, worldAnchorB, bodyB.position);
+
+    // Compute distance vector between world anchor points
+    vec2.sub(r, worldAnchorB, worldAnchorA);
+    var rlen = vec2.len(r);
+    vec2.normalize(r_unit,r);
+
+    //console.log(rlen)
+    //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB))
+
+    // Compute relative velocity of the anchor points, u
+    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);
+
+    // F = - k * ( x - L ) - D * ( u )
+    vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit));
+
+    // Add forces to bodies
+    vec2.sub( bodyA.force, bodyA.force, f);
+    vec2.add( bodyB.force, bodyB.force, f);
+
+    // Angular force
+    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":57,"./Spring":34}],33:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2');
+var Spring = _dereq_('./Spring');
+
+module.exports = RotationalSpring;
+
+/**
+ * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies.
+ *
+ * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap.
+ *
+ * @class RotationalSpring
+ * @extends Spring
+ * @constructor
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Object} [options]
+ * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
+ * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
+ * @param {number} [options.damping=1] A number >= 0.
+ */
+function RotationalSpring(bodyA, bodyB, options){
+    options = options || {};
+
+    Spring.call(this, bodyA, bodyB, options);
+
+    /**
+     * Rest angle of the spring.
+     * @property restAngle
+     * @type {number}
+     */
+    this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle;
+}
+RotationalSpring.prototype = new Spring();
+RotationalSpring.prototype.constructor = RotationalSpring;
+
+/**
+ * Apply the spring force to the connected bodies.
+ * @method applyForce
+ */
+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(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2');
+var Utils = _dereq_('../utils/Utils');
+
+module.exports = Spring;
+
+/**
+ * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver.
+ *
+ * @class Spring
+ * @constructor
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ * @param {Object} [options]
+ * @param {number} [options.stiffness=100]  Spring constant (see Hookes Law). A number >= 0.
+ * @param {number} [options.damping=1]      A number >= 0. Default: 1
+ * @param {Array}  [options.localAnchorA]   Where to hook the spring to body A, in local body coordinates. Defaults to the body center.
+ * @param {Array}  [options.localAnchorB]
+ * @param {Array}  [options.worldAnchorA]   Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given.
+ * @param {Array}  [options.worldAnchorB]
+ */
+function Spring(bodyA, bodyB, options){
+    options = Utils.defaults(options,{
+        stiffness: 100,
+        damping: 1,
+    });
+
+    /**
+     * Stiffness of the spring.
+     * @property stiffness
+     * @type {number}
+     */
+    this.stiffness = options.stiffness;
+
+    /**
+     * Damping of the spring.
+     * @property damping
+     * @type {number}
+     */
+    this.damping = options.damping;
+
+    /**
+     * First connected body.
+     * @property bodyA
+     * @type {Body}
+     */
+    this.bodyA = bodyA;
+
+    /**
+     * Second connected body.
+     * @property bodyB
+     * @type {Body}
+     */
+    this.bodyB = bodyB;
+}
+
+/**
+ * Apply the spring force to the connected bodies.
+ * @method applyForce
+ */
+Spring.prototype.applyForce = function(){
+    // To be implemented by subclasses
+};
+
+},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2');
+var Utils = _dereq_('../utils/Utils');
+var Constraint = _dereq_('../constraints/Constraint');
+var FrictionEquation = _dereq_('../equations/FrictionEquation');
+var Body = _dereq_('../objects/Body');
+
+module.exports = TopDownVehicle;
+
+/**
+ * @class TopDownVehicle
+ * @constructor
+ * @param {Body} chassisBody A dynamic body, already added to the world.
+ * @param {Object} [options]
+ *
+ * @example
+ *
+ *     // Create a dynamic body for the chassis
+ *     var chassisBody = new Body({
+ *         mass: 1
+ *     });
+ *     var boxShape = new Box({ width: 0.5, height: 1 });
+ *     chassisBody.addShape(boxShape);
+ *     world.addBody(chassisBody);
+ *
+ *     // Create the vehicle
+ *     var vehicle = new TopDownVehicle(chassisBody);
+ *
+ *     // Add one front wheel and one back wheel - we don't actually need four :)
+ *     var frontWheel = vehicle.addWheel({
+ *         localPosition: [0, 0.5] // front
+ *     });
+ *     frontWheel.setSideFriction(4);
+ *
+ *     // Back wheel
+ *     var backWheel = vehicle.addWheel({
+ *         localPosition: [0, -0.5] // back
+ *     });
+ *     backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift
+ *     vehicle.addToWorld(world);
+ *
+ *     // Steer value zero means straight forward. Positive is left and negative right.
+ *     frontWheel.steerValue = Math.PI / 16;
+ *
+ *     // Engine force forward
+ *     backWheel.engineForce = 10;
+ *     backWheel.setBrakeForce(0);
+ */
+function TopDownVehicle(chassisBody, options){
+    options = options || {};
+
+    /**
+     * @property {Body} chassisBody
+     */
+    this.chassisBody = chassisBody;
+
+    /**
+     * @property {Array} wheels
+     */
+    this.wheels = [];
+
+    // A dummy body to constrain the chassis to
+    this.groundBody = new Body({ mass: 0 });
+
+    this.world = null;
+
+    var that = this;
+    this.preStepCallback = function(){
+        that.update();
+    };
+}
+
+/**
+ * @method addToWorld
+ * @param {World} world
+ */
+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);
+    }
+};
+
+/**
+ * @method removeFromWorld
+ * @param {World} world
+ */
+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;
+};
+
+/**
+ * @method addWheel
+ * @param {object} [wheelOptions]
+ * @return {WheelConstraint}
+ */
+TopDownVehicle.prototype.addWheel = function(wheelOptions){
+    var wheel = new WheelConstraint(this,wheelOptions);
+    this.wheels.push(wheel);
+    return wheel;
+};
+
+/**
+ * @method update
+ */
+TopDownVehicle.prototype.update = function(){
+    for (var i = 0; i < this.wheels.length; i++) {
+        this.wheels[i].update();
+    }
+};
+
+/**
+ * @class WheelConstraint
+ * @constructor
+ * @extends {Constraint}
+ * @param {Vehicle} vehicle
+ * @param {object} [options]
+ * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero.
+ * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body.
+ * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction.
+ */
+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);
+
+    /**
+     * @property {number} steerValue
+     */
+    this.steerValue = 0;
+
+    /**
+     * @property {number} engineForce
+     */
+    this.engineForce = 0;
+
+    this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5);
+
+    /**
+     * @property {Array} localForwardVector
+     */
+    this.localForwardVector = vec2.fromValues(0, 1);
+    if(options.localForwardVector){
+        vec2.copy(this.localForwardVector, options.localForwardVector);
+    }
+
+    /**
+     * @property {Array} localPosition
+     */
+    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();
+
+/**
+ * @method setForwardFriction
+ */
+WheelConstraint.prototype.setBrakeForce = function(force){
+    this.forwardEquation.setSlipForce(force);
+};
+
+/**
+ * @method setSideFriction
+ */
+WheelConstraint.prototype.setSideFriction = function(force){
+    this.sideEquation.setSlipForce(force);
+};
+
+var worldVelocity = vec2.create();
+var relativePoint = vec2.create();
+
+/**
+ * @method getSpeed
+ */
+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();
+
+/**
+ * @method update
+ */
+WheelConstraint.prototype.update = function(){
+
+    // Directional
+    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);
+
+    // Attachment point
+    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);
+
+    // Add engine force
+    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":57}],36:[function(_dereq_,module,exports){
+// Export p2 classes
+var p2 = module.exports = {
+    AABB :                          _dereq_('./collision/AABB'),
+    AngleLockEquation :             _dereq_('./equations/AngleLockEquation'),
+    Body :                          _dereq_('./objects/Body'),
+    Broadphase :                    _dereq_('./collision/Broadphase'),
+    Capsule :                       _dereq_('./shapes/Capsule'),
+    Circle :                        _dereq_('./shapes/Circle'),
+    Constraint :                    _dereq_('./constraints/Constraint'),
+    ContactEquation :               _dereq_('./equations/ContactEquation'),
+    ContactEquationPool :           _dereq_('./utils/ContactEquationPool'),
+    ContactMaterial :               _dereq_('./material/ContactMaterial'),
+    Convex :                        _dereq_('./shapes/Convex'),
+    DistanceConstraint :            _dereq_('./constraints/DistanceConstraint'),
+    Equation :                      _dereq_('./equations/Equation'),
+    EventEmitter :                  _dereq_('./events/EventEmitter'),
+    FrictionEquation :              _dereq_('./equations/FrictionEquation'),
+    FrictionEquationPool :          _dereq_('./utils/FrictionEquationPool'),
+    GearConstraint :                _dereq_('./constraints/GearConstraint'),
+    GSSolver :                      _dereq_('./solver/GSSolver'),
+    Heightfield :                   _dereq_('./shapes/Heightfield'),
+    Line :                          _dereq_('./shapes/Line'),
+    LockConstraint :                _dereq_('./constraints/LockConstraint'),
+    Material :                      _dereq_('./material/Material'),
+    Narrowphase :                   _dereq_('./collision/Narrowphase'),
+    NaiveBroadphase :               _dereq_('./collision/NaiveBroadphase'),
+    Particle :                      _dereq_('./shapes/Particle'),
+    Plane :                         _dereq_('./shapes/Plane'),
+    Pool :                          _dereq_('./utils/Pool'),
+    RevoluteConstraint :            _dereq_('./constraints/RevoluteConstraint'),
+    PrismaticConstraint :           _dereq_('./constraints/PrismaticConstraint'),
+    Ray :                           _dereq_('./collision/Ray'),
+    RaycastResult :                 _dereq_('./collision/RaycastResult'),
+    Box :                           _dereq_('./shapes/Box'),
+    RotationalVelocityEquation :    _dereq_('./equations/RotationalVelocityEquation'),
+    SAPBroadphase :                 _dereq_('./collision/SAPBroadphase'),
+    Shape :                         _dereq_('./shapes/Shape'),
+    Solver :                        _dereq_('./solver/Solver'),
+    Spring :                        _dereq_('./objects/Spring'),
+    TopDownVehicle :                _dereq_('./objects/TopDownVehicle'),
+    LinearSpring :                  _dereq_('./objects/LinearSpring'),
+    RotationalSpring :              _dereq_('./objects/RotationalSpring'),
+    Utils :                         _dereq_('./utils/Utils'),
+    World :                         _dereq_('./world/World'),
+    vec2 :                          _dereq_('./math/vec2'),
+    version :                       _dereq_('../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":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   Shape = _dereq_('./Shape')
+,   Convex = _dereq_('./Convex');
+
+module.exports = Box;
+
+/**
+ * Box shape class.
+ * @class Box
+ * @constructor
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @param {Number} [options.width=1] Total width of the box
+ * @param {Number} [options.height=1] Total height of the box
+ * @extends Convex
+ */
+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 || {};
+
+    /**
+     * Total width of the box
+     * @property width
+     * @type {Number}
+     */
+    var width = this.width = options.width || 1;
+
+    /**
+     * Total height of the box
+     * @property height
+     * @type {Number}
+     */
+    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;
+
+/**
+ * Compute moment of inertia
+ * @method computeMomentOfInertia
+ * @param  {Number} mass
+ * @return {Number}
+ */
+Box.prototype.computeMomentOfInertia = function(mass){
+    var w = this.width,
+        h = this.height;
+    return mass * (h*h + w*w) / 12;
+};
+
+/**
+ * Update the bounding radius
+ * @method updateBoundingRadius
+ */
+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();
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out      The resulting AABB.
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+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":40,"./Shape":45}],38:[function(_dereq_,module,exports){
+var Shape = _dereq_('./Shape')
+,   vec2 = _dereq_('../math/vec2');
+
+module.exports = Capsule;
+
+/**
+ * Capsule shape class.
+ * @class Capsule
+ * @constructor
+ * @extends Shape
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @param {Number} [options.length=1] The distance between the end points
+ * @param {Number} [options.radius=1] Radius of the capsule
+ * @example
+ *     var capsuleShape = new Capsule({
+ *         length: 1,
+ *         radius: 2
+ *     });
+ *     body.addShape(capsuleShape);
+ */
+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 || {};
+
+    /**
+     * The distance between the end points.
+     * @property {Number} length
+     */
+    this.length = options.length || 1;
+
+    /**
+     * The radius of the capsule.
+     * @property {Number} radius
+     */
+    this.radius = options.radius || 1;
+
+    options.type = Shape.CAPSULE;
+    Shape.call(this, options);
+}
+Capsule.prototype = new Shape();
+Capsule.prototype.constructor = Capsule;
+
+/**
+ * Compute the mass moment of inertia of the Capsule.
+ * @method conputeMomentOfInertia
+ * @param  {Number} mass
+ * @return {Number}
+ * @todo
+ */
+Capsule.prototype.computeMomentOfInertia = function(mass){
+    // Approximate with rectangle
+    var r = this.radius,
+        w = this.length + r, // 2*r is too much, 0 is too little
+        h = r*2;
+    return mass * (h*h + w*w) / 12;
+};
+
+/**
+ * @method updateBoundingRadius
+ */
+Capsule.prototype.updateBoundingRadius = function(){
+    this.boundingRadius = this.radius + this.length/2;
+};
+
+/**
+ * @method updateArea
+ */
+Capsule.prototype.updateArea = function(){
+    this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length;
+};
+
+var r = vec2.create();
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out      The resulting AABB.
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+Capsule.prototype.computeAABB = function(out, position, angle){
+    var radius = this.radius;
+
+    // Compute center position of one of the the circles, world oriented, but with local offset
+    vec2.set(r,this.length / 2,0);
+    if(angle !== 0){
+        vec2.rotate(r,r,angle);
+    }
+
+    // Get bounds
+    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));
+
+    // Add offset
+    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);
+
+/**
+ * @method raycast
+ * @param  {RaycastResult} result
+ * @param  {Ray} ray
+ * @param  {array} position
+ * @param  {number} angle
+ */
+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;
+
+    // The sides
+    var halfLen = this.length / 2;
+    for(var i=0; i<2; i++){
+
+        // get start and end of the line
+        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;
+            }
+        }
+    }
+
+    // Circles
+    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){
+            // No intersection
+            continue;
+
+        } else if(delta === 0){
+            // single intersection point
+            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":45}],39:[function(_dereq_,module,exports){
+var Shape = _dereq_('./Shape')
+,    vec2 = _dereq_('../math/vec2');
+
+module.exports = Circle;
+
+/**
+ * Circle shape class.
+ * @class Circle
+ * @extends Shape
+ * @constructor
+ * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @param {number} [options.radius=1] The radius of this circle
+ *
+ * @example
+ *     var circleShape = new Circle({ radius: 1 });
+ *     body.addShape(circleShape);
+ */
+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 || {};
+
+    /**
+     * The radius of the circle.
+     * @property radius
+     * @type {number}
+     */
+    this.radius = options.radius || 1;
+
+    options.type = Shape.CIRCLE;
+    Shape.call(this, options);
+}
+Circle.prototype = new Shape();
+Circle.prototype.constructor = Circle;
+
+/**
+ * @method computeMomentOfInertia
+ * @param  {Number} mass
+ * @return {Number}
+ */
+Circle.prototype.computeMomentOfInertia = function(mass){
+    var r = this.radius;
+    return mass * r * r / 2;
+};
+
+/**
+ * @method updateBoundingRadius
+ * @return {Number}
+ */
+Circle.prototype.updateBoundingRadius = function(){
+    this.boundingRadius = this.radius;
+};
+
+/**
+ * @method updateArea
+ * @return {Number}
+ */
+Circle.prototype.updateArea = function(){
+    this.area = Math.PI * this.radius * this.radius;
+};
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out      The resulting AABB.
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+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();
+
+/**
+ * @method raycast
+ * @param  {RaycastResult} result
+ * @param  {Ray} ray
+ * @param  {array} position
+ * @param  {number} angle
+ */
+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){
+        // No intersection
+        return;
+
+    } else if(delta === 0){
+        // single intersection point
+        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":45}],40:[function(_dereq_,module,exports){
+var Shape = _dereq_('./Shape')
+,   vec2 = _dereq_('../math/vec2')
+,   polyk = _dereq_('../math/polyk')
+,   decomp = _dereq_('poly-decomp');
+
+module.exports = Convex;
+
+/**
+ * Convex shape class.
+ * @class Convex
+ * @constructor
+ * @extends Shape
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction.
+ * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex.
+ * @example
+ *     // Create a box
+ *     var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]];
+ *     var convexShape = new Convex({ vertices: vertices });
+ *     body.addShape(convexShape);
+ */
+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 || {};
+
+    /**
+     * Vertices defined in the local frame.
+     * @property vertices
+     * @type {Array}
+     */
+    this.vertices = [];
+
+    // Copy the verts
+    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);
+    }
+
+    /**
+     * Axes defined in the local frame.
+     * @property axes
+     * @type {Array}
+     */
+    this.axes = [];
+
+    if(options.axes){
+
+        // Copy the 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 {
+
+        // Construct axes from the vertex data
+        for(var i = 0; i < this.vertices.length; i++){
+            // Get the world edge
+            var worldPoint0 = this.vertices[i];
+            var worldPoint1 = this.vertices[(i+1) % this.vertices.length];
+
+            var normal = vec2.create();
+            vec2.sub(normal, worldPoint1, worldPoint0);
+
+            // Get normal - just rotate 90 degrees since vertices are given in CCW
+            vec2.rotate90cw(normal, normal);
+            vec2.normalize(normal, normal);
+
+            this.axes.push(normal);
+        }
+
+    }
+
+    /**
+     * The center of mass of the Convex
+     * @property centerOfMass
+     * @type {Array}
+     */
+    this.centerOfMass = vec2.fromValues(0,0);
+
+    /**
+     * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices.
+     * @property triangles
+     * @type {Array}
+     */
+    this.triangles = [];
+
+    if(this.vertices.length){
+        this.updateTriangles();
+        this.updateCenterOfMass();
+    }
+
+    /**
+     * The bounding radius of the convex
+     * @property boundingRadius
+     * @type {Number}
+     */
+    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();
+
+/**
+ * Project a Convex onto a world-oriented axis
+ * @method projectOntoAxis
+ * @static
+ * @param  {Array} offset
+ * @param  {Array} localAxis
+ * @param  {Array} result
+ */
+Convex.prototype.projectOntoLocalAxis = function(localAxis, result){
+    var max=null,
+        min=null,
+        v,
+        value,
+        localAxis = tmpVec1;
+
+    // Get projected position of all vertices
+    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);
+
+    // Project the position of the body onto the axis - need to add this to the 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);
+};
+
+
+/**
+ * Update the .triangles property
+ * @method updateTriangles
+ */
+Convex.prototype.updateTriangles = function(){
+
+    this.triangles.length = 0;
+
+    // Rewrite on polyk notation, array of numbers
+    var polykVerts = [];
+    for(var i=0; i<this.vertices.length; i++){
+        var v = this.vertices[i];
+        polykVerts.push(v[0],v[1]);
+    }
+
+    // Triangulate
+    var triangles = polyk.Triangulate(polykVerts);
+
+    // Loop over all triangles, add their inertia contributions to I
+    for(var i=0; i<triangles.length; i+=3){
+        var id1 = triangles[i],
+            id2 = triangles[i+1],
+            id3 = triangles[i+2];
+
+        // Add to triangles
+        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();
+
+/**
+ * Update the .centerOfMass property.
+ * @method updateCenterOfMass
+ */
+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);
+
+        // Get mass for the triangle (density=1 in this case)
+        // http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors
+        var m = Convex.triangleArea(a,b,c);
+        totalArea += m;
+
+        // Add to center of mass
+        vec2.scale(centroid_times_mass, centroid, m);
+        vec2.add(cm, cm, centroid_times_mass);
+    }
+
+    vec2.scale(cm,cm,1/totalArea);
+};
+
+/**
+ * Compute the mass moment of inertia of the Convex.
+ * @method computeMomentOfInertia
+ * @param  {Number} mass
+ * @return {Number}
+ * @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/
+ */
+Convex.prototype.computeMomentOfInertia = function(mass){
+    var denom = 0.0,
+        numer = 0.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.0) * (denom / numer);
+};
+
+/**
+ * Updates the .boundingRadius property
+ * @method updateBoundingRadius
+ */
+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);
+};
+
+/**
+ * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative.
+ * @static
+ * @method triangleArea
+ * @param {Array} a
+ * @param {Array} b
+ * @param {Array} c
+ * @return {Number}
+ */
+Convex.triangleArea = function(a,b,c){
+    return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5;
+};
+
+/**
+ * Update the .area
+ * @method updateArea
+ */
+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]];
+
+        // Get mass for the triangle (density=1 in this case)
+        var m = Convex.triangleArea(a,b,c);
+        this.area += m;
+    }
+};
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+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();
+
+/**
+ * @method raycast
+ * @param  {RaycastResult} result
+ * @param  {Ray} ray
+ * @param  {array} position
+ * @param  {number} angle
+ */
+Convex.prototype.raycast = function(result, ray, position, angle){
+    var rayStart = intersectConvex_rayStart;
+    var rayEnd = intersectConvex_rayEnd;
+    var normal = intersectConvex_normal;
+    var vertices = this.vertices;
+
+    // Transform to local shape space
+    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":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){
+var Shape = _dereq_('./Shape')
+,    vec2 = _dereq_('../math/vec2')
+,    Utils = _dereq_('../utils/Utils');
+
+module.exports = Heightfield;
+
+/**
+ * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth".
+ * @class Heightfield
+ * @extends Shape
+ * @constructor
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @param {array} [options.heights] An array of Y values that will be used to construct the terrain.
+ * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
+ * @param {Number} [options.maxValue] Maximum value.
+ * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction.
+ *
+ * @example
+ *     // Generate some height data (y-values).
+ *     var heights = [];
+ *     for(var i = 0; i < 1000; i++){
+ *         var y = 0.5 * Math.cos(0.2 * i);
+ *         heights.push(y);
+ *     }
+ *
+ *     // Create the heightfield shape
+ *     var heightfieldShape = new Heightfield({
+ *         heights: heights,
+ *         elementWidth: 1 // Distance between the data points in X direction
+ *     });
+ *     var heightfieldBody = new Body();
+ *     heightfieldBody.addShape(heightfieldShape);
+ *     world.addBody(heightfieldBody);
+ *
+ * @todo Should use a scale property with X and Y direction instead of just elementWidth
+ */
+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 || {};
+
+    /**
+     * An array of numbers, or height values, that are spread out along the x axis.
+     * @property {array} heights
+     */
+    this.heights = options.heights ? options.heights.slice(0) : [];
+
+    /**
+     * Max value of the heights
+     * @property {number} maxValue
+     */
+    this.maxValue = options.maxValue || null;
+
+    /**
+     * Max value of the heights
+     * @property {number} minValue
+     */
+    this.minValue = options.minValue || null;
+
+    /**
+     * The width of each element
+     * @property {number} elementWidth
+     */
+    this.elementWidth = options.elementWidth || 0.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;
+
+/**
+ * Update the .minValue and the .maxValue
+ * @method updateMaxMinValues
+ */
+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;
+};
+
+/**
+ * @method computeMomentOfInertia
+ * @param  {Number} mass
+ * @return {Number}
+ */
+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()
+];
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out      The resulting AABB.
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+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);
+};
+
+/**
+ * Get a line segment in the heightfield
+ * @method getLineSegment
+ * @param  {array} start Where to store the resulting start point
+ * @param  {array} end Where to store the resulting end point
+ * @param  {number} i
+ */
+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)); // clamp
+    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);
+
+// Returns 1 if the lines intersect, otherwise 0.
+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) { // Collision detected
+        var intX = p0[0] + (t * s1_x);
+        var intY = p0[1] + (t * s1_y);
+        out[0] = intX;
+        out[1] = intY;
+        return t;
+    }
+    return -1; // No collision
+}
+
+/**
+ * @method raycast
+ * @param  {RayResult} result
+ * @param  {Ray} ray
+ * @param  {array} position
+ * @param  {number} angle
+ */
+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;
+
+    // get local ray start and end
+    vec2.toLocalFrame(localFrom, from, position, angle);
+    vec2.toLocalFrame(localTo, to, position, angle);
+
+    // Get the segment range
+    var i0 = this.getClampedSegmentIndex(localFrom);
+    var i1 = this.getClampedSegmentIndex(localTo);
+    if(i0 > i1){
+        var tmp = i0;
+        i0 = i1;
+        i1 = tmp;
+    }
+
+    // The segments
+    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":57,"./Shape":45}],42:[function(_dereq_,module,exports){
+var Shape = _dereq_('./Shape')
+,   vec2 = _dereq_('../math/vec2');
+
+module.exports = Line;
+
+/**
+ * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
+ * @class Line
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @param {Number} [options.length=1] The total length of the line
+ * @extends Shape
+ * @constructor
+ */
+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 || {};
+
+    /**
+     * Length of this line
+     * @property {Number} length
+     * @default 1
+     */
+    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()];
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out      The resulting AABB.
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+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);
+
+/**
+ * @method raycast
+ * @param  {RaycastResult} result
+ * @param  {Ray} ray
+ * @param  {number} angle
+ * @param  {array} position
+ */
+Line.prototype.raycast = function(result, ray, position, angle){
+    var from = ray.from;
+    var to = ray.to;
+
+    var l0 = raycast_l0;
+    var l1 = raycast_l1;
+
+    // get start and end of the line
+    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); // todo: this should depend on which side the ray comes from
+        ray.reportIntersection(result, fraction, normal, -1);
+    }
+};
+},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){
+var Shape = _dereq_('./Shape')
+,   vec2 = _dereq_('../math/vec2');
+
+module.exports = Particle;
+
+/**
+ * Particle shape class.
+ * @class Particle
+ * @constructor
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ * @extends Shape
+ */
+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; // Can't rotate a particle
+};
+
+Particle.prototype.updateBoundingRadius = function(){
+    this.boundingRadius = 0;
+};
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+Particle.prototype.computeAABB = function(out, position, angle){
+    vec2.copy(out.lowerBound, position);
+    vec2.copy(out.upperBound, position);
+};
+
+},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){
+var Shape =  _dereq_('./Shape')
+,    vec2 =  _dereq_('../math/vec2')
+,    Utils = _dereq_('../utils/Utils');
+
+module.exports = Plane;
+
+/**
+ * Plane shape class. The plane is facing in the Y direction.
+ * @class Plane
+ * @extends Shape
+ * @constructor
+ * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
+ */
+function Plane(options){
+    options = options || {};
+    options.type = Shape.PLANE;
+    Shape.call(this, options);
+}
+Plane.prototype = new Shape();
+Plane.prototype.constructor = Plane;
+
+/**
+ * Compute moment of inertia
+ * @method computeMomentOfInertia
+ */
+Plane.prototype.computeMomentOfInertia = function(mass){
+    return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here
+};
+
+/**
+ * Update the bounding radius
+ * @method updateBoundingRadius
+ */
+Plane.prototype.updateBoundingRadius = function(){
+    this.boundingRadius = Number.MAX_VALUE;
+};
+
+/**
+ * @method computeAABB
+ * @param  {AABB}   out
+ * @param  {Array}  position
+ * @param  {Number} angle
+ */
+Plane.prototype.computeAABB = function(out, position, angle){
+    var a = angle % (2 * Math.PI);
+    var set = vec2.set;
+    var max = Number.MAX_VALUE;
+    var lowerBound = out.lowerBound;
+    var upperBound = out.upperBound;
+
+    if(a === 0){
+        // y goes from -inf to 0
+        set(lowerBound, -max, -max);
+        set(upperBound,  max,  0);
+
+    } else if(a === Math.PI / 2){
+
+        // x goes from 0 to inf
+        set(lowerBound, 0, -max);
+        set(upperBound,      max,  max);
+
+    } else if(a === Math.PI){
+
+        // y goes from 0 to inf
+        set(lowerBound, -max, 0);
+        set(upperBound,  max, max);
+
+    } else if(a === 3*Math.PI/2){
+
+        // x goes from -inf to 0
+        set(lowerBound, -max,     -max);
+        set(upperBound,  0,  max);
+
+    } else {
+
+        // Set max bounds
+        set(lowerBound, -max, -max);
+        set(upperBound,  max,  max);
+    }
+
+    vec2.add(lowerBound, lowerBound, position);
+    vec2.add(upperBound, upperBound, position);
+};
+
+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();
+
+/**
+ * @method raycast
+ * @param  {RayResult} result
+ * @param  {Ray} ray
+ * @param  {array} position
+ * @param  {number} angle
+ */
+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;
+
+    // Get plane normal
+    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){
+        // "from" and "to" are on the same side of the plane... bail out
+        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":57,"./Shape":45}],45:[function(_dereq_,module,exports){
+module.exports = Shape;
+
+var vec2 = _dereq_('../math/vec2');
+
+/**
+ * Base class for shapes.
+ * @class Shape
+ * @constructor
+ * @param {object} [options]
+ * @param {array} [options.position]
+ * @param {number} [options.angle=0]
+ * @param {number} [options.collisionGroup=1]
+ * @param {number} [options.collisionMask=1]
+ * @param {boolean} [options.sensor=false]
+ * @param {boolean} [options.collisionResponse=true]
+ * @param {object} [options.type=0]
+ */
+function Shape(options){
+    options = options || {};
+
+    /**
+     * The body this shape is attached to. A shape can only be attached to a single body.
+     * @property {Body} body
+     */
+    this.body = null;
+
+    /**
+     * Body-local position of the shape.
+     * @property {Array} position
+     */
+    this.position = vec2.fromValues(0,0);
+    if(options.position){
+        vec2.copy(this.position, options.position);
+    }
+
+    /**
+     * Body-local angle of the shape.
+     * @property {number} angle
+     */
+    this.angle = options.angle || 0;
+
+    /**
+     * The type of the shape. One of:
+     *
+     * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}}
+     * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}}
+     * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}}
+     * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}}
+     * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}}
+     * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}}
+     * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}}
+     * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}}
+     *
+     * @property {number} type
+     */
+    this.type = options.type || 0;
+
+    /**
+     * Shape object identifier.
+     * @type {Number}
+     * @property id
+     */
+    this.id = Shape.idCounter++;
+
+    /**
+     * Bounding circle radius of this shape
+     * @property boundingRadius
+     * @type {Number}
+     */
+    this.boundingRadius = 0;
+
+    /**
+     * Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
+     * @property collisionGroup
+     * @type {Number}
+     * @example
+     *     // Setup bits for each available group
+     *     var PLAYER = Math.pow(2,0),
+     *         ENEMY =  Math.pow(2,1),
+     *         GROUND = Math.pow(2,2)
+     *
+     *     // Put shapes into their groups
+     *     player1Shape.collisionGroup = PLAYER;
+     *     player2Shape.collisionGroup = PLAYER;
+     *     enemyShape  .collisionGroup = ENEMY;
+     *     groundShape .collisionGroup = GROUND;
+     *
+     *     // Assign groups that each shape collide with.
+     *     // Note that the players can collide with ground and enemies, but not with other players.
+     *     player1Shape.collisionMask = ENEMY | GROUND;
+     *     player2Shape.collisionMask = ENEMY | GROUND;
+     *     enemyShape  .collisionMask = PLAYER | GROUND;
+     *     groundShape .collisionMask = PLAYER | ENEMY;
+     *
+     * @example
+     *     // How collision check is done
+     *     if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
+     *         // The shapes will collide
+     *     }
+     */
+    this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
+
+    /**
+     * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
+     * @property {Boolean} collisionResponse
+     */
+    this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
+
+    /**
+     * Collision mask of this shape. See .collisionGroup.
+     * @property collisionMask
+     * @type {Number}
+     */
+    this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
+
+    /**
+     * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
+     * @property material
+     * @type {Material}
+     */
+    this.material = options.material || null;
+
+    /**
+     * Area of this shape.
+     * @property area
+     * @type {Number}
+     */
+    this.area = 0;
+
+    /**
+     * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
+     * @property {Boolean} sensor
+     */
+    this.sensor = options.sensor !== undefined ? options.sensor : false;
+
+    if(this.type){
+        this.updateBoundingRadius();
+    }
+
+    this.updateArea();
+}
+
+Shape.idCounter = 0;
+
+/**
+ * @static
+ * @property {Number} CIRCLE
+ */
+Shape.CIRCLE =      1;
+
+/**
+ * @static
+ * @property {Number} PARTICLE
+ */
+Shape.PARTICLE =    2;
+
+/**
+ * @static
+ * @property {Number} PLANE
+ */
+Shape.PLANE =       4;
+
+/**
+ * @static
+ * @property {Number} CONVEX
+ */
+Shape.CONVEX =      8;
+
+/**
+ * @static
+ * @property {Number} LINE
+ */
+Shape.LINE =        16;
+
+/**
+ * @static
+ * @property {Number} BOX
+ */
+Shape.BOX =   32;
+
+Object.defineProperty(Shape, 'RECTANGLE', {
+    get: function() {
+        console.warn('Shape.RECTANGLE is deprecated, use Shape.BOX instead.');
+        return Shape.BOX;
+    }
+});
+
+/**
+ * @static
+ * @property {Number} CAPSULE
+ */
+Shape.CAPSULE =     64;
+
+/**
+ * @static
+ * @property {Number} HEIGHTFIELD
+ */
+Shape.HEIGHTFIELD = 128;
+
+/**
+ * Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
+ * @method computeMomentOfInertia
+ * @param  {Number} mass
+ * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
+ */
+Shape.prototype.computeMomentOfInertia = function(mass){};
+
+/**
+ * Returns the bounding circle radius of this shape.
+ * @method updateBoundingRadius
+ * @return {Number}
+ */
+Shape.prototype.updateBoundingRadius = function(){};
+
+/**
+ * Update the .area property of the shape.
+ * @method updateArea
+ */
+Shape.prototype.updateArea = function(){
+    // To be implemented in all subclasses
+};
+
+/**
+ * Compute the world axis-aligned bounding box (AABB) of this shape.
+ * @method computeAABB
+ * @param  {AABB} out The resulting AABB.
+ * @param  {Array} position World position of the shape.
+ * @param  {Number} angle World angle of the shape.
+ */
+Shape.prototype.computeAABB = function(out, position, angle){
+    // To be implemented in each subclass
+};
+
+/**
+ * Perform raycasting on this shape.
+ * @method raycast
+ * @param  {RayResult} result Where to store the resulting data.
+ * @param  {Ray} ray The Ray that you want to use for raycasting.
+ * @param  {array} position World position of the shape (the .position property will be ignored).
+ * @param  {number} angle World angle of the shape (the .angle property will be ignored).
+ */
+Shape.prototype.raycast = function(result, ray, position, angle){
+    // To be implemented in each subclass
+};
+},{"../math/vec2":30}],46:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   Solver = _dereq_('./Solver')
+,   Utils = _dereq_('../utils/Utils')
+,   FrictionEquation = _dereq_('../equations/FrictionEquation');
+
+module.exports = GSSolver;
+
+/**
+ * Iterative Gauss-Seidel constraint equation solver.
+ *
+ * @class GSSolver
+ * @constructor
+ * @extends Solver
+ * @param {Object} [options]
+ * @param {Number} [options.iterations=10]
+ * @param {Number} [options.tolerance=0]
+ */
+function GSSolver(options){
+    Solver.call(this,options,Solver.GS);
+    options = options || {};
+
+    /**
+     * The max number of iterations to do when solving. More gives better results, but is more expensive.
+     * @property iterations
+     * @type {Number}
+     */
+    this.iterations = options.iterations || 10;
+
+    /**
+     * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster.
+     * @property tolerance
+     * @type {Number}
+     * @default 1e-7
+     */
+    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);
+
+    /**
+     * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications.
+     * @property useZeroRHS
+     * @type {Boolean}
+     */
+    this.useZeroRHS = false;
+
+    /**
+     * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example.
+     * The solver will use less iterations if the solution is below the .tolerance.
+     * @property frictionIterations
+     * @type {Number}
+     */
+    this.frictionIterations = 0;
+
+    /**
+     * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations.
+     * @property {Number} usedIterations
+     */
+    this.usedIterations = 0;
+}
+GSSolver.prototype = new Solver();
+GSSolver.prototype.constructor = GSSolver;
+
+function setArrayZero(array){
+    var l = array.length;
+    while(l--){
+        array[l] = +0.0;
+    }
+}
+
+/**
+ * Solve the system of equations
+ * @method solve
+ * @param  {Number}  h       Time step
+ * @param  {World}   world    World to solve
+ */
+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];
+
+            // Update solve mass
+            b.updateSolveMassProperties();
+        }
+    }
+
+    // Things that does not change during iteration can be computed once
+    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];
+
+            // Reset vlambda
+            b.resetConstraintVelocity();
+        }
+
+        if(maxFrictionIter){
+            // Iterate over contact equations to get normal forces
+            for(iter=0; iter!==maxFrictionIter; iter++){
+
+                // Accumulate the total error for each iteration.
+                deltalambdaTot = 0.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 the total error is small enough - stop iterate
+                if(deltalambdaTot*deltalambdaTot <= tolSquared){
+                    break;
+                }
+            }
+
+            GSSolver.updateMultipliers(equations, lambda, 1/h);
+
+            // Set computed friction force
+            for(j=0; j!==Neq; j++){
+                var eq = equations[j];
+                if(eq instanceof FrictionEquation){
+                    var f = 0.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;
+                }
+            }
+        }
+
+        // Iterate over all equations
+        for(iter=0; iter!==maxIter; iter++){
+
+            // Accumulate the total error for each iteration.
+            deltalambdaTot = 0.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 the total error is small enough - stop iterate
+            if(deltalambdaTot*deltalambdaTot <= tolSquared){
+                break;
+            }
+        }
+
+        // Add result to velocity
+        for(i=0; i!==Nbodies; i++){
+            bodies[i].addConstraintVelocity();
+        }
+
+        GSSolver.updateMultipliers(equations, lambda, 1/h);
+    }
+};
+
+// Sets the .multiplier property of each equation
+GSSolver.updateMultipliers = function(equations, lambda, invDt){
+    // Set the .multiplier property of each equation
+    var l = equations.length;
+    while(l--){
+        equations[l].multiplier = lambda[l] * invDt;
+    }
+};
+
+GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){
+    // Compute iteration
+    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 );
+
+    // Clamp if we are not within the min/max interval
+    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":57,"./Solver":47}],47:[function(_dereq_,module,exports){
+var Utils = _dereq_('../utils/Utils')
+,   EventEmitter = _dereq_('../events/EventEmitter');
+
+module.exports = Solver;
+
+/**
+ * Base class for constraint solvers.
+ * @class Solver
+ * @constructor
+ * @extends EventEmitter
+ */
+function Solver(options,type){
+    options = options || {};
+
+    EventEmitter.call(this);
+
+    this.type = type;
+
+    /**
+     * Current equations in the solver.
+     *
+     * @property equations
+     * @type {Array}
+     */
+    this.equations = [];
+
+    /**
+     * Function that is used to sort all equations before each solve.
+     * @property equationSortFunction
+     * @type {function|boolean}
+     */
+    this.equationSortFunction = options.equationSortFunction || false;
+}
+Solver.prototype = new EventEmitter();
+Solver.prototype.constructor = Solver;
+
+/**
+ * Method to be implemented in each subclass
+ * @method solve
+ * @param  {Number} dt
+ * @param  {World} world
+ */
+Solver.prototype.solve = function(dt,world){
+    throw new Error("Solver.solve should be implemented by subclasses!");
+};
+
+var mockWorld = {bodies:[]};
+
+/**
+ * Solves all constraints in an island.
+ * @method solveIsland
+ * @param  {Number} dt
+ * @param  {Island} island
+ */
+Solver.prototype.solveIsland = function(dt,island){
+
+    this.removeAllEquations();
+
+    if(island.equations.length){
+        // Add equations to solver
+        this.addEquations(island.equations);
+        mockWorld.bodies.length = 0;
+        island.getBodies(mockWorld.bodies);
+
+        // Solve
+        if(mockWorld.bodies.length){
+            this.solve(dt,mockWorld);
+        }
+    }
+};
+
+/**
+ * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving.
+ * @method sortEquations
+ */
+Solver.prototype.sortEquations = function(){
+    if(this.equationSortFunction){
+        this.equations.sort(this.equationSortFunction);
+    }
+};
+
+/**
+ * Add an equation to be solved.
+ *
+ * @method addEquation
+ * @param {Equation} eq
+ */
+Solver.prototype.addEquation = function(eq){
+    if(eq.enabled){
+        this.equations.push(eq);
+    }
+};
+
+/**
+ * Add equations. Same as .addEquation, but this time the argument is an array of Equations
+ *
+ * @method addEquations
+ * @param {Array} eqs
+ */
+Solver.prototype.addEquations = function(eqs){
+    //Utils.appendArray(this.equations,eqs);
+    for(var i=0, N=eqs.length; i!==N; i++){
+        var eq = eqs[i];
+        if(eq.enabled){
+            this.equations.push(eq);
+        }
+    }
+};
+
+/**
+ * Remove an equation.
+ *
+ * @method removeEquation
+ * @param {Equation} eq
+ */
+Solver.prototype.removeEquation = function(eq){
+    var i = this.equations.indexOf(eq);
+    if(i !== -1){
+        this.equations.splice(i,1);
+    }
+};
+
+/**
+ * Remove all currently added equations.
+ *
+ * @method removeAllEquations
+ */
+Solver.prototype.removeAllEquations = function(){
+    this.equations.length=0;
+};
+
+Solver.GS = 1;
+Solver.ISLAND = 2;
+
+},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){
+var ContactEquation = _dereq_('../equations/ContactEquation');
+var Pool = _dereq_('./Pool');
+
+module.exports = ContactEquationPool;
+
+/**
+ * @class
+ */
+function ContactEquationPool() {
+	Pool.apply(this, arguments);
+}
+ContactEquationPool.prototype = new Pool();
+ContactEquationPool.prototype.constructor = ContactEquationPool;
+
+/**
+ * @method create
+ * @return {ContactEquation}
+ */
+ContactEquationPool.prototype.create = function () {
+	return new ContactEquation();
+};
+
+/**
+ * @method destroy
+ * @param {ContactEquation} equation
+ * @return {ContactEquationPool}
+ */
+ContactEquationPool.prototype.destroy = function (equation) {
+	equation.bodyA = equation.bodyB = null;
+	return this;
+};
+
+},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){
+var FrictionEquation = _dereq_('../equations/FrictionEquation');
+var Pool = _dereq_('./Pool');
+
+module.exports = FrictionEquationPool;
+
+/**
+ * @class
+ */
+function FrictionEquationPool() {
+	Pool.apply(this, arguments);
+}
+FrictionEquationPool.prototype = new Pool();
+FrictionEquationPool.prototype.constructor = FrictionEquationPool;
+
+/**
+ * @method create
+ * @return {FrictionEquation}
+ */
+FrictionEquationPool.prototype.create = function () {
+	return new FrictionEquation();
+};
+
+/**
+ * @method destroy
+ * @param {FrictionEquation} equation
+ * @return {FrictionEquationPool}
+ */
+FrictionEquationPool.prototype.destroy = function (equation) {
+	equation.bodyA = equation.bodyB = null;
+	return this;
+};
+
+},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){
+var IslandNode = _dereq_('../world/IslandNode');
+var Pool = _dereq_('./Pool');
+
+module.exports = IslandNodePool;
+
+/**
+ * @class
+ */
+function IslandNodePool() {
+	Pool.apply(this, arguments);
+}
+IslandNodePool.prototype = new Pool();
+IslandNodePool.prototype.constructor = IslandNodePool;
+
+/**
+ * @method create
+ * @return {IslandNode}
+ */
+IslandNodePool.prototype.create = function () {
+	return new IslandNode();
+};
+
+/**
+ * @method destroy
+ * @param {IslandNode} node
+ * @return {IslandNodePool}
+ */
+IslandNodePool.prototype.destroy = function (node) {
+	node.reset();
+	return this;
+};
+
+},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){
+var Island = _dereq_('../world/Island');
+var Pool = _dereq_('./Pool');
+
+module.exports = IslandPool;
+
+/**
+ * @class
+ */
+function IslandPool() {
+	Pool.apply(this, arguments);
+}
+IslandPool.prototype = new Pool();
+IslandPool.prototype.constructor = IslandPool;
+
+/**
+ * @method create
+ * @return {Island}
+ */
+IslandPool.prototype.create = function () {
+	return new Island();
+};
+
+/**
+ * @method destroy
+ * @param {Island} island
+ * @return {IslandPool}
+ */
+IslandPool.prototype.destroy = function (island) {
+	island.reset();
+	return this;
+};
+
+},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){
+var TupleDictionary = _dereq_('./TupleDictionary');
+var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord');
+var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool');
+var Utils = _dereq_('./Utils');
+
+module.exports = OverlapKeeper;
+
+/**
+ * Keeps track of overlaps in the current state and the last step state.
+ * @class OverlapKeeper
+ * @constructor
+ */
+function OverlapKeeper() {
+    this.overlappingShapesLastState = new TupleDictionary();
+    this.overlappingShapesCurrentState = new TupleDictionary();
+    this.recordPool = new OverlapKeeperRecordPool({ size: 16 });
+    this.tmpDict = new TupleDictionary();
+    this.tmpArray1 = [];
+}
+
+/**
+ * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current.
+ * @method tick
+ */
+OverlapKeeper.prototype.tick = function() {
+    var last = this.overlappingShapesLastState;
+    var current = this.overlappingShapesCurrentState;
+
+    // Save old objects into pool
+    var l = last.keys.length;
+    while(l--){
+        var key = last.keys[l];
+        var lastObject = last.getByKey(key);
+        var currentObject = current.getByKey(key);
+        if(lastObject){
+            // The record is only used in the "last" dict, and will be removed. We might as well pool it.
+            this.recordPool.release(lastObject);
+        }
+    }
+
+    // Clear last object
+    last.reset();
+
+    // Transfer from new object to old
+    last.copy(current);
+
+    // Clear current object
+    current.reset();
+};
+
+/**
+ * @method setOverlapping
+ * @param {Body} bodyA
+ * @param {Body} shapeA
+ * @param {Body} bodyB
+ * @param {Body} shapeB
+ */
+OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) {
+    var last = this.overlappingShapesLastState;
+    var current = this.overlappingShapesCurrentState;
+
+    // Store current contact state
+    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);
+};
+
+/**
+ * Checks if two bodies are currently overlapping.
+ * @method bodiesAreOverlapping
+ * @param  {Body} bodyA
+ * @param  {Body} bodyB
+ * @return {boolean}
+ */
+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){
+            // Not overlapping in last state, but in current.
+            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;
+    // Not in last but in new
+    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];
+
+        // Since we use body id's for the accumulator, these will be a subset of the original one
+        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":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){
+module.exports = OverlapKeeperRecord;
+
+/**
+ * Overlap data container for the OverlapKeeper
+ * @class OverlapKeeperRecord
+ * @constructor
+ * @param {Body} bodyA
+ * @param {Shape} shapeA
+ * @param {Body} bodyB
+ * @param {Shape} shapeB
+ */
+function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){
+    /**
+     * @property {Shape} shapeA
+     */
+    this.shapeA = shapeA;
+    /**
+     * @property {Shape} shapeB
+     */
+    this.shapeB = shapeB;
+    /**
+     * @property {Body} bodyA
+     */
+    this.bodyA = bodyA;
+    /**
+     * @property {Body} bodyB
+     */
+    this.bodyB = bodyB;
+}
+
+/**
+ * Set the data for the record
+ * @method set
+ * @param {Body} bodyA
+ * @param {Shape} shapeA
+ * @param {Body} bodyB
+ * @param {Shape} shapeB
+ */
+OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){
+    OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB);
+};
+
+},{}],54:[function(_dereq_,module,exports){
+var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord');
+var Pool = _dereq_('./Pool');
+
+module.exports = OverlapKeeperRecordPool;
+
+/**
+ * @class
+ */
+function OverlapKeeperRecordPool() {
+	Pool.apply(this, arguments);
+}
+OverlapKeeperRecordPool.prototype = new Pool();
+OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool;
+
+/**
+ * @method create
+ * @return {OverlapKeeperRecord}
+ */
+OverlapKeeperRecordPool.prototype.create = function () {
+	return new OverlapKeeperRecord();
+};
+
+/**
+ * @method destroy
+ * @param {OverlapKeeperRecord} record
+ * @return {OverlapKeeperRecordPool}
+ */
+OverlapKeeperRecordPool.prototype.destroy = function (record) {
+	record.bodyA = record.bodyB = record.shapeA = record.shapeB = null;
+	return this;
+};
+
+},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){
+module.exports = Pool;
+
+/**
+ * @class Object pooling utility.
+ */
+function Pool(options) {
+	options = options || {};
+
+	/**
+	 * @property {Array} objects
+	 * @type {Array}
+	 */
+	this.objects = [];
+
+	if(options.size !== undefined){
+		this.resize(options.size);
+	}
+}
+
+/**
+ * @method resize
+ * @param {number} size
+ * @return {Pool} Self, for chaining
+ */
+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;
+};
+
+/**
+ * Get an object from the pool or create a new instance.
+ * @method get
+ * @return {Object}
+ */
+Pool.prototype.get = function () {
+	var objects = this.objects;
+	return objects.length ? objects.pop() : this.create();
+};
+
+/**
+ * Clean up and put the object back into the pool for later use.
+ * @method release
+ * @param {Object} object
+ * @return {Pool} Self for chaining
+ */
+Pool.prototype.release = function (object) {
+	this.destroy(object);
+	this.objects.push(object);
+	return this;
+};
+
+},{}],56:[function(_dereq_,module,exports){
+var Utils = _dereq_('./Utils');
+
+module.exports = TupleDictionary;
+
+/**
+ * @class TupleDictionary
+ * @constructor
+ */
+function TupleDictionary() {
+
+    /**
+     * The data storage
+     * @property data
+     * @type {Object}
+     */
+    this.data = {};
+
+    /**
+     * Keys that are currently used.
+     * @property {Array} keys
+     */
+    this.keys = [];
+}
+
+/**
+ * Generate a key given two integers
+ * @method getKey
+ * @param  {number} i
+ * @param  {number} j
+ * @return {string}
+ */
+TupleDictionary.prototype.getKey = function(id1, id2) {
+    id1 = id1|0;
+    id2 = id2|0;
+
+    if ( (id1|0) === (id2|0) ){
+        return -1;
+    }
+
+    // valid for values < 2^16
+    return ((id1|0) > (id2|0) ?
+        (id1 << 16) | (id2 & 0xFFFF) :
+        (id2 << 16) | (id1 & 0xFFFF))|0
+        ;
+};
+
+/**
+ * @method getByKey
+ * @param  {Number} key
+ * @return {Object}
+ */
+TupleDictionary.prototype.getByKey = function(key) {
+    key = key|0;
+    return this.data[key];
+};
+
+/**
+ * @method get
+ * @param  {Number} i
+ * @param  {Number} j
+ * @return {Number}
+ */
+TupleDictionary.prototype.get = function(i, j) {
+    return this.data[this.getKey(i, j)];
+};
+
+/**
+ * Set a value.
+ * @method set
+ * @param  {Number} i
+ * @param  {Number} j
+ * @param {Number} value
+ */
+TupleDictionary.prototype.set = function(i, j, value) {
+    if(!value){
+        throw new Error("No data!");
+    }
+
+    var key = this.getKey(i, j);
+
+    // Check if key already exists
+    if(!this.data[key]){
+        this.keys.push(key);
+    }
+
+    this.data[key] = value;
+
+    return key;
+};
+
+/**
+ * Remove all data.
+ * @method reset
+ */
+TupleDictionary.prototype.reset = function() {
+    var data = this.data,
+        keys = this.keys;
+
+    var l = keys.length;
+    while(l--) {
+        delete data[keys[l]];
+    }
+
+    keys.length = 0;
+};
+
+/**
+ * Copy another TupleDictionary. Note that all data in this dictionary will be removed.
+ * @method copy
+ * @param {TupleDictionary} dict The TupleDictionary to copy into this one.
+ */
+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":57}],57:[function(_dereq_,module,exports){
+/* global P2_ARRAY_TYPE */
+
+module.exports = Utils;
+
+/**
+ * Misc utility functions
+ * @class Utils
+ * @constructor
+ */
+function Utils(){}
+
+/**
+ * Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
+ * @method appendArray
+ * @static
+ * @param  {Array} a
+ * @param  {Array} b
+ */
+Utils.appendArray = function(a,b){
+    if (b.length < 150000) {
+        a.push.apply(a, b);
+    } else {
+        for (var i = 0, len = b.length; i !== len; ++i) {
+            a.push(b[i]);
+        }
+    }
+};
+
+/**
+ * Garbage free Array.splice(). Does not allocate a new array.
+ * @method splice
+ * @static
+ * @param  {Array} array
+ * @param  {Number} index
+ * @param  {Number} howmany
+ */
+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;
+};
+
+/**
+ * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
+ * @static
+ * @property {function} ARRAY_TYPE
+ * @example
+ *     <script>
+ *         <!-- Inject your preferred array type before loading p2.js -->
+ *         P2_ARRAY_TYPE = Array;
+ *     </script>
+ *     <script src="p2.js"></script>
+ */
+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;
+}
+
+/**
+ * Extend an object with the properties of another
+ * @static
+ * @method extend
+ * @param  {object} a
+ * @param  {object} b
+ */
+Utils.extend = function(a,b){
+    for(var key in b){
+        a[key] = b[key];
+    }
+};
+
+/**
+ * Extend an options object with default values.
+ * @static
+ * @method defaults
+ * @param  {object} options The options object. May be falsy: in this case, a new object is created and returned.
+ * @param  {object} defaults An object containing default values.
+ * @return {object} The modified options object.
+ */
+Utils.defaults = function(options, defaults){
+    options = options || {};
+    for(var key in defaults){
+        if(!(key in options)){
+            options[key] = defaults[key];
+        }
+    }
+    return options;
+};
+
+},{}],58:[function(_dereq_,module,exports){
+var Body = _dereq_('../objects/Body');
+
+module.exports = Island;
+
+/**
+ * An island of bodies connected with equations.
+ * @class Island
+ * @constructor
+ */
+function Island(){
+
+    /**
+     * Current equations in this island.
+     * @property equations
+     * @type {Array}
+     */
+    this.equations = [];
+
+    /**
+     * Current bodies in this island.
+     * @property bodies
+     * @type {Array}
+     */
+    this.bodies = [];
+}
+
+/**
+ * Clean this island from bodies and equations.
+ * @method reset
+ */
+Island.prototype.reset = function(){
+    this.equations.length = this.bodies.length = 0;
+};
+
+var bodyIds = [];
+
+/**
+ * Get all unique bodies in this island.
+ * @method getBodies
+ * @return {Array} An array of Body
+ */
+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;
+};
+
+/**
+ * Check if the entire island wants to sleep.
+ * @method wantsToSleep
+ * @return {Boolean}
+ */
+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;
+};
+
+/**
+ * Make all bodies in the island sleep.
+ * @method sleep
+ */
+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}],59:[function(_dereq_,module,exports){
+var vec2 = _dereq_('../math/vec2')
+,   Island = _dereq_('./Island')
+,   IslandNode = _dereq_('./IslandNode')
+,   IslandNodePool = _dereq_('./../utils/IslandNodePool')
+,   IslandPool = _dereq_('./../utils/IslandPool')
+,   Body = _dereq_('../objects/Body');
+
+module.exports = IslandManager;
+
+/**
+ * Splits the system of bodies and equations into independent islands
+ *
+ * @class IslandManager
+ * @constructor
+ * @param {Object} [options]
+ * @extends Solver
+ */
+function IslandManager(options){
+
+    /**
+     * @property nodePool
+     * @type {IslandNodePool}
+     */
+    this.nodePool = new IslandNodePool({ size: 16 });
+
+    /**
+     * @property islandPool
+     * @type {IslandPool}
+     */
+    this.islandPool = new IslandPool({ size: 8 });
+
+    /**
+     * The equations to split. Manually fill this array before running .split().
+     * @property {Array} equations
+     */
+    this.equations = [];
+
+    /**
+     * The resulting {{#crossLink "Island"}}{{/crossLink}}s.
+     * @property {Array} islands
+     */
+    this.islands = [];
+
+    /**
+     * The resulting graph nodes.
+     * @property {Array} nodes
+     */
+    this.nodes = [];
+
+    /**
+     * The node queue, used when traversing the graph of nodes.
+     * @private
+     * @property {Array} queue
+     */
+    this.queue = [];
+}
+
+/**
+ * Get an unvisited node from a list of nodes.
+ * @static
+ * @method getUnvisitedNode
+ * @param  {Array} nodes
+ * @return {IslandNode|boolean} The node if found, else false.
+ */
+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;
+};
+
+/**
+ * Visit a node.
+ * @method visit
+ * @param  {IslandNode} node
+ * @param  {Array} bds
+ * @param  {Array} eqs
+ */
+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){ // Already added?
+            eqs.push(eq);
+        }
+    }
+};
+
+/**
+ * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays.
+ * @method bfs
+ * @param  {IslandNode} root The node to start from
+ * @param  {Array} bds  An array to append resulting Bodies to.
+ * @param  {Array} eqs  An array to append resulting Equations to.
+ */
+IslandManager.prototype.bfs = function(root,bds,eqs){
+
+    // Reset the visit queue
+    var queue = this.queue;
+    queue.length = 0;
+
+    // Add root node to queue
+    queue.push(root);
+    root.visited = true;
+    this.visit(root,bds,eqs);
+
+    // Process all queued nodes
+    while(queue.length) {
+
+        // Get next node in the queue
+        var node = queue.pop();
+
+        // Visit unvisited neighboring nodes
+        var child;
+        while((child = IslandManager.getUnvisitedNode(node.neighbors))) {
+            child.visited = true;
+            this.visit(child,bds,eqs);
+
+            // Only visit the children of this node if it's dynamic
+            if(child.body.type === Body.DYNAMIC){
+                queue.push(child);
+            }
+        }
+    }
+};
+
+/**
+ * Split the world into independent islands. The result is stored in .islands.
+ * @method split
+ * @param  {World} world
+ * @return {Array} The generated islands
+ */
+IslandManager.prototype.split = function(world){
+    var bodies = world.bodies,
+        nodes = this.nodes,
+        equations = this.equations;
+
+    // Move old nodes to the node pool
+    while(nodes.length){
+        this.nodePool.release(nodes.pop());
+    }
+
+    // Create needed nodes, reuse if possible
+    for(var i=0; i!==bodies.length; i++){
+        var node = this.nodePool.get();
+        node.body = bodies[i];
+        nodes.push(node);
+        // if(this.nodePool.length){
+        //     var node = this.nodePool.pop();
+        //     node.reset();
+        //     node.body = bodies[i];
+        //     nodes.push(node);
+        // } else {
+        //     nodes.push(new IslandNode(bodies[i]));
+        // }
+    }
+
+    // Add connectivity data. Each equation connects 2 bodies.
+    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);
+    }
+
+    // Move old islands to the island pool
+    var islands = this.islands;
+    for(var i=0; i<islands.length; i++){
+        this.islandPool.release(islands[i]);
+    }
+    islands.length = 0;
+
+    // Get islands
+    var child;
+    while((child = IslandManager.getUnvisitedNode(nodes))){
+
+        // Create new island
+        var island = this.islandPool.get();
+
+        // Get all equations and bodies in this island
+        this.bfs(child, island.bodies, island.equations);
+
+        islands.push(island);
+    }
+
+    return islands;
+};
+
+},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(_dereq_,module,exports){
+module.exports = IslandNode;
+
+/**
+ * Holds a body and keeps track of some additional properties needed for graph traversal.
+ * @class IslandNode
+ * @constructor
+ * @param {Body} body
+ */
+function IslandNode(body){
+
+	/**
+	 * The body that is contained in this node.
+	 * @property {Body} body
+	 */
+    this.body = body;
+
+    /**
+     * Neighboring IslandNodes
+     * @property {Array} neighbors
+     */
+    this.neighbors = [];
+
+    /**
+     * Equations connected to this node.
+     * @property {Array} equations
+     */
+    this.equations = [];
+
+    /**
+     * If this node was visiting during the graph traversal.
+     * @property visited
+     * @type {Boolean}
+     */
+    this.visited = false;
+}
+
+/**
+ * Clean this node from bodies and equations.
+ * @method reset
+ */
+IslandNode.prototype.reset = function(){
+    this.equations.length = 0;
+    this.neighbors.length = 0;
+    this.visited = false;
+    this.body = null;
+};
+
+},{}],61:[function(_dereq_,module,exports){
+var  GSSolver = _dereq_('../solver/GSSolver')
+,    Solver = _dereq_('../solver/Solver')
+,    Ray = _dereq_('../collision/Ray')
+,    vec2 = _dereq_('../math/vec2')
+,    Circle = _dereq_('../shapes/Circle')
+,    Convex = _dereq_('../shapes/Convex')
+,    Line = _dereq_('../shapes/Line')
+,    Plane = _dereq_('../shapes/Plane')
+,    Capsule = _dereq_('../shapes/Capsule')
+,    Particle = _dereq_('../shapes/Particle')
+,    EventEmitter = _dereq_('../events/EventEmitter')
+,    Body = _dereq_('../objects/Body')
+,    Shape = _dereq_('../shapes/Shape')
+,    LinearSpring = _dereq_('../objects/LinearSpring')
+,    Material = _dereq_('../material/Material')
+,    ContactMaterial = _dereq_('../material/ContactMaterial')
+,    DistanceConstraint = _dereq_('../constraints/DistanceConstraint')
+,    Constraint = _dereq_('../constraints/Constraint')
+,    LockConstraint = _dereq_('../constraints/LockConstraint')
+,    RevoluteConstraint = _dereq_('../constraints/RevoluteConstraint')
+,    PrismaticConstraint = _dereq_('../constraints/PrismaticConstraint')
+,    GearConstraint = _dereq_('../constraints/GearConstraint')
+,    pkg = _dereq_('../../package.json')
+,    Broadphase = _dereq_('../collision/Broadphase')
+,    AABB = _dereq_('../collision/AABB')
+,    SAPBroadphase = _dereq_('../collision/SAPBroadphase')
+,    Narrowphase = _dereq_('../collision/Narrowphase')
+,    Utils = _dereq_('../utils/Utils')
+,    OverlapKeeper = _dereq_('../utils/OverlapKeeper')
+,    IslandManager = _dereq_('./IslandManager')
+,    RotationalSpring = _dereq_('../objects/RotationalSpring');
+
+module.exports = World;
+
+/**
+ * The dynamics world, where all bodies and constraints live.
+ *
+ * @class World
+ * @constructor
+ * @param {Object} [options]
+ * @param {Solver} [options.solver] Defaults to GSSolver.
+ * @param {Array} [options.gravity] Defaults to y=-9.78.
+ * @param {Broadphase} [options.broadphase] Defaults to SAPBroadphase
+ * @param {Boolean} [options.islandSplit=true]
+ * @extends EventEmitter
+ *
+ * @example
+ *     var world = new World({
+ *         gravity: [0, -10],
+ *         broadphase: new SAPBroadphase()
+ *     });
+ *     world.addBody(new Body());
+ */
+function World(options){
+    EventEmitter.apply(this);
+
+    options = options || {};
+
+    /**
+     * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}.
+     *
+     * @property springs
+     * @type {Array}
+     */
+    this.springs = [];
+
+    /**
+     * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}.
+     * @property {Array} bodies
+     */
+    this.bodies = [];
+
+    /**
+     * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}.
+     * @private
+     * @property {Array} disabledBodyCollisionPairs
+     */
+    this.disabledBodyCollisionPairs = [];
+
+    /**
+     * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}.
+     * @property {Solver} solver
+     */
+    this.solver = options.solver || new GSSolver();
+
+    /**
+     * The narrowphase to use to generate contacts.
+     *
+     * @property narrowphase
+     * @type {Narrowphase}
+     */
+    this.narrowphase = new Narrowphase(this);
+
+    /**
+     * The island manager of this world.
+     * @property {IslandManager} islandManager
+     */
+    this.islandManager = new IslandManager();
+
+    /**
+     * Gravity in the world. This is applied on all bodies in the beginning of each step().
+     *
+     * @property gravity
+     * @type {Array}
+     */
+    this.gravity = vec2.fromValues(0, -9.78);
+    if(options.gravity){
+        vec2.copy(this.gravity, options.gravity);
+    }
+
+    /**
+     * Gravity to use when approximating the friction max force (mu*mass*gravity).
+     * @property {Number} frictionGravity
+     */
+    this.frictionGravity = vec2.length(this.gravity) || 10;
+
+    /**
+     * Set to true if you want .frictionGravity to be automatically set to the length of .gravity.
+     * @property {Boolean} useWorldGravityAsFrictionGravity
+     * @default true
+     */
+    this.useWorldGravityAsFrictionGravity = true;
+
+    /**
+     * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games.
+     * @property {Boolean} useFrictionGravityOnZeroGravity
+     * @default true
+     */
+    this.useFrictionGravityOnZeroGravity = true;
+
+    /**
+     * The broadphase algorithm to use.
+     *
+     * @property broadphase
+     * @type {Broadphase}
+     */
+    this.broadphase = options.broadphase || new SAPBroadphase();
+    this.broadphase.setWorld(this);
+
+    /**
+     * User-added constraints.
+     *
+     * @property constraints
+     * @type {Array}
+     */
+    this.constraints = [];
+
+    /**
+     * Dummy default material in the world, used in .defaultContactMaterial
+     * @property {Material} defaultMaterial
+     */
+    this.defaultMaterial = new Material();
+
+    /**
+     * The default contact material to use, if no contact material was set for the colliding materials.
+     * @property {ContactMaterial} defaultContactMaterial
+     */
+    this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial);
+
+    /**
+     * For keeping track of what time step size we used last step
+     * @property lastTimeStep
+     * @type {Number}
+     */
+    this.lastTimeStep = 1/60;
+
+    /**
+     * Enable to automatically apply spring forces each step.
+     * @property applySpringForces
+     * @type {Boolean}
+     * @default true
+     */
+    this.applySpringForces = true;
+
+    /**
+     * Enable to automatically apply body damping each step.
+     * @property applyDamping
+     * @type {Boolean}
+     * @default true
+     */
+    this.applyDamping = true;
+
+    /**
+     * Enable to automatically apply gravity each step.
+     * @property applyGravity
+     * @type {Boolean}
+     * @default true
+     */
+    this.applyGravity = true;
+
+    /**
+     * Enable/disable constraint solving in each step.
+     * @property solveConstraints
+     * @type {Boolean}
+     * @default true
+     */
+    this.solveConstraints = true;
+
+    /**
+     * The ContactMaterials added to the World.
+     * @property contactMaterials
+     * @type {Array}
+     */
+    this.contactMaterials = [];
+
+    /**
+     * World time.
+     * @property time
+     * @type {Number}
+     */
+    this.time = 0.0;
+    this.accumulator = 0;
+
+    /**
+     * Is true during step().
+     * @property {Boolean} stepping
+     */
+    this.stepping = false;
+
+    /**
+     * Bodies that are scheduled to be removed at the end of the step.
+     * @property {Array} bodiesToBeRemoved
+     * @private
+     */
+    this.bodiesToBeRemoved = [];
+
+    /**
+     * Whether to enable island splitting. Island splitting can be an advantage for both precision and performance. See {{#crossLink "IslandManager"}}{{/crossLink}}.
+     * @property {Boolean} islandSplit
+     * @default true
+     */
+    this.islandSplit = typeof(options.islandSplit)!=="undefined" ? !!options.islandSplit : true;
+
+    /**
+     * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
+     * @property emitImpactEvent
+     * @type {Boolean}
+     * @default true
+     */
+    this.emitImpactEvent = true;
+
+    // Id counters
+    this._constraintIdCounter = 0;
+    this._bodyIdCounter = 0;
+
+    /**
+     * Fired after the step().
+     * @event postStep
+     */
+    this.postStepEvent = {
+        type : "postStep"
+    };
+
+    /**
+     * Fired when a body is added to the world.
+     * @event addBody
+     * @param {Body} body
+     */
+    this.addBodyEvent = {
+        type : "addBody",
+        body : null
+    };
+
+    /**
+     * Fired when a body is removed from the world.
+     * @event removeBody
+     * @param {Body} body
+     */
+    this.removeBodyEvent = {
+        type : "removeBody",
+        body : null
+    };
+
+    /**
+     * Fired when a spring is added to the world.
+     * @event addSpring
+     * @param {Spring} spring
+     */
+    this.addSpringEvent = {
+        type : "addSpring",
+        spring : null
+    };
+
+    /**
+     * Fired when a first contact is created between two bodies. This event is fired after the step has been done.
+     * @event impact
+     * @param {Body} bodyA
+     * @param {Body} bodyB
+     */
+    this.impactEvent = {
+        type: "impact",
+        bodyA : null,
+        bodyB : null,
+        shapeA : null,
+        shapeB : null,
+        contactEquation : null
+    };
+
+    /**
+     * Fired after the Broadphase has collected collision pairs in the world.
+     * Inside the event handler, you can modify the pairs array as you like, to
+     * prevent collisions between objects that you don't want.
+     * @event postBroadphase
+     * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase.
+     */
+    this.postBroadphaseEvent = {
+        type: "postBroadphase",
+        pairs: null
+    };
+
+    /**
+     * How to deactivate bodies during simulation. Possible modes are: {{#crossLink "World/NO_SLEEPING:property"}}World.NO_SLEEPING{{/crossLink}}, {{#crossLink "World/BODY_SLEEPING:property"}}World.BODY_SLEEPING{{/crossLink}} and {{#crossLink "World/ISLAND_SLEEPING:property"}}World.ISLAND_SLEEPING{{/crossLink}}.
+     * If sleeping is enabled, you might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}.
+     * @property sleepMode
+     * @type {number}
+     * @default World.NO_SLEEPING
+     */
+    this.sleepMode = World.NO_SLEEPING;
+
+    /**
+     * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step.
+     * @event beginContact
+     * @param {Shape} shapeA
+     * @param {Shape} shapeB
+     * @param {Body}  bodyA
+     * @param {Body}  bodyB
+     * @param {Array} contactEquations
+     */
+    this.beginContactEvent = {
+        type: "beginContact",
+        shapeA: null,
+        shapeB: null,
+        bodyA: null,
+        bodyB: null,
+        contactEquations: []
+    };
+
+    /**
+     * Fired when two shapes stop overlapping, after the narrowphase (during step).
+     * @event endContact
+     * @param {Shape} shapeA
+     * @param {Shape} shapeB
+     * @param {Body}  bodyA
+     * @param {Body}  bodyB
+     */
+    this.endContactEvent = {
+        type: "endContact",
+        shapeA: null,
+        shapeB: null,
+        bodyA: null,
+        bodyB: null
+    };
+
+    /**
+     * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver.
+     * @event preSolve
+     * @param {Array} contactEquations  An array of contacts to be solved.
+     * @param {Array} frictionEquations An array of friction equations to be solved.
+     */
+    this.preSolveEvent = {
+        type: "preSolve",
+        contactEquations: null,
+        frictionEquations: null
+    };
+
+    // For keeping track of overlapping shapes
+    this.overlappingShapesLastState = { keys:[] };
+    this.overlappingShapesCurrentState = { keys:[] };
+
+    /**
+     * @property {OverlapKeeper} overlapKeeper
+     */
+    this.overlapKeeper = new OverlapKeeper();
+}
+World.prototype = new Object(EventEmitter.prototype);
+World.prototype.constructor = World;
+
+/**
+ * Never deactivate bodies.
+ * @static
+ * @property {number} NO_SLEEPING
+ */
+World.NO_SLEEPING = 1;
+
+/**
+ * Deactivate individual bodies if they are sleepy.
+ * @static
+ * @property {number} BODY_SLEEPING
+ */
+World.BODY_SLEEPING = 2;
+
+/**
+ * Deactivates bodies that are in contact, if all of them are sleepy. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work.
+ * @static
+ * @property {number} ISLAND_SLEEPING
+ */
+World.ISLAND_SLEEPING = 4;
+
+/**
+ * Add a constraint to the simulation.
+ *
+ * @method addConstraint
+ * @param {Constraint} constraint
+ * @example
+ *     var constraint = new LockConstraint(bodyA, bodyB);
+ *     world.addConstraint(constraint);
+ */
+World.prototype.addConstraint = function(constraint){
+    this.constraints.push(constraint);
+};
+
+/**
+ * Add a ContactMaterial to the simulation.
+ * @method addContactMaterial
+ * @param {ContactMaterial} contactMaterial
+ */
+World.prototype.addContactMaterial = function(contactMaterial){
+    this.contactMaterials.push(contactMaterial);
+};
+
+/**
+ * Removes a contact material
+ *
+ * @method removeContactMaterial
+ * @param {ContactMaterial} cm
+ */
+World.prototype.removeContactMaterial = function(cm){
+    var idx = this.contactMaterials.indexOf(cm);
+    if(idx!==-1){
+        Utils.splice(this.contactMaterials,idx,1);
+    }
+};
+
+/**
+ * Get a contact material given two materials
+ * @method getContactMaterial
+ * @param {Material} materialA
+ * @param {Material} materialB
+ * @return {ContactMaterial} The matching ContactMaterial, or false on fail.
+ * @todo Use faster hash map to lookup from material id's
+ */
+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;
+};
+
+/**
+ * Removes a constraint
+ *
+ * @method removeConstraint
+ * @param {Constraint} constraint
+ */
+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);
+
+/**
+ * Step the physics world forward in time.
+ *
+ * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
+ *
+ * @method step
+ * @param {Number} dt                       The fixed time step size to use.
+ * @param {Number} [timeSinceLastCalled=0]  The time elapsed since the function was last called.
+ * @param {Number} [maxSubSteps=10]         Maximum number of fixed steps to take per function call.
+ *
+ * @example
+ *     // Simple fixed timestepping without interpolation
+ *     var fixedTimeStep = 1 / 60;
+ *     var world = new World();
+ *     var body = new Body({ mass: 1 });
+ *     world.addBody(body);
+ *
+ *     function animate(){
+ *         requestAnimationFrame(animate);
+ *         world.step(fixedTimeStep);
+ *         renderBody(body.position, body.angle);
+ *     }
+ *
+ *     // Start animation loop
+ *     requestAnimationFrame(animate);
+ *
+ * @example
+ *     // Fixed timestepping with interpolation
+ *     var maxSubSteps = 10;
+ *     var lastTimeSeconds;
+ *
+ *     function animate(t){
+ *         requestAnimationFrame(animate);
+ *         timeSeconds = t / 1000;
+ *         lastTimeSeconds = lastTimeSeconds || timeSeconds;
+ *
+ *         deltaTime = timeSeconds - lastTimeSeconds;
+ *         world.step(fixedTimeStep, deltaTime, maxSubSteps);
+ *
+ *         renderBody(body.interpolatedPosition, body.interpolatedAngle);
+ *     }
+ *
+ *     // Start animation loop
+ *     requestAnimationFrame(animate);
+ *
+ * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
+ */
+World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){
+    maxSubSteps = maxSubSteps || 10;
+    timeSinceLastCalled = timeSinceLastCalled || 0;
+
+    if(timeSinceLastCalled === 0){ // Fixed, simple stepping
+
+        this.internalStep(dt);
+
+        // Increment time
+        this.time += dt;
+
+    } else {
+
+        this.accumulator += timeSinceLastCalled;
+        var substeps = 0;
+        while (this.accumulator >= dt && substeps < maxSubSteps) {
+            // Do fixed steps to catch up
+            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 = [];
+
+/**
+ * Make a fixed step.
+ * @method internalStep
+ * @param  {number} dt
+ * @private
+ */
+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;
+
+    // Update approximate friction gravity.
+    if(this.useWorldGravityAsFrictionGravity){
+        var gravityLen = vec2.length(this.gravity);
+        if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){
+            // Nonzero gravity. Use it.
+            this.frictionGravity = gravityLen;
+        }
+    }
+
+    // Add gravity to bodies
+    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); // F=m*g
+            add(fi,fi,mg);
+        }
+    }
+
+    // Add spring forces
+    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);
+            }
+        }
+    }
+
+    // Broadphase
+    var result = broadphase.getCollisionPairs(this);
+
+    // Remove ignored collision pairs
+    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);
+            }
+        }
+    }
+
+    // Remove constrained pairs with collideConnected == false
+    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);
+                }
+            }
+        }
+    }
+
+    // postBroadphase event
+    this.postBroadphaseEvent.pairs = result;
+    this.emit(this.postBroadphaseEvent);
+    this.postBroadphaseEvent.pairs = null;
+
+    // Narrowphase
+    np.reset(this);
+    for(var i=0, Nresults=result.length; i!==Nresults; i+=2){
+        var bi = result[i],
+            bj = result[i+1];
+
+        // Loop over all shapes of body i
+        for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){
+            var si = bi.shapes[k],
+                xi = si.position,
+                ai = si.angle;
+
+            // All shapes of body j
+            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);
+            }
+        }
+    }
+
+    // Wake up bodies
+    for(var i=0; i!==Nbodies; i++){
+        var body = bodies[i];
+        if(body._wakeUpAfterNarrowphase){
+            body.wakeUp();
+            body._wakeUpAfterNarrowphase = false;
+        }
+    }
+
+    // Emit end overlap events
+    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;
+
+    // update constraint equations
+    var Nconstraints = constraints.length;
+    for(i=0; i!==Nconstraints; i++){
+        constraints[i].update();
+    }
+
+    if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){
+        if(this.islandSplit){
+            // Split into islands
+            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 {
+
+            // Add contact equations to solver
+            solver.addEquations(np.contactEquations);
+            solver.addEquations(np.frictionEquations);
+
+            // Add user-defined constraint equations
+            for(i=0; i!==Nconstraints; i++){
+                solver.addEquations(constraints[i].equations);
+            }
+
+            if(this.solveConstraints){
+                solver.solve(dt,this);
+            }
+
+            solver.removeAllEquations();
+        }
+    }
+
+    // Step forward
+    for(var i=0; i!==Nbodies; i++){
+        var body = bodies[i];
+
+        // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){
+        body.integrate(dt);
+        // }
+    }
+
+    // Reset force
+    for(var i=0; i!==Nbodies; i++){
+        bodies[i].setZeroForce();
+    }
+
+    // Emit impact event
+    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);
+            }
+        }
+    }
+
+    // Sleeping update
+    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){
+
+        // Tell all bodies to sleep tick but dont sleep yet
+        for(i=0; i!==Nbodies; i++){
+            bodies[i].sleepTick(this.time, true, dt);
+        }
+
+        // Sleep islands
+        for(var i=0; i<this.islandManager.islands.length; i++){
+            var island = this.islandManager.islands[i];
+            if(island.wantsToSleep()){
+                island.sleep();
+            }
+        }
+    }
+
+    this.stepping = false;
+
+    // Remove bodies that are scheduled for removal
+    var bodiesToBeRemoved = this.bodiesToBeRemoved;
+    for(var i=0; i!==bodiesToBeRemoved.length; i++){
+        this.removeBody(bodiesToBeRemoved[i]);
+    }
+    bodiesToBeRemoved.length = 0;
+
+    this.emit(this.postStepEvent);
+};
+
+/**
+ * Runs narrowphase for the shape pair i and j.
+ * @method runNarrowphase
+ * @param  {Narrowphase} np
+ * @param  {Body} bi
+ * @param  {Shape} si
+ * @param  {Array} xi
+ * @param  {Number} ai
+ * @param  {Body} bj
+ * @param  {Shape} sj
+ * @param  {Array} xj
+ * @param  {Number} aj
+ * @param  {Number} mu
+ */
+World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){
+
+    // Check collision groups and masks
+    if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)){
+        return;
+    }
+
+    // Get world position and angle of each shape
+    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)){
+
+                // Report new shape overlap
+                var e = this.beginContactEvent;
+                e.shapeA = si;
+                e.shapeB = sj;
+                e.bodyA = bi;
+                e.bodyB = bj;
+
+                // Reset contact equations
+                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);
+            }
+
+            // divide the max friction force by the number of contacts
+            if(typeof(numContacts)==="number" && numFrictionEquations > 1){ // Why divide by 1?
+                for(var i=np.frictionEquations.length-numFrictionEquations; i<np.frictionEquations.length; i++){
+                    var f = np.frictionEquations[i];
+                    f.setSlipForce(f.getSlipForce() / numFrictionEquations);
+                }
+            }
+        }
+    }
+
+};
+
+/**
+ * Add a spring to the simulation
+ *
+ * @method addSpring
+ * @param {Spring} spring
+ */
+World.prototype.addSpring = function(spring){
+    this.springs.push(spring);
+    var evt = this.addSpringEvent;
+    evt.spring = spring;
+    this.emit(evt);
+    evt.spring = null;
+};
+
+/**
+ * Remove a spring
+ *
+ * @method removeSpring
+ * @param {Spring} spring
+ */
+World.prototype.removeSpring = function(spring){
+    var idx = this.springs.indexOf(spring);
+    if(idx !== -1){
+        Utils.splice(this.springs,idx,1);
+    }
+};
+
+/**
+ * Add a body to the simulation
+ *
+ * @method addBody
+ * @param {Body} body
+ *
+ * @example
+ *     var world = new World(),
+ *         body = new Body();
+ *     world.addBody(body);
+ * @todo What if this is done during step?
+ */
+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;
+    }
+};
+
+/**
+ * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step.
+ *
+ * @method removeBody
+ * @param {Body} body
+ */
+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;
+        }
+    }
+};
+
+/**
+ * Get a body by its id.
+ * @method getBodyById
+ * @param {number} id
+ * @return {Body} The body, or false if it was not found.
+ */
+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;
+};
+
+/**
+ * Disable collision between two bodies
+ * @method disableBodyCollision
+ * @param {Body} bodyA
+ * @param {Body} bodyB
+ */
+World.prototype.disableBodyCollision = function(bodyA,bodyB){
+    this.disabledBodyCollisionPairs.push(bodyA,bodyB);
+};
+
+/**
+ * Enable collisions between the given two bodies
+ * @method enableBodyCollision
+ * @param {Body} bodyA
+ * @param {Body} 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;
+        }
+    }
+};
+
+/**
+ * Resets the World, removes all bodies, constraints and springs.
+ *
+ * @method clear
+ */
+World.prototype.clear = function(){
+
+    this.time = 0;
+
+    // Remove all solver equations
+    if(this.solver && this.solver.equations.length){
+        this.solver.removeAllEquations();
+    }
+
+    // Remove all constraints
+    var cs = this.constraints;
+    for(var i=cs.length-1; i>=0; i--){
+        this.removeConstraint(cs[i]);
+    }
+
+    // Remove all bodies
+    var bodies = this.bodies;
+    for(var i=bodies.length-1; i>=0; i--){
+        this.removeBody(bodies[i]);
+    }
+
+    // Remove all springs
+    var springs = this.springs;
+    for(var i=springs.length-1; i>=0; i--){
+        this.removeSpring(springs[i]);
+    }
+
+    // Remove all contact materials
+    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);
+
+/**
+ * Test if a world point overlaps bodies
+ * @method hitTest
+ * @param  {Array}  worldPoint  Point to use for intersection tests
+ * @param  {Array}  bodies      A list of objects to check for intersection
+ * @param  {Number} precision   Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
+ * @return {Array}              Array of bodies that overlap the point
+ * @todo Should use an api similar to the raycast function
+ * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient
+ */
+World.prototype.hitTest = function(worldPoint,bodies,precision){
+    precision = precision || 0;
+
+    // Create a dummy particle body with a particle shape to test against the bodies
+    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 = [];
+
+    // Check bodies
+    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];
+
+            // Get shape world position + angle
+            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;
+};
+
+/**
+ * Set the stiffness for all equations and contact materials.
+ * @method setGlobalStiffness
+ * @param {Number} stiffness
+ */
+World.prototype.setGlobalStiffness = function(stiffness){
+
+    // Set for all constraints
+    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;
+        }
+    }
+
+    // Set for all contact materials
+    var contactMaterials = this.contactMaterials;
+    for(var i=0; i !== contactMaterials.length; i++){
+        var c = contactMaterials[i];
+        c.stiffness = c.frictionStiffness = stiffness;
+    }
+
+    // Set for default contact material
+    var c = this.defaultContactMaterial;
+    c.stiffness = c.frictionStiffness = stiffness;
+};
+
+/**
+ * Set the relaxation for all equations and contact materials.
+ * @method setGlobalRelaxation
+ * @param {Number} relaxation
+ */
+World.prototype.setGlobalRelaxation = function(relaxation){
+
+    // Set for all constraints
+    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;
+        }
+    }
+
+    // Set for all contact materials
+    for(var i=0; i !== this.contactMaterials.length; i++){
+        var c = this.contactMaterials[i];
+        c.relaxation = c.frictionRelaxation = relaxation;
+    }
+
+    // Set for default contact material
+    var c = this.defaultContactMaterial;
+    c.relaxation = c.frictionRelaxation = relaxation;
+};
+
+var tmpAABB = new AABB();
+var tmpArray = [];
+
+/**
+ * Ray cast against all bodies in the world.
+ * @method raycast
+ * @param  {RaycastResult} result
+ * @param  {Ray} ray
+ * @return {boolean} True if any body was hit.
+ *
+ * @example
+ *     var ray = new Ray({
+ *         mode: Ray.CLOSEST, // or ANY
+ *         from: [0, 0],
+ *         to: [10, 0],
+ *     });
+ *     var result = new RaycastResult();
+ *     world.raycast(result, ray);
+ *
+ *     // Get the hit point
+ *     var hitPoint = vec2.create();
+ *     result.getHitPoint(hitPoint, ray);
+ *     console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
+ *
+ * @example
+ *     var ray = new Ray({
+ *         mode: Ray.ALL,
+ *         from: [0, 0],
+ *         to: [10, 0],
+ *         callback: function(result){
+ *
+ *             // Print some info about the hit
+ *             console.log('Hit body and shape: ', result.body, result.shape);
+ *
+ *             // Get the hit point
+ *             var hitPoint = vec2.create();
+ *             result.getHitPoint(hitPoint, ray);
+ *             console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
+ *
+ *             // If you are happy with the hits you got this far, you can stop the traversal here:
+ *             result.stop();
+ *         }
+ *     });
+ *     var result = new RaycastResult();
+ *     world.raycast(result, ray);
+ */
+World.prototype.raycast = function(result, ray){
+
+    // Get all bodies within the ray AABB
+    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":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])
+(36)
+});
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+(function(){
+
+    var root = this;
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * The [pixi.js](http://www.pixijs.com/) module/namespace.
+ *
+ * @module PIXI
+ */
+ 
+/**
+ * Namespace-class for [pixi.js](http://www.pixijs.com/).
+ *
+ * Contains assorted static properties and enumerations.
+ *
+ * @class PIXI
+ * @static
+ */
+var PIXI = PIXI || {};
+
+/**
+ * @property {Number} WEBGL_RENDERER
+ * @protected
+ * @static 
+ */
+PIXI.WEBGL_RENDERER = 0;
+
+/**
+ * @property {Number} CANVAS_RENDERER
+ * @protected
+ * @static
+ */
+PIXI.CANVAS_RENDERER = 1;
+
+/**
+ * Version of pixi that is loaded.
+ * @property {String} VERSION
+ * @static 
+ */
+PIXI.VERSION = "v2.2.8";
+
+// used to create uids for various pixi objects.
+PIXI._UID = 0;
+
+if (typeof(Float32Array) != 'undefined')
+{
+    PIXI.Float32Array = Float32Array;
+    PIXI.Uint16Array = Uint16Array;
+
+    // Uint32Array and ArrayBuffer only used by WebGL renderer
+    // We can suppose that if WebGL is supported then typed arrays are supported too
+    // as they predate WebGL support for all browsers:
+    // see typed arrays support: http://caniuse.com/#search=TypedArrays
+    // see WebGL support: http://caniuse.com/#search=WebGL
+    PIXI.Uint32Array = Uint32Array;
+    PIXI.ArrayBuffer = ArrayBuffer;
+}
+else
+{
+    PIXI.Float32Array = Array;
+    PIXI.Uint16Array = Array;
+}
+
+/**
+ * @property {Number} PI_2
+ * @static
+ */
+PIXI.PI_2 = Math.PI * 2;
+
+/**
+ * @property {Number} RAD_TO_DEG
+ * @static
+ */
+PIXI.RAD_TO_DEG = 180 / Math.PI;
+
+/**
+ * @property {Number} DEG_TO_RAD
+ * @static
+ */
+PIXI.DEG_TO_RAD = Math.PI / 180;
+
+/**
+ * @property {String} RETINA_PREFIX
+ * @protected
+ * @static
+ */
+PIXI.RETINA_PREFIX = "@2x";
+
+/**
+ * The default render options if none are supplied to
+ * {{#crossLink "WebGLRenderer"}}{{/crossLink}} or {{#crossLink "CanvasRenderer"}}{{/crossLink}}.
+ *
+ * @property {Object} defaultRenderOptions
+ * @property {Object} defaultRenderOptions.view=null
+ * @property {Boolean} defaultRenderOptions.transparent=false
+ * @property {Boolean} defaultRenderOptions.antialias=false
+ * @property {Boolean} defaultRenderOptions.preserveDrawingBuffer=false
+ * @property {Number} defaultRenderOptions.resolution=1
+ * @property {Boolean} defaultRenderOptions.clearBeforeRender=true
+ * @property {Boolean} defaultRenderOptions.autoResize=false
+ * @static
+ */
+PIXI.defaultRenderOptions = {
+    view: null,
+    transparent: false,
+    antialias: false, 
+    preserveDrawingBuffer: false,
+    resolution: 1,
+    clearBeforeRender: true,
+    autoResize: false
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * The base class for all objects that are rendered on the screen.
+ * This is an abstract class and should not be used on its own rather it should be extended.
+ *
+ * @class DisplayObject
+ * @constructor
+ */
+PIXI.DisplayObject = function()
+{
+    /**
+     * The coordinate of the object relative to the local coordinates of the parent.
+     *
+     * @property position
+     * @type Point
+     */
+    this.position = new PIXI.Point(0, 0);
+
+    /**
+     * The scale factor of the object.
+     *
+     * @property scale
+     * @type Point
+     */
+    this.scale = new PIXI.Point(1, 1);
+
+    /**
+     * The transform callback is an optional callback that if set will be called at the end of the updateTransform method and sent two parameters:
+     * This Display Objects worldTransform matrix and its parents transform matrix. Both are PIXI.Matrix object types.
+     * The matrix are passed by reference and can be modified directly without needing to return them.
+     * This ability allows you to check any of the matrix values and perform actions such as clamping scale or limiting rotation, regardless of the parent transforms.
+     * 
+     * @property transformCallback
+     * @type Function
+     */
+    this.transformCallback = null;
+
+    /**
+     * The context under which the transformCallback is invoked.
+     * 
+     * @property transformCallbackContext
+     * @type Object
+     */
+    this.transformCallbackContext = null;
+
+    /**
+     * The pivot point of the displayObject that it rotates around
+     *
+     * @property pivot
+     * @type Point
+     */
+    this.pivot = new PIXI.Point(0, 0);
+
+    /**
+     * The rotation of the object in radians.
+     *
+     * @property rotation
+     * @type Number
+     */
+    this.rotation = 0;
+
+    /**
+     * The opacity of the object.
+     *
+     * @property alpha
+     * @type Number
+     */
+    this.alpha = 1;
+
+    /**
+     * The visibility of the object.
+     *
+     * @property visible
+     * @type Boolean
+     */
+    this.visible = true;
+
+    /**
+     * This is the defined area that will pick up mouse / touch events. It is null by default.
+     * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
+     *
+     * @property hitArea
+     * @type Rectangle|Circle|Ellipse|Polygon
+     */
+    this.hitArea = null;
+
+    /**
+     * Can this object be rendered
+     *
+     * @property renderable
+     * @type Boolean
+     */
+    this.renderable = false;
+
+    /**
+     * [read-only] The display object container that contains this display object.
+     *
+     * @property parent
+     * @type DisplayObjectContainer
+     * @readOnly
+     */
+    this.parent = null;
+
+    /**
+     * [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
+     *
+     * @property stage
+     * @type Stage
+     * @readOnly
+     */
+    this.stage = null;
+
+    /**
+     * [read-only] The multiplied alpha of the displayObject
+     *
+     * @property worldAlpha
+     * @type Number
+     * @readOnly
+     */
+    this.worldAlpha = 1;
+
+    /**
+     * [read-only] Current transform of the object based on world (parent) factors
+     *
+     * @property worldTransform
+     * @type Matrix
+     * @readOnly
+     * @private
+     */
+    this.worldTransform = new PIXI.Matrix();
+
+    /**
+     * The position of the Display Object based on the world transform.
+     * This value is updated at the end of updateTransform and takes all parent transforms into account.
+     *
+     * @property worldPosition
+     * @type Point
+     * @readOnly
+     */
+    this.worldPosition = new PIXI.Point(0, 0);
+
+    /**
+     * The scale of the Display Object based on the world transform.
+     * This value is updated at the end of updateTransform and takes all parent transforms into account.
+     *
+     * @property worldScale
+     * @type Point
+     * @readOnly
+     */
+    this.worldScale = new PIXI.Point(1, 1);
+
+    /**
+     * The rotation of the Display Object, in radians, based on the world transform.
+     * This value is updated at the end of updateTransform and takes all parent transforms into account.
+     *
+     * @property worldRotation
+     * @type Number
+     * @readOnly
+     */
+    this.worldRotation = 0;
+
+    /**
+     * cached sin rotation and cos rotation
+     *
+     * @property _sr
+     * @type Number
+     * @private
+     */
+    this._sr = 0;
+
+    /**
+     * cached sin rotation and cos rotation
+     *
+     * @property _cr
+     * @type Number
+     * @private
+     */
+    this._cr = 1;
+
+    /**
+     * The area the filter is applied to like the hitArea this is used as more of an optimisation
+     * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle
+     *
+     * @property filterArea
+     * @type Rectangle
+     */
+    this.filterArea = null;
+
+    /**
+     * The original, cached bounds of the object
+     *
+     * @property _bounds
+     * @type Rectangle
+     * @private
+     */
+    this._bounds = new PIXI.Rectangle(0, 0, 1, 1);
+
+    /**
+     * The most up-to-date bounds of the object
+     *
+     * @property _currentBounds
+     * @type Rectangle
+     * @private
+     */
+    this._currentBounds = null;
+
+    /**
+     * The original, cached mask of the object
+     *
+     * @property _mask
+     * @type Rectangle
+     * @private
+     */
+    this._mask = null;
+
+    /**
+     * Cached internal flag.
+     *
+     * @property _cacheAsBitmap
+     * @type Boolean
+     * @private
+     */
+    this._cacheAsBitmap = false;
+
+    /**
+     * Cached internal flag.
+     *
+     * @property _cacheIsDirty
+     * @type Boolean
+     * @private
+     */
+    this._cacheIsDirty = false;
+
+};
+
+// constructor
+PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject;
+
+/**
+ * Destroy this DisplayObject.
+ * Removes all references to transformCallbacks, its parent, the stage, filters, bounds, mask and cached Sprites.
+ *
+ * @method destroy
+ */
+PIXI.DisplayObject.prototype.destroy = function()
+{
+    if (this.children)
+    {
+        var i = this.children.length;
+
+        while (i--)
+        {
+            this.children[i].destroy();
+        }
+
+        this.children = [];
+    }
+
+    this.transformCallback = null;
+    this.transformCallbackContext = null;
+    this.hitArea = null;
+    this.parent = null;
+    this.stage = null;
+    this.worldTransform = null;
+    this.filterArea = null;
+    this._bounds = null;
+    this._currentBounds = null;
+    this._mask = null;
+
+    //  In case Pixi is still going to try and render it even though destroyed
+    this.renderable = false;
+
+    this._destroyCachedSprite();
+};
+
+/**
+ * [read-only] Indicates if the sprite is globally visible.
+ *
+ * @property worldVisible
+ * @type Boolean
+ */
+Object.defineProperty(PIXI.DisplayObject.prototype, 'worldVisible', {
+
+    get: function() {
+
+        var item = this;
+
+        do
+        {
+            if (!item.visible) return false;
+            item = item.parent;
+        }
+        while(item);
+
+        return true;
+    }
+
+});
+
+/**
+ * Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it.
+ * In PIXI a regular mask must be a PIXI.Graphics object. This allows for much faster masking in canvas as it utilises shape clipping.
+ * To remove a mask, set this property to null.
+ *
+ * @property mask
+ * @type Graphics
+ */
+Object.defineProperty(PIXI.DisplayObject.prototype, 'mask', {
+
+    get: function() {
+        return this._mask;
+    },
+
+    set: function(value) {
+
+        if (this._mask) this._mask.isMask = false;
+
+        this._mask = value;
+
+        if (this._mask) this._mask.isMask = true;
+    }
+
+});
+
+/**
+ * Sets the filters for the displayObject.
+ * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer.
+ * To remove filters simply set this property to 'null'
+ * @property filters
+ * @type Array(Filter)
+ */
+Object.defineProperty(PIXI.DisplayObject.prototype, 'filters', {
+
+    get: function() {
+        return this._filters;
+    },
+
+    set: function(value) {
+
+        if (value)
+        {
+            // now put all the passes in one place..
+            var passes = [];
+
+            for (var i = 0; i < value.length; i++)
+            {
+                var filterPasses = value[i].passes;
+
+                for (var j = 0; j < filterPasses.length; j++)
+                {
+                    passes.push(filterPasses[j]);
+                }
+            }
+
+            // TODO change this as it is legacy
+            this._filterBlock = { target: this, filterPasses: passes };
+        }
+
+        this._filters = value;
+    }
+});
+
+/**
+ * Set if this display object is cached as a bitmap.
+ * This basically takes a snap shot of the display object as it is at that moment. It can provide a performance benefit for complex static displayObjects.
+ * To remove simply set this property to 'null'
+ * @property cacheAsBitmap
+ * @type Boolean
+ */
+Object.defineProperty(PIXI.DisplayObject.prototype, 'cacheAsBitmap', {
+
+    get: function() {
+        return  this._cacheAsBitmap;
+    },
+
+    set: function(value) {
+
+        if (this._cacheAsBitmap === value) return;
+
+        if (value)
+        {
+            this._generateCachedSprite();
+        }
+        else
+        {
+            this._destroyCachedSprite();
+        }
+
+        this._cacheAsBitmap = value;
+    }
+});
+
+/*
+ * Updates the object transform for rendering.
+ *
+ * If the object has no parent, and no parent parameter is provided, it will default to Phaser.Game.World as the parent.
+ * If that is unavailable the transform fails to take place.
+ *
+ * The `parent` parameter has priority over the actual parent. Use it as a parent override.
+ * Setting it does **not** change the actual parent of this DisplayObject, it just uses the parent for the transform update.
+ *
+ * @method updateTransform
+ * @param {DisplayObject} [parent] - Optional parent to parent this DisplayObject transform from.
+ */
+PIXI.DisplayObject.prototype.updateTransform = function(parent)
+{
+    if (!parent && !this.parent && !this.game)
+    {
+        return;
+    }
+
+    var p = this.parent;
+
+    if (parent)
+    {
+        p = parent;
+    }
+    else if (!this.parent)
+    {
+        p = this.game.world;
+    }
+
+    // create some matrix refs for easy access
+    var pt = p.worldTransform;
+    var wt = this.worldTransform;
+
+    // temporary matrix variables
+    var a, b, c, d, tx, ty;
+
+    // so if rotation is between 0 then we can simplify the multiplication process..
+    if (this.rotation % PIXI.PI_2)
+    {
+        // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes
+        if (this.rotation !== this.rotationCache)
+        {
+            this.rotationCache = this.rotation;
+            this._sr = Math.sin(this.rotation);
+            this._cr = Math.cos(this.rotation);
+        }
+
+        // get the matrix values of the displayobject based on its transform properties..
+        a  =  this._cr * this.scale.x;
+        b  =  this._sr * this.scale.x;
+        c  = -this._sr * this.scale.y;
+        d  =  this._cr * this.scale.y;
+        tx =  this.position.x;
+        ty =  this.position.y;
+        
+        // check for pivot.. not often used so geared towards that fact!
+        if (this.pivot.x || this.pivot.y)
+        {
+            tx -= this.pivot.x * a + this.pivot.y * c;
+            ty -= this.pivot.x * b + this.pivot.y * d;
+        }
+
+        // concat the parent matrix with the objects transform.
+        wt.a  = a  * pt.a + b  * pt.c;
+        wt.b  = a  * pt.b + b  * pt.d;
+        wt.c  = c  * pt.a + d  * pt.c;
+        wt.d  = c  * pt.b + d  * pt.d;
+        wt.tx = tx * pt.a + ty * pt.c + pt.tx;
+        wt.ty = tx * pt.b + ty * pt.d + pt.ty;
+    }
+    else
+    {
+        // lets do the fast version as we know there is no rotation..
+        a  = this.scale.x;
+        d  = this.scale.y;
+
+        tx = this.position.x - this.pivot.x * a;
+        ty = this.position.y - this.pivot.y * d;
+
+        wt.a  = a  * pt.a;
+        wt.b  = a  * pt.b;
+        wt.c  = d  * pt.c;
+        wt.d  = d  * pt.d;
+        wt.tx = tx * pt.a + ty * pt.c + pt.tx;
+        wt.ty = tx * pt.b + ty * pt.d + pt.ty;
+    }
+
+    // multiply the alphas..
+    this.worldAlpha = this.alpha * p.worldAlpha;
+
+    this.worldPosition.set(wt.tx, wt.ty);
+    this.worldScale.set(Math.sqrt(wt.a * wt.a + wt.b * wt.b), Math.sqrt(wt.c * wt.c + wt.d * wt.d));
+    this.worldRotation = Math.atan2(-wt.c, wt.d);
+
+    // reset the bounds each time this is called!
+    this._currentBounds = null;
+
+    //  Custom callback?
+    if (this.transformCallback)
+    {
+        this.transformCallback.call(this.transformCallbackContext, wt, pt);
+    }
+
+};
+
+// performance increase to avoid using call.. (10x faster)
+PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform;
+
+/**
+ * Retrieves the bounds of the displayObject as a rectangle object
+ *
+ * @method getBounds
+ * @param matrix {Matrix}
+ * @return {Rectangle} the rectangular bounding area
+ */
+PIXI.DisplayObject.prototype.getBounds = function(matrix)
+{
+    matrix = matrix;//just to get passed js hinting (and preserve inheritance)
+    return PIXI.EmptyRectangle;
+};
+
+/**
+ * Retrieves the local bounds of the displayObject as a rectangle object
+ *
+ * @method getLocalBounds
+ * @return {Rectangle} the rectangular bounding area
+ */
+PIXI.DisplayObject.prototype.getLocalBounds = function()
+{
+    return this.getBounds(PIXI.identityMatrix);///PIXI.EmptyRectangle();
+};
+
+/**
+ * Sets the object's stage reference, the stage this object is connected to
+ *
+ * @method setStageReference
+ * @param stage {Stage} the stage that the object will have as its current stage reference
+ */
+PIXI.DisplayObject.prototype.setStageReference = function(stage)
+{
+    this.stage = stage;
+};
+
+/**
+ * Empty, to be overridden by classes that require it.
+ *
+ * @method preUpdate
+ */
+PIXI.DisplayObject.prototype.preUpdate = function()
+{
+};
+
+/**
+ * Useful function that returns a texture of the displayObject object that can then be used to create sprites
+ * This can be quite useful if your displayObject is static / complicated and needs to be reused multiple times.
+ *
+ * @method generateTexture
+ * @param resolution {Number} The resolution of the texture being generated
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture.
+ * @return {Texture} a texture of the graphics object
+ */
+PIXI.DisplayObject.prototype.generateTexture = function(resolution, scaleMode, renderer)
+{
+    var bounds = this.getLocalBounds();
+
+    var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution);
+    
+    PIXI.DisplayObject._tempMatrix.tx = -bounds.x;
+    PIXI.DisplayObject._tempMatrix.ty = -bounds.y;
+    
+    renderTexture.render(this, PIXI.DisplayObject._tempMatrix);
+
+    return renderTexture;
+};
+
+/**
+ * Generates and updates the cached sprite for this object.
+ *
+ * @method updateCache
+ */
+PIXI.DisplayObject.prototype.updateCache = function()
+{
+    this._generateCachedSprite();
+};
+
+/**
+ * Calculates the global position of the display object
+ *
+ * @method toGlobal
+ * @param position {Point} The world origin to calculate from
+ * @return {Point} A point object representing the position of this object
+ */
+PIXI.DisplayObject.prototype.toGlobal = function(position)
+{
+    // don't need to u[date the lot
+    this.displayObjectUpdateTransform();
+    return this.worldTransform.apply(position);
+};
+
+/**
+ * Calculates the local position of the display object relative to another point
+ *
+ * @method toLocal
+ * @param position {Point} The world origin to calculate from
+ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from
+ * @return {Point} A point object representing the position of this object
+ */
+PIXI.DisplayObject.prototype.toLocal = function(position, from)
+{
+    if (from)
+    {
+        position = from.toGlobal(position);
+    }
+
+    // don't need to u[date the lot
+    this.displayObjectUpdateTransform();
+
+    return this.worldTransform.applyInverse(position);
+};
+
+/**
+ * Internal method.
+ *
+ * @method _renderCachedSprite
+ * @param renderSession {Object} The render session
+ * @private
+ */
+PIXI.DisplayObject.prototype._renderCachedSprite = function(renderSession)
+{
+    this._cachedSprite.worldAlpha = this.worldAlpha;
+
+    if (renderSession.gl)
+    {
+        PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
+    }
+    else
+    {
+        PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
+    }
+};
+
+/**
+ * Internal method.
+ *
+ * @method _generateCachedSprite
+ * @private
+ */
+PIXI.DisplayObject.prototype._generateCachedSprite = function()
+{
+    this._cacheAsBitmap = false;
+
+    var bounds = this.getLocalBounds();
+
+    if (!this._cachedSprite)
+    {
+        var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0);//, renderSession.renderer);
+
+        this._cachedSprite = new PIXI.Sprite(renderTexture);
+        this._cachedSprite.worldTransform = this.worldTransform;
+    }
+    else
+    {
+        this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0);
+    }
+
+    //REMOVE filter!
+    var tempFilters = this._filters;
+    this._filters = null;
+
+    this._cachedSprite.filters = tempFilters;
+
+    PIXI.DisplayObject._tempMatrix.tx = -bounds.x;
+    PIXI.DisplayObject._tempMatrix.ty = -bounds.y;
+    
+    this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true);
+
+    this._cachedSprite.anchor.x = -( bounds.x / bounds.width );
+    this._cachedSprite.anchor.y = -( bounds.y / bounds.height );
+
+    this._filters = tempFilters;
+
+    this._cacheAsBitmap = true;
+};
+
+/**
+* Destroys the cached sprite.
+*
+* @method _destroyCachedSprite
+* @private
+*/
+PIXI.DisplayObject.prototype._destroyCachedSprite = function()
+{
+    if (!this._cachedSprite) return;
+
+    this._cachedSprite.texture.destroy(true);
+
+    // TODO could be object pooled!
+    this._cachedSprite = null;
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method _renderWebGL
+* @param renderSession {RenderSession}
+* @private
+*/
+PIXI.DisplayObject.prototype._renderWebGL = function(renderSession)
+{
+    // OVERWRITE;
+    // this line is just here to pass jshinting :)
+    renderSession = renderSession;
+};
+
+/**
+* Renders the object using the Canvas renderer
+*
+* @method _renderCanvas
+* @param renderSession {RenderSession}
+* @private
+*/
+PIXI.DisplayObject.prototype._renderCanvas = function(renderSession)
+{
+    // OVERWRITE;
+    // this line is just here to pass jshinting :)
+    renderSession = renderSession;
+};
+
+/**
+ * The position of the displayObject on the x axis relative to the local coordinates of the parent.
+ *
+ * @property x
+ * @type Number
+ */
+Object.defineProperty(PIXI.DisplayObject.prototype, 'x', {
+
+    get: function() {
+        return  this.position.x;
+    },
+
+    set: function(value) {
+        this.position.x = value;
+    }
+
+});
+
+/**
+ * The position of the displayObject on the y axis relative to the local coordinates of the parent.
+ *
+ * @property y
+ * @type Number
+ */
+Object.defineProperty(PIXI.DisplayObject.prototype, 'y', {
+
+    get: function() {
+        return  this.position.y;
+    },
+
+    set: function(value) {
+        this.position.y = value;
+    }
+
+});
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * A DisplayObjectContainer represents a collection of display objects.
+ * It is the base class of all display objects that act as a container for other objects.
+ *
+ * @class DisplayObjectContainer
+ * @extends DisplayObject
+ * @constructor
+ */
+PIXI.DisplayObjectContainer = function()
+{
+    PIXI.DisplayObject.call(this);
+
+    /**
+     * [read-only] The array of children of this container.
+     *
+     * @property children
+     * @type Array(DisplayObject)
+     * @readOnly
+     */
+    this.children = [];
+    
+};
+
+// constructor
+PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
+PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
+
+/**
+ * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
+ *
+ * @property width
+ * @type Number
+ */
+Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', {
+
+    get: function() {
+        return this.scale.x * this.getLocalBounds().width;
+    },
+
+    set: function(value) {
+        
+        var width = this.getLocalBounds().width;
+
+        if (width !== 0)
+        {
+            this.scale.x = value / width;
+        }
+        else
+        {
+            this.scale.x = 1;
+        }
+        
+        this._width = value;
+    }
+});
+
+/**
+ * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
+ *
+ * @property height
+ * @type Number
+ */
+Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', {
+
+    get: function() {
+        return  this.scale.y * this.getLocalBounds().height;
+    },
+
+    set: function(value) {
+
+        var height = this.getLocalBounds().height;
+
+        if (height !== 0)
+        {
+            this.scale.y = value / height;
+        }
+        else
+        {
+            this.scale.y = 1;
+        }
+
+        this._height = value;
+    }
+
+});
+
+/**
+ * Adds a child to the container.
+ *
+ * @method addChild
+ * @param child {DisplayObject} The DisplayObject to add to the container
+ * @return {DisplayObject} The child that was added.
+ */
+PIXI.DisplayObjectContainer.prototype.addChild = function(child)
+{
+    return this.addChildAt(child, this.children.length);
+};
+
+/**
+ * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
+ *
+ * @method addChildAt
+ * @param child {DisplayObject} The child to add
+ * @param index {Number} The index to place the child in
+ * @return {DisplayObject} The child that was added.
+ */
+PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
+{
+    if(index >= 0 && index <= this.children.length)
+    {
+        if(child.parent)
+        {
+            child.parent.removeChild(child);
+        }
+
+        child.parent = this;
+
+        this.children.splice(index, 0, child);
+
+        if(this.stage)child.setStageReference(this.stage);
+
+        return child;
+    }
+    else
+    {
+        throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length);
+    }
+};
+
+/**
+ * Swaps the position of 2 Display Objects within this container.
+ *
+ * @method swapChildren
+ * @param child {DisplayObject}
+ * @param child2 {DisplayObject}
+ */
+PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
+{
+    if(child === child2) {
+        return;
+    }
+
+    var index1 = this.getChildIndex(child);
+    var index2 = this.getChildIndex(child2);
+
+    if(index1 < 0 || index2 < 0) {
+        throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.');
+    }
+
+    this.children[index1] = child2;
+    this.children[index2] = child;
+
+};
+
+/**
+ * Returns the index position of a child DisplayObject instance
+ *
+ * @method getChildIndex
+ * @param child {DisplayObject} The DisplayObject instance to identify
+ * @return {Number} The index position of the child display object to identify
+ */
+PIXI.DisplayObjectContainer.prototype.getChildIndex = function(child)
+{
+    var index = this.children.indexOf(child);
+    if (index === -1)
+    {
+        throw new Error('The supplied DisplayObject must be a child of the caller');
+    }
+    return index;
+};
+
+/**
+ * Changes the position of an existing child in the display object container
+ *
+ * @method setChildIndex
+ * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number
+ * @param index {Number} The resulting index number for the child display object
+ */
+PIXI.DisplayObjectContainer.prototype.setChildIndex = function(child, index)
+{
+    if (index < 0 || index >= this.children.length)
+    {
+        throw new Error('The supplied index is out of bounds');
+    }
+    var currentIndex = this.getChildIndex(child);
+    this.children.splice(currentIndex, 1); //remove from old position
+    this.children.splice(index, 0, child); //add at new position
+};
+
+/**
+ * Returns the child at the specified index
+ *
+ * @method getChildAt
+ * @param index {Number} The index to get the child from
+ * @return {DisplayObject} The child at the given index, if any.
+ */
+PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
+{
+    if (index < 0 || index >= this.children.length)
+    {
+        throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller');
+    }
+    return this.children[index];
+    
+};
+
+/**
+ * Removes a child from the container.
+ *
+ * @method removeChild
+ * @param child {DisplayObject} The DisplayObject to remove
+ * @return {DisplayObject} The child that was removed.
+ */
+PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
+{
+    var index = this.children.indexOf( child );
+    if(index === -1)return;
+    
+    return this.removeChildAt( index );
+};
+
+/**
+ * Removes a child from the specified index position.
+ *
+ * @method removeChildAt
+ * @param index {Number} The index to get the child from
+ * @return {DisplayObject} The child that was removed.
+ */
+PIXI.DisplayObjectContainer.prototype.removeChildAt = function(index)
+{
+    var child = this.getChildAt( index );
+    if(this.stage)
+        child.removeStageReference();
+
+    child.parent = undefined;
+    this.children.splice( index, 1 );
+    return child;
+};
+
+/**
+* Removes all children from this container that are within the begin and end indexes.
+*
+* @method removeChildren
+* @param beginIndex {Number} The beginning position. Default value is 0.
+* @param endIndex {Number} The ending position. Default value is size of the container.
+*/
+PIXI.DisplayObjectContainer.prototype.removeChildren = function(beginIndex, endIndex)
+{
+    var begin = beginIndex || 0;
+    var end = typeof endIndex === 'number' ? endIndex : this.children.length;
+    var range = end - begin;
+
+    if (range > 0 && range <= end)
+    {
+        var removed = this.children.splice(begin, range);
+        for (var i = 0; i < removed.length; i++) {
+            var child = removed[i];
+            if(this.stage)
+                child.removeStageReference();
+            child.parent = undefined;
+        }
+        return removed;
+    }
+    else if (range === 0 && this.children.length === 0)
+    {
+        return [];
+    }
+    else
+    {
+        throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' );
+    }
+};
+
+/*
+ * Updates the transform on all children of this container for rendering
+ *
+ * @method updateTransform
+ * @private
+ */
+PIXI.DisplayObjectContainer.prototype.updateTransform = function()
+{
+    if (!this.visible)
+    {
+        return;
+    }
+
+    this.displayObjectUpdateTransform();
+
+    if (this._cacheAsBitmap)
+    {
+        return;
+    }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i].updateTransform();
+    }
+};
+
+// performance increase to avoid using call.. (10x faster)
+PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform;
+
+/**
+ * Retrieves the bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration.
+ *
+ * @method getBounds
+ * @return {Rectangle} The rectangular bounding area
+ */
+PIXI.DisplayObjectContainer.prototype.getBounds = function()
+{
+    if(this.children.length === 0)return PIXI.EmptyRectangle;
+
+    // TODO the bounds have already been calculated this render session so return what we have
+
+    var minX = Infinity;
+    var minY = Infinity;
+
+    var maxX = -Infinity;
+    var maxY = -Infinity;
+
+    var childBounds;
+    var childMaxX;
+    var childMaxY;
+
+    var childVisible = false;
+
+    for(var i=0,j=this.children.length; i<j; i++)
+    {
+        var child = this.children[i];
+        
+        if(!child.visible)continue;
+
+        childVisible = true;
+
+        childBounds = this.children[i].getBounds();
+     
+        minX = minX < childBounds.x ? minX : childBounds.x;
+        minY = minY < childBounds.y ? minY : childBounds.y;
+
+        childMaxX = childBounds.width + childBounds.x;
+        childMaxY = childBounds.height + childBounds.y;
+
+        maxX = maxX > childMaxX ? maxX : childMaxX;
+        maxY = maxY > childMaxY ? maxY : childMaxY;
+    }
+
+    if(!childVisible)
+        return PIXI.EmptyRectangle;
+
+    var bounds = this._bounds;
+
+    bounds.x = minX;
+    bounds.y = minY;
+    bounds.width = maxX - minX;
+    bounds.height = maxY - minY;
+
+    // TODO: store a reference so that if this function gets called again in the render cycle we do not have to recalculate
+    //this._currentBounds = bounds;
+   
+    return bounds;
+};
+
+/**
+ * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle. The calculation takes all visible children into consideration.
+ *
+ * @method getLocalBounds
+ * @return {Rectangle} The rectangular bounding area
+ */
+PIXI.DisplayObjectContainer.prototype.getLocalBounds = function()
+{
+    var matrixCache = this.worldTransform;
+
+    this.worldTransform = PIXI.identityMatrix;
+
+    for(var i=0,j=this.children.length; i<j; i++)
+    {
+        this.children[i].updateTransform();
+    }
+
+    var bounds = this.getBounds();
+
+    this.worldTransform = matrixCache;
+
+    return bounds;
+};
+
+/**
+ * Sets the containers Stage reference. This is the Stage that this object, and all of its children, is connected to.
+ *
+ * @method setStageReference
+ * @param stage {Stage} the stage that the container will have as its current stage reference
+ */
+PIXI.DisplayObjectContainer.prototype.setStageReference = function(stage)
+{
+    this.stage = stage;
+    
+    for (var i=0; i < this.children.length; i++)
+    {
+        this.children[i].setStageReference(stage)
+    }
+};
+
+/**
+ * Removes the current stage reference from the container and all of its children.
+ *
+ * @method removeStageReference
+ */
+PIXI.DisplayObjectContainer.prototype.removeStageReference = function()
+{
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i].removeStageReference();
+    }
+
+    this.stage = null;
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method _renderWebGL
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.DisplayObjectContainer.prototype._renderWebGL = function(renderSession)
+{
+    if (!this.visible || this.alpha <= 0) return;
+    
+    if (this._cacheAsBitmap)
+    {
+        this._renderCachedSprite(renderSession);
+        return;
+    }
+    
+    var i;
+
+    if (this._mask || this._filters)
+    {
+        // push filter first as we need to ensure the stencil buffer is correct for any masking
+        if (this._filters)
+        {
+            renderSession.spriteBatch.flush();
+            renderSession.filterManager.pushFilter(this._filterBlock);
+        }
+
+        if (this._mask)
+        {
+            renderSession.spriteBatch.stop();
+            renderSession.maskManager.pushMask(this.mask, renderSession);
+            renderSession.spriteBatch.start();
+        }
+
+        // simple render children!
+        for (i = 0; i < this.children.length; i++)
+        {
+            this.children[i]._renderWebGL(renderSession);
+        }
+
+        renderSession.spriteBatch.stop();
+
+        if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
+        if (this._filters) renderSession.filterManager.popFilter();
+        
+        renderSession.spriteBatch.start();
+    }
+    else
+    {
+        // simple render children!
+        for (i = 0; i < this.children.length; i++)
+        {
+            this.children[i]._renderWebGL(renderSession);
+        }
+    }
+};
+
+/**
+* Renders the object using the Canvas renderer
+*
+* @method _renderCanvas
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.DisplayObjectContainer.prototype._renderCanvas = function(renderSession)
+{
+    if (this.visible === false || this.alpha === 0) return;
+
+    if (this._cacheAsBitmap)
+    {
+        this._renderCachedSprite(renderSession);
+        return;
+    }
+
+    if (this._mask)
+    {
+        renderSession.maskManager.pushMask(this._mask, renderSession);
+    }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i]._renderCanvas(renderSession);
+    }
+
+    if (this._mask)
+    {
+        renderSession.maskManager.popMask(renderSession);
+    }
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * The Sprite object is the base for all textured objects that are rendered to the screen
+ *
+ * @class Sprite
+ * @extends DisplayObjectContainer
+ * @constructor
+ * @param texture {Texture} The texture for this sprite
+ *
+ * A sprite can be created directly from an image like this :
+ * var sprite = new PIXI.Sprite.fromImage('assets/image.png');
+ * yourStage.addChild(sprite);
+ * then obviously don't forget to add it to the stage you have already created
+ */
+PIXI.Sprite = function(texture)
+{
+    PIXI.DisplayObjectContainer.call(this);
+
+    /**
+     * The anchor sets the origin point of the texture.
+     * The default is 0,0 this means the texture's origin is the top left
+     * Setting than anchor to 0.5,0.5 means the textures origin is centered
+     * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner
+     *
+     * @property anchor
+     * @type Point
+     */
+    this.anchor = new PIXI.Point();
+
+    /**
+     * The texture that the sprite is using
+     *
+     * @property texture
+     * @type Texture
+     */
+    this.texture = texture || PIXI.Texture.emptyTexture;
+
+    /**
+     * The width of the sprite (this is initially set by the texture)
+     *
+     * @property _width
+     * @type Number
+     * @private
+     */
+    this._width = 0;
+
+    /**
+     * The height of the sprite (this is initially set by the texture)
+     *
+     * @property _height
+     * @type Number
+     * @private
+     */
+    this._height = 0;
+
+    /**
+     * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
+     *
+     * @property tint
+     * @type Number
+     * @default 0xFFFFFF
+     */
+    this.tint = 0xFFFFFF;
+
+    /**
+     * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
+     *
+     * @property cachedTint
+     * @private
+     * @type Number
+     * @default -1
+     */
+    this.cachedTint = -1;
+
+    /**
+     * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this)
+     *
+     * @property tintedTexture
+     * @type Canvas
+     * @default null
+     */
+    this.tintedTexture = null;
+
+    /**
+     * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode.
+     *
+     * @property blendMode
+     * @type Number
+     * @default PIXI.blendModes.NORMAL;
+     */
+    this.blendMode = PIXI.blendModes.NORMAL;
+
+    /**
+     * The shader that will be used to render the texture to the stage. Set to null to remove a current shader.
+     *
+     * @property shader
+     * @type AbstractFilter
+     * @default null
+     */
+    this.shader = null;
+
+    if (this.texture.baseTexture.hasLoaded)
+    {
+        this.onTextureUpdate();
+    }
+
+    this.renderable = true;
+
+};
+
+// constructor
+PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
+PIXI.Sprite.prototype.constructor = PIXI.Sprite;
+
+/**
+ * The width of the sprite, setting this will actually modify the scale to achieve the value set
+ *
+ * @property width
+ * @type Number
+ */
+Object.defineProperty(PIXI.Sprite.prototype, 'width', {
+
+    get: function() {
+        return this.scale.x * this.texture.frame.width;
+    },
+
+    set: function(value) {
+        this.scale.x = value / this.texture.frame.width;
+        this._width = value;
+    }
+
+});
+
+/**
+ * The height of the sprite, setting this will actually modify the scale to achieve the value set
+ *
+ * @property height
+ * @type Number
+ */
+Object.defineProperty(PIXI.Sprite.prototype, 'height', {
+
+    get: function() {
+        return  this.scale.y * this.texture.frame.height;
+    },
+
+    set: function(value) {
+        this.scale.y = value / this.texture.frame.height;
+        this._height = value;
+    }
+
+});
+
+/**
+ * Sets the texture of the sprite
+ *
+ * @method setTexture
+ * @param texture {Texture} The PIXI texture that is displayed by the sprite
+ */
+PIXI.Sprite.prototype.setTexture = function(texture)
+{
+    this.texture = texture;
+    this.texture.valid = true;
+};
+
+/**
+ * When the texture is updated, this event will fire to update the scale and frame
+ *
+ * @method onTextureUpdate
+ * @param event
+ * @private
+ */
+PIXI.Sprite.prototype.onTextureUpdate = function()
+{
+    // so if _width is 0 then width was not set..
+    if (this._width) this.scale.x = this._width / this.texture.frame.width;
+    if (this._height) this.scale.y = this._height / this.texture.frame.height;
+};
+
+/**
+* Returns the bounds of the Sprite as a rectangle. The bounds calculation takes the worldTransform into account.
+*
+* @method getBounds
+* @param matrix {Matrix} the transformation matrix of the sprite
+* @return {Rectangle} the framing rectangle
+*/
+PIXI.Sprite.prototype.getBounds = function(matrix)
+{
+    var width = this.texture.frame.width;
+    var height = this.texture.frame.height;
+
+    var w0 = width * (1-this.anchor.x);
+    var w1 = width * -this.anchor.x;
+
+    var h0 = height * (1-this.anchor.y);
+    var h1 = height * -this.anchor.y;
+
+    var worldTransform = matrix || this.worldTransform;
+
+    var a = worldTransform.a;
+    var b = worldTransform.b;
+    var c = worldTransform.c;
+    var d = worldTransform.d;
+    var tx = worldTransform.tx;
+    var ty = worldTransform.ty;
+
+    var maxX = -Infinity;
+    var maxY = -Infinity;
+
+    var minX = Infinity;
+    var minY = Infinity;
+
+    if (b === 0 && c === 0)
+    {
+        // scale may be negative!
+        if (a < 0) a *= -1;
+        if (d < 0) d *= -1;
+
+        // this means there is no rotation going on right? RIGHT?
+        // if thats the case then we can avoid checking the bound values! yay         
+        minX = a * w1 + tx;
+        maxX = a * w0 + tx;
+        minY = d * h1 + ty;
+        maxY = d * h0 + ty;
+    }
+    else
+    {
+        var x1 = a * w1 + c * h1 + tx;
+        var y1 = d * h1 + b * w1 + ty;
+
+        var x2 = a * w0 + c * h1 + tx;
+        var y2 = d * h1 + b * w0 + ty;
+
+        var x3 = a * w0 + c * h0 + tx;
+        var y3 = d * h0 + b * w0 + ty;
+
+        var x4 =  a * w1 + c * h0 + tx;
+        var y4 =  d * h0 + b * w1 + ty;
+
+        minX = x1 < minX ? x1 : minX;
+        minX = x2 < minX ? x2 : minX;
+        minX = x3 < minX ? x3 : minX;
+        minX = x4 < minX ? x4 : minX;
+
+        minY = y1 < minY ? y1 : minY;
+        minY = y2 < minY ? y2 : minY;
+        minY = y3 < minY ? y3 : minY;
+        minY = y4 < minY ? y4 : minY;
+
+        maxX = x1 > maxX ? x1 : maxX;
+        maxX = x2 > maxX ? x2 : maxX;
+        maxX = x3 > maxX ? x3 : maxX;
+        maxX = x4 > maxX ? x4 : maxX;
+
+        maxY = y1 > maxY ? y1 : maxY;
+        maxY = y2 > maxY ? y2 : maxY;
+        maxY = y3 > maxY ? y3 : maxY;
+        maxY = y4 > maxY ? y4 : maxY;
+    }
+
+    var bounds = this._bounds;
+
+    bounds.x = minX;
+    bounds.width = maxX - minX;
+
+    bounds.y = minY;
+    bounds.height = maxY - minY;
+
+    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
+    this._currentBounds = bounds;
+
+    return bounds;
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method _renderWebGL
+* @param renderSession {RenderSession}
+* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
+* @private
+*/
+PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix)
+{
+    // if the sprite is not visible or the alpha is 0 then no need to render this element
+    if (!this.visible || this.alpha <= 0 || !this.renderable) return;
+
+    //  They provided an alternative rendering matrix, so use it
+    var wt = this.worldTransform;
+
+    if (matrix)
+    {
+        wt = matrix;
+    }
+
+    //  A quick check to see if this element has a mask or a filter.
+    if (this._mask || this._filters)
+    {
+        var spriteBatch = renderSession.spriteBatch;
+
+        // push filter first as we need to ensure the stencil buffer is correct for any masking
+        if (this._filters)
+        {
+            spriteBatch.flush();
+            renderSession.filterManager.pushFilter(this._filterBlock);
+        }
+
+        if (this._mask)
+        {
+            spriteBatch.stop();
+            renderSession.maskManager.pushMask(this.mask, renderSession);
+            spriteBatch.start();
+        }
+
+        // add this sprite to the batch
+        spriteBatch.render(this);
+
+        // now loop through the children and make sure they get rendered
+        for (var i = 0; i < this.children.length; i++)
+        {
+            this.children[i]._renderWebGL(renderSession);
+        }
+
+        // time to stop the sprite batch as either a mask element or a filter draw will happen next
+        spriteBatch.stop();
+
+        if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
+        if (this._filters) renderSession.filterManager.popFilter();
+
+        spriteBatch.start();
+    }
+    else
+    {
+        renderSession.spriteBatch.render(this);
+
+        //  Render children!
+        for (var i = 0; i < this.children.length; i++)
+        {
+            this.children[i]._renderWebGL(renderSession, wt);
+        }
+
+    }
+};
+
+/**
+* Renders the object using the Canvas renderer
+*
+* @method _renderCanvas
+* @param renderSession {RenderSession}
+* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
+* @private
+*/
+PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix)
+{
+    // If the sprite is not visible or the alpha is 0 then no need to render this element
+    if (this.visible === false || this.alpha === 0 || this.renderable === false || this.texture.crop.width <= 0 || this.texture.crop.height <= 0)
+    {
+        return;
+    }
+
+    var wt = this.worldTransform;
+
+    //  If they provided an alternative rendering matrix then use it
+    if (matrix)
+    {
+        wt = matrix;
+    }
+
+    if (this.blendMode !== renderSession.currentBlendMode)
+    {
+        renderSession.currentBlendMode = this.blendMode;
+        renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
+    }
+
+    if (this._mask)
+    {
+        renderSession.maskManager.pushMask(this._mask, renderSession);
+    }
+
+    //  Ignore null sources
+    if (this.texture.valid)
+    {
+        var resolution = this.texture.baseTexture.resolution / renderSession.resolution;
+
+        renderSession.context.globalAlpha = this.worldAlpha;
+
+         //  If smoothingEnabled is supported and we need to change the smoothing property for this texture
+        if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode)
+        {
+            renderSession.scaleMode = this.texture.baseTexture.scaleMode;
+            renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR);
+        }
+
+        //  If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
+        var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width;
+        var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height;
+
+        //  Allow for pixel rounding
+        if (renderSession.roundPixels)
+        {
+            renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, (wt.tx * renderSession.resolution) | 0, (wt.ty * renderSession.resolution) | 0);
+            dx = dx | 0;
+            dy = dy | 0;
+        }
+        else
+        {
+            renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderSession.resolution, wt.ty * renderSession.resolution);
+        }
+
+        var cw = this.texture.crop.width;
+        var ch = this.texture.crop.height;
+
+        dx /= resolution;
+        dy /= resolution;
+
+        if (this.tint !== 0xFFFFFF)
+        {
+            if (this.texture.requiresReTint || this.cachedTint !== this.tint)
+            {
+                this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint);
+
+                this.cachedTint = this.tint;
+            }
+
+            renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution);
+        }
+        else
+        {
+            var cx = this.texture.crop.x;
+            var cy = this.texture.crop.y;
+            renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution);
+        }
+    }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i]._renderCanvas(renderSession);
+    }
+
+    if (this._mask)
+    {
+        renderSession.maskManager.popMask(renderSession);
+    }
+
+};
+
+// some helper functions..
+
+/**
+ *
+ * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
+ * The frame ids are created when a Texture packer file has been loaded
+ *
+ * @method fromFrame
+ * @static
+ * @param frameId {String} The frame Id of the texture in the cache
+ * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId
+ */
+PIXI.Sprite.fromFrame = function(frameId)
+{
+    var texture = PIXI.TextureCache[frameId];
+
+    if (!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this);
+
+    return new PIXI.Sprite(texture);
+};
+
+/**
+ *
+ * Helper function that creates a sprite that will contain a texture based on an image url
+ * If the image is not in the texture cache it will be loaded
+ *
+ * @method fromImage
+ * @static
+ * @param imageId {String} The image url of the texture
+ * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id
+ */
+PIXI.Sprite.fromImage = function(imageId, crossorigin, scaleMode)
+{
+    var texture = PIXI.Texture.fromImage(imageId, crossorigin, scaleMode);
+
+    return new PIXI.Sprite(texture);
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/
+ */
+
+/**
+ * The SpriteBatch class is a really fast version of the DisplayObjectContainer 
+ * built solely for speed, so use when you need a lot of sprites or particles.
+ * And it's extremely easy to use : 
+
+    var container = new PIXI.SpriteBatch();
+ 
+    stage.addChild(container);
+ 
+    for(var i  = 0; i < 100; i++)
+    {
+        var sprite = new PIXI.Sprite.fromImage("myImage.png");
+        container.addChild(sprite);
+    }
+ * And here you have a hundred sprites that will be renderer at the speed of light
+ *
+ * @class SpriteBatch
+ * @constructor
+ * @param texture {Texture}
+ */
+PIXI.SpriteBatch = function(texture)
+{
+    PIXI.DisplayObjectContainer.call( this);
+
+    this.textureThing = texture;
+
+    this.ready = false;
+};
+
+PIXI.SpriteBatch.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
+PIXI.SpriteBatch.prototype.constructor = PIXI.SpriteBatch;
+
+/*
+ * Initialises the spriteBatch
+ *
+ * @method initWebGL
+ * @param gl {WebGLContext} the current WebGL drawing context
+ */
+PIXI.SpriteBatch.prototype.initWebGL = function(gl)
+{
+    // TODO only one needed for the whole engine really?
+    this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(gl);
+
+    this.ready = true;
+};
+
+/*
+ * Updates the object transform for rendering
+ *
+ * @method updateTransform
+ * @private
+ */
+PIXI.SpriteBatch.prototype.updateTransform = function()
+{
+    // TODO don't need to!
+    this.displayObjectUpdateTransform();
+    //  PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method _renderWebGL
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.SpriteBatch.prototype._renderWebGL = function(renderSession)
+{
+    if (!this.visible || this.alpha <= 0 || !this.children.length) return;
+
+    if (!this.ready)
+    {
+        this.initWebGL(renderSession.gl);
+    }
+    
+    if (this.fastSpriteBatch.gl !== renderSession.gl)
+    {
+        this.fastSpriteBatch.setContext(renderSession.gl);
+    }
+
+    renderSession.spriteBatch.stop();
+    
+    renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader);
+    
+    this.fastSpriteBatch.begin(this, renderSession);
+    this.fastSpriteBatch.render(this);
+
+    renderSession.spriteBatch.start();
+ 
+};
+
+/**
+* Renders the object using the Canvas renderer
+*
+* @method _renderCanvas
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.SpriteBatch.prototype._renderCanvas = function(renderSession)
+{
+    if (!this.visible || this.alpha <= 0 || !this.children.length) return;
+    
+    var context = renderSession.context;
+
+    context.globalAlpha = this.worldAlpha;
+
+    this.displayObjectUpdateTransform();
+
+    var transform = this.worldTransform;
+       
+    var isRotated = true;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        var child = this.children[i];
+
+        if (!child.visible) continue;
+
+        var texture = child.texture;
+        var frame = texture.frame;
+
+        context.globalAlpha = this.worldAlpha * child.alpha;
+
+        if (child.rotation % (Math.PI * 2) === 0)
+        {
+            if (isRotated)
+            {
+                context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
+                isRotated = false;
+            }
+
+            // this is the fastest  way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call
+            context.drawImage(texture.baseTexture.source,
+                                 frame.x,
+                                 frame.y,
+                                 frame.width,
+                                 frame.height,
+                                 ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x  + 0.5) | 0,
+                                 ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y  + 0.5) | 0,
+                                 frame.width * child.scale.x,
+                                 frame.height * child.scale.y);
+        }
+        else
+        {
+            if (!isRotated) isRotated = true;
+    
+            child.displayObjectUpdateTransform();
+           
+            var childTransform = child.worldTransform;
+
+            // allow for trimming
+           
+            if (renderSession.roundPixels)
+            {
+                context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx | 0, childTransform.ty | 0);
+            }
+            else
+            {
+                context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx, childTransform.ty);
+            }
+
+            context.drawImage(texture.baseTexture.source,
+                                 frame.x,
+                                 frame.y,
+                                 frame.width,
+                                 frame.height,
+                                 ((child.anchor.x) * (-frame.width) + 0.5) | 0,
+                                 ((child.anchor.y) * (-frame.height) + 0.5) | 0,
+                                 frame.width,
+                                 frame.height);
+        }
+    }
+
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * A Stage represents the root of the display tree. Everything connected to the stage is rendered
+ *
+ * @class Stage
+ * @extends DisplayObjectContainer
+ * @constructor
+ * @param backgroundColor {Number} the background color of the stage, you have to pass this in is in hex format
+ *      like: 0xFFFFFF for white
+ * 
+ * Creating a stage is a mandatory process when you use Pixi, which is as simple as this : 
+ * var stage = new PIXI.Stage(0xFFFFFF);
+ * where the parameter given is the background colour of the stage, in hex
+ * you will use this stage instance to add your sprites to it and therefore to the renderer
+ * Here is how to add a sprite to the stage : 
+ * stage.addChild(sprite);
+ */
+PIXI.Stage = function(backgroundColor)
+{
+    PIXI.DisplayObjectContainer.call( this );
+
+    /**
+     * [read-only] Current transform of the object based on world (parent) factors
+     *
+     * @property worldTransform
+     * @type Matrix
+     * @readOnly
+     * @private
+     */
+    this.worldTransform = new PIXI.Matrix();
+
+    //the stage is its own stage
+    this.stage = this;
+
+    this.setBackgroundColor(backgroundColor);
+};
+
+// constructor
+PIXI.Stage.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
+PIXI.Stage.prototype.constructor = PIXI.Stage;
+
+/*
+ * Updates the object transform for rendering
+ *
+ * @method updateTransform
+ * @private
+ */
+PIXI.Stage.prototype.updateTransform = function()
+{
+    this.worldAlpha = 1;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i].updateTransform();
+    }
+};
+
+/**
+ * Sets the background color for the stage
+ *
+ * @method setBackgroundColor
+ * @param backgroundColor {Number} the color of the background, easiest way to pass this in is in hex format
+ *      like: 0xFFFFFF for white
+ */
+PIXI.Stage.prototype.setBackgroundColor = function(backgroundColor)
+{
+    this.backgroundColor = backgroundColor || 0x000000;
+    this.backgroundColorSplit = PIXI.hex2rgb(this.backgroundColor);
+    var hex = this.backgroundColor.toString(16);
+    hex = '000000'.substr(0, 6 - hex.length) + hex;
+    this.backgroundColorString = '#' + hex;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+ 
+/**
+ * Converts a hex color number to an [R, G, B] array
+ *
+ * @method hex2rgb
+ * @param hex {Number}
+ */
+PIXI.hex2rgb = function(hex) {
+    return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
+};
+
+/**
+ * Converts a color as an [R, G, B] array to a hex number
+ *
+ * @method rgb2hex
+ * @param rgb {Array}
+ */
+PIXI.rgb2hex = function(rgb) {
+    return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
+};
+
+/**
+ * Checks whether the Canvas BlendModes are supported by the current browser for drawImage
+ *
+ * @method canUseNewCanvasBlendModes
+ * @return {Boolean} whether they are supported
+ */
+PIXI.canUseNewCanvasBlendModes = function()
+{
+    if (document === undefined) return false;
+
+    var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/';
+    var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==';
+
+    var magenta = new Image();
+    magenta.src = pngHead + 'AP804Oa6' + pngEnd;
+
+    var yellow = new Image();
+    yellow.src = pngHead + '/wCKxvRF' + pngEnd;
+
+    var canvas = document.createElement('canvas');
+    canvas.width = 6;
+    canvas.height = 1;
+    var context = canvas.getContext('2d');
+    context.globalCompositeOperation = 'multiply';
+    context.drawImage(magenta, 0, 0);
+    context.drawImage(yellow, 2, 0);
+
+    if (!context.getImageData(2,0,1,1))
+    {
+        return false;
+    }
+
+    var data = context.getImageData(2,0,1,1).data;
+
+    return (data[0] === 255 && data[1] === 0 && data[2] === 0);
+};
+
+/**
+ * Given a number, this function returns the closest number that is a power of two
+ * this function is taken from Starling Framework as its pretty neat ;)
+ *
+ * @method getNextPowerOfTwo
+ * @param number {Number}
+ * @return {Number} the closest number that is a power of two
+ */
+PIXI.getNextPowerOfTwo = function(number)
+{
+    if (number > 0 && (number & (number - 1)) === 0) // see: http://goo.gl/D9kPj
+        return number;
+    else
+    {
+        var result = 1;
+        while (result < number) result <<= 1;
+        return result;
+    }
+};
+
+/**
+ * checks if the given width and height make a power of two texture
+ * @method isPowerOfTwo
+ * @param width {Number}
+ * @param height {Number}
+ * @return {Boolean} 
+ */
+PIXI.isPowerOfTwo = function(width, height)
+{
+    return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0);
+
+};
+
+/*
+    PolyK library
+    url: http://polyk.ivank.net
+    Released under MIT licence.
+
+    Copyright (c) 2012 Ivan Kuckir
+
+    Permission is hereby granted, free of charge, to any person
+    obtaining a copy of this software and associated documentation
+    files (the "Software"), to deal in the Software without
+    restriction, including without limitation the rights to use,
+    copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the
+    Software is furnished to do so, subject to the following
+    conditions:
+
+    The above copyright notice and this permission notice shall be
+    included in all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+    OTHER DEALINGS IN THE SOFTWARE.
+
+    This is an amazing lib!
+
+    Slightly modified by Mat Groves (matgroves.com);
+*/
+
+/**
+ * Based on the Polyk library http://polyk.ivank.net released under MIT licence.
+ * This is an amazing lib!
+ * Slightly modified by Mat Groves (matgroves.com);
+ * @class PolyK
+ */
+PIXI.PolyK = {};
+
+/**
+ * Triangulates shapes for webGL graphic fills.
+ *
+ * @method Triangulate
+ */
+PIXI.PolyK.Triangulate = function(p)
+{
+    var sign = true;
+
+    var n = p.length >> 1;
+    if(n < 3) return [];
+
+    var tgs = [];
+    var avl = [];
+    for(var i = 0; i < n; i++) avl.push(i);
+
+    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(PIXI.PolyK._convex(ax, ay, bx, by, cx, cy, sign))
+        {
+            earFound = true;
+            for(var j = 0; j < al; j++)
+            {
+                var vi = avl[j];
+                if(vi === i0 || vi === i1 || vi === i2) continue;
+
+                if(PIXI.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)
+        {
+            // need to flip flip reverse it!
+            // reset!
+            if(sign)
+            {
+                tgs = [];
+                avl = [];
+                for(i = 0; i < n; i++) avl.push(i);
+
+                i = 0;
+                al = n;
+
+                sign = false;
+            }
+            else
+            {
+             //   window.console.log("PIXI Warning: shape too complex to fill");
+                return null;
+            }
+        }
+    }
+
+    tgs.push(avl[0], avl[1], avl[2]);
+    return tgs;
+};
+
+/**
+ * Checks whether a point is within a triangle
+ *
+ * @method _PointInTriangle
+ * @param px {Number} x coordinate of the point to test
+ * @param py {Number} y coordinate of the point to test
+ * @param ax {Number} x coordinate of the a point of the triangle
+ * @param ay {Number} y coordinate of the a point of the triangle
+ * @param bx {Number} x coordinate of the b point of the triangle
+ * @param by {Number} y coordinate of the b point of the triangle
+ * @param cx {Number} x coordinate of the c point of the triangle
+ * @param cy {Number} y coordinate of the c point of the triangle
+ * @private
+ * @return {Boolean}
+ */
+PIXI.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;
+
+    // Check if point is in triangle
+    return (u >= 0) && (v >= 0) && (u + v < 1);
+};
+
+/**
+ * Checks whether a shape is convex
+ *
+ * @method _convex
+ * @private
+ * @return {Boolean}
+ */
+PIXI.PolyK._convex = function(ax, ay, bx, by, cx, cy, sign)
+{
+    return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @method initDefaultShaders
+* @static
+* @private
+*/
+PIXI.initDefaultShaders = function()
+{
+};
+
+/**
+* @method CompileVertexShader
+* @static
+* @param gl {WebGLContext} the current WebGL drawing context
+* @param shaderSrc {Array}
+* @return {Any}
+*/
+PIXI.CompileVertexShader = function(gl, shaderSrc)
+{
+    return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER);
+};
+
+/**
+* @method CompileFragmentShader
+* @static
+* @param gl {WebGLContext} the current WebGL drawing context
+* @param shaderSrc {Array}
+* @return {Any}
+*/
+PIXI.CompileFragmentShader = function(gl, shaderSrc)
+{
+    return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER);
+};
+
+/**
+* @method _CompileShader
+* @static
+* @private
+* @param gl {WebGLContext} the current WebGL drawing context
+* @param shaderSrc {Array}
+* @param shaderType {Number}
+* @return {Any}
+*/
+PIXI._CompileShader = function(gl, shaderSrc, shaderType)
+{
+    var src = shaderSrc;
+
+    if (Array.isArray(shaderSrc))
+    {
+        src = shaderSrc.join("\n");
+    }
+
+    var shader = gl.createShader(shaderType);
+    gl.shaderSource(shader, src);
+    gl.compileShader(shader);
+
+    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
+    {
+        window.console.log(gl.getShaderInfoLog(shader));
+        return null;
+    }
+
+    return shader;
+};
+
+/**
+* @method compileProgram
+* @static
+* @param gl {WebGLContext} the current WebGL drawing context
+* @param vertexSrc {Array}
+* @param fragmentSrc {Array}
+* @return {Any}
+*/
+PIXI.compileProgram = function(gl, vertexSrc, fragmentSrc)
+{
+    var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc);
+    var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc);
+
+    var shaderProgram = gl.createProgram();
+
+    gl.attachShader(shaderProgram, vertexShader);
+    gl.attachShader(shaderProgram, fragmentShader);
+    gl.linkProgram(shaderProgram);
+
+    if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
+    {
+        window.console.log("Could not initialise shaders");
+    }
+
+    return shaderProgram;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ * @author Richard Davey http://www.photonstorm.com @photonstorm
+ */
+
+/**
+* @class PixiShader
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.PixiShader = function(gl)
+{
+    /**
+     * @property _UID
+     * @type Number
+     * @private
+     */
+    this._UID = PIXI._UID++;
+
+    /**
+     * @property gl
+     * @type WebGLContext
+     */
+    this.gl = gl;
+
+    /**
+     * The WebGL program.
+     * @property program
+     * @type Any
+     */
+    this.program = null;
+
+    /**
+     * The fragment shader.
+     * @property fragmentSrc
+     * @type Array
+     */
+    this.fragmentSrc = [
+        'precision lowp float;',
+        'varying vec2 vTextureCoord;',
+        'varying vec4 vColor;',
+        'uniform sampler2D uSampler;',
+        'void main(void) {',
+        '   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
+        '}'
+    ];
+
+    /**
+     * A local texture counter for multi-texture shaders.
+     * @property textureCount
+     * @type Number
+     */
+    this.textureCount = 0;
+
+    /**
+     * A local flag
+     * @property firstRun
+     * @type Boolean
+     * @private
+     */
+    this.firstRun = true;
+
+    /**
+     * A dirty flag
+     * @property dirty
+     * @type Boolean
+     */
+    this.dirty = true;
+
+    /**
+     * Uniform attributes cache.
+     * @property attributes
+     * @type Array
+     * @private
+     */
+    this.attributes = [];
+
+    this.init();
+};
+
+PIXI.PixiShader.prototype.constructor = PIXI.PixiShader;
+
+/**
+* Initialises the shader.
+*
+* @method init
+*/
+PIXI.PixiShader.prototype.init = function()
+{
+    var gl = this.gl;
+
+    var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc);
+
+    gl.useProgram(program);
+
+    // get and store the uniforms for the shader
+    this.uSampler = gl.getUniformLocation(program, 'uSampler');
+    this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
+    this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
+    this.dimensions = gl.getUniformLocation(program, 'dimensions');
+
+    // get and store the attributes
+    this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
+    this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
+    this.colorAttribute = gl.getAttribLocation(program, 'aColor');
+
+    // Begin worst hack eva //
+
+    // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
+    // maybe its something to do with the current state of the gl context.
+    // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
+    // If theres any webGL people that know why could happen please help :)
+    if(this.colorAttribute === -1)
+    {
+        this.colorAttribute = 2;
+    }
+
+    this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute];
+
+    // End worst hack eva //
+
+    // add those custom shaders!
+    for (var key in this.uniforms)
+    {
+        // get the uniform locations..
+        this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key);
+    }
+
+    this.initUniforms();
+
+    this.program = program;
+};
+
+/**
+* Initialises the shader uniform values.
+*
+* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
+* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
+*
+* @method initUniforms
+*/
+PIXI.PixiShader.prototype.initUniforms = function()
+{
+    this.textureCount = 1;
+    var gl = this.gl;
+    var uniform;
+
+    for (var key in this.uniforms)
+    {
+        uniform = this.uniforms[key];
+
+        var type = uniform.type;
+
+        if (type === 'sampler2D')
+        {
+            uniform._init = false;
+
+            if (uniform.value !== null)
+            {
+                this.initSampler2D(uniform);
+            }
+        }
+        else if (type === 'mat2' || type === 'mat3' || type === 'mat4')
+        {
+            //  These require special handling
+            uniform.glMatrix = true;
+            uniform.glValueLength = 1;
+
+            if (type === 'mat2')
+            {
+                uniform.glFunc = gl.uniformMatrix2fv;
+            }
+            else if (type === 'mat3')
+            {
+                uniform.glFunc = gl.uniformMatrix3fv;
+            }
+            else if (type === 'mat4')
+            {
+                uniform.glFunc = gl.uniformMatrix4fv;
+            }
+        }
+        else
+        {
+            //  GL function reference
+            uniform.glFunc = gl['uniform' + type];
+
+            if (type === '2f' || type === '2i')
+            {
+                uniform.glValueLength = 2;
+            }
+            else if (type === '3f' || type === '3i')
+            {
+                uniform.glValueLength = 3;
+            }
+            else if (type === '4f' || type === '4i')
+            {
+                uniform.glValueLength = 4;
+            }
+            else
+            {
+                uniform.glValueLength = 1;
+            }
+        }
+    }
+
+};
+
+/**
+* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded)
+*
+* @method initSampler2D
+*/
+PIXI.PixiShader.prototype.initSampler2D = function(uniform)
+{
+    if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded)
+    {
+        return;
+    }
+
+    var gl = this.gl;
+
+    gl.activeTexture(gl['TEXTURE' + this.textureCount]);
+    gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
+
+    //  Extended texture data
+    if (uniform.textureData)
+    {
+        var data = uniform.textureData;
+
+        // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D);
+        // GLTextureLinear = mag/min linear, wrap clamp
+        // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat
+        // GLTextureNearest = mag/min nearest, wrap clamp
+        // AudioTexture = whatever + luminance + width 512, height 2, border 0
+        // KeyTexture = whatever + luminance + width 256, height 2, border 0
+
+        //  magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
+        //  wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
+
+        var magFilter = (data.magFilter) ? data.magFilter : gl.LINEAR;
+        var minFilter = (data.minFilter) ? data.minFilter : gl.LINEAR;
+        var wrapS = (data.wrapS) ? data.wrapS : gl.CLAMP_TO_EDGE;
+        var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE;
+        var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA;
+
+        if (data.repeat)
+        {
+            wrapS = gl.REPEAT;
+            wrapT = gl.REPEAT;
+        }
+
+        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);
+
+        if (data.width)
+        {
+            var width = (data.width) ? data.width : 512;
+            var height = (data.height) ? data.height : 2;
+            var border = (data.border) ? data.border : 0;
+
+            // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
+            gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null);
+        }
+        else
+        {
+            //  void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels);
+            gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.value.baseTexture.source);
+        }
+
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
+    }
+
+    gl.uniform1i(uniform.uniformLocation, this.textureCount);
+
+    uniform._init = true;
+
+    this.textureCount++;
+
+};
+
+/**
+* Updates the shader uniform values.
+*
+* @method syncUniforms
+*/
+PIXI.PixiShader.prototype.syncUniforms = function()
+{
+    this.textureCount = 1;
+    var uniform;
+    var gl = this.gl;
+
+    //  This would probably be faster in an array and it would guarantee key order
+    for (var key in this.uniforms)
+    {
+        uniform = this.uniforms[key];
+
+        if (uniform.glValueLength === 1)
+        {
+            if (uniform.glMatrix === true)
+            {
+                uniform.glFunc.call(gl, uniform.uniformLocation, uniform.transpose, uniform.value);
+            }
+            else
+            {
+                uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value);
+            }
+        }
+        else if (uniform.glValueLength === 2)
+        {
+            uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y);
+        }
+        else if (uniform.glValueLength === 3)
+        {
+            uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z);
+        }
+        else if (uniform.glValueLength === 4)
+        {
+            uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z, uniform.value.w);
+        }
+        else if (uniform.type === 'sampler2D')
+        {
+            if (uniform._init)
+            {
+                gl.activeTexture(gl['TEXTURE' + this.textureCount]);
+
+                if(uniform.value.baseTexture._dirty[gl.id])
+                {
+                    PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture);
+                }
+                else
+                {
+                    // bind the current texture
+                    gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
+                }
+
+                //  gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture( uniform.value.baseTexture, gl));
+                gl.uniform1i(uniform.uniformLocation, this.textureCount);
+                this.textureCount++;
+            }
+            else
+            {
+                this.initSampler2D(uniform);
+            }
+        }
+    }
+
+};
+
+/**
+* Destroys the shader.
+*
+* @method destroy
+*/
+PIXI.PixiShader.prototype.destroy = function()
+{
+    this.gl.deleteProgram( this.program );
+    this.uniforms = null;
+    this.gl = null;
+
+    this.attributes = null;
+};
+
+/**
+* The Default Vertex shader source.
+*
+* @property defaultVertexSrc
+* @type String
+*/
+PIXI.PixiShader.defaultVertexSrc = [
+    'attribute vec2 aVertexPosition;',
+    'attribute vec2 aTextureCoord;',
+    'attribute vec4 aColor;',
+
+    'uniform vec2 projectionVector;',
+    'uniform vec2 offsetVector;',
+
+    'varying vec2 vTextureCoord;',
+    'varying vec4 vColor;',
+
+    'const vec2 center = vec2(-1.0, 1.0);',
+
+    'void main(void) {',
+    '   gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);',
+    '   vTextureCoord = aTextureCoord;',
+    '   vColor = vec4(aColor.rgb * aColor.a, aColor.a);',
+    '}'
+];
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class PixiFastShader
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.PixiFastShader = function(gl)
+{
+    /**
+     * @property _UID
+     * @type Number
+     * @private
+     */
+    this._UID = PIXI._UID++;
+    
+    /**
+     * @property gl
+     * @type WebGLContext
+     */
+    this.gl = gl;
+
+    /**
+     * The WebGL program.
+     * @property program
+     * @type Any
+     */
+    this.program = null;
+
+    /**
+     * The fragment shader.
+     * @property fragmentSrc
+     * @type Array
+     */
+    this.fragmentSrc = [
+        'precision lowp float;',
+        'varying vec2 vTextureCoord;',
+        'varying float vColor;',
+        'uniform sampler2D uSampler;',
+        'void main(void) {',
+        '   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
+        '}'
+    ];
+
+    /**
+     * The vertex shader.
+     * @property vertexSrc
+     * @type Array
+     */
+    this.vertexSrc = [
+        'attribute vec2 aVertexPosition;',
+        'attribute vec2 aPositionCoord;',
+        'attribute vec2 aScale;',
+        'attribute float aRotation;',
+        'attribute vec2 aTextureCoord;',
+        'attribute float aColor;',
+
+        'uniform vec2 projectionVector;',
+        'uniform vec2 offsetVector;',
+        'uniform mat3 uMatrix;',
+
+        'varying vec2 vTextureCoord;',
+        'varying float vColor;',
+
+        'const vec2 center = vec2(-1.0, 1.0);',
+
+        'void main(void) {',
+        '   vec2 v;',
+        '   vec2 sv = aVertexPosition * aScale;',
+        '   v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);',
+        '   v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);',
+        '   v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;',
+        '   gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);',
+        '   vTextureCoord = aTextureCoord;',
+      //  '   vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
+        '   vColor = aColor;',
+        '}'
+    ];
+
+    /**
+     * A local texture counter for multi-texture shaders.
+     * @property textureCount
+     * @type Number
+     */
+    this.textureCount = 0;
+    
+    this.init();
+};
+
+PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader;
+
+/**
+* Initialises the shader.
+* 
+* @method init
+*/
+PIXI.PixiFastShader.prototype.init = function()
+{
+    var gl = this.gl;
+
+    var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
+    
+    gl.useProgram(program);
+
+    // get and store the uniforms for the shader
+    this.uSampler = gl.getUniformLocation(program, 'uSampler');
+
+    this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
+    this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
+    this.dimensions = gl.getUniformLocation(program, 'dimensions');
+    this.uMatrix = gl.getUniformLocation(program, 'uMatrix');
+
+    // get and store the attributes
+    this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
+    this.aPositionCoord = gl.getAttribLocation(program, 'aPositionCoord');
+
+    this.aScale = gl.getAttribLocation(program, 'aScale');
+    this.aRotation = gl.getAttribLocation(program, 'aRotation');
+
+    this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
+    this.colorAttribute = gl.getAttribLocation(program, 'aColor');
+   
+    // Begin worst hack eva //
+
+    // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
+    // maybe its somthing to do with the current state of the gl context.
+    // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
+    // If theres any webGL people that know why could happen please help :)
+    if(this.colorAttribute === -1)
+    {
+        this.colorAttribute = 2;
+    }
+
+    this.attributes = [this.aVertexPosition, this.aPositionCoord,  this.aScale, this.aRotation, this.aTextureCoord, this.colorAttribute];
+    
+    // End worst hack eva //
+
+    this.program = program;
+};
+
+/**
+* Destroys the shader.
+* 
+* @method destroy
+*/
+PIXI.PixiFastShader.prototype.destroy = function()
+{
+    this.gl.deleteProgram( this.program );
+    this.uniforms = null;
+    this.gl = null;
+
+    this.attributes = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class StripShader
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.StripShader = function(gl)
+{
+    /**
+     * @property _UID
+     * @type Number
+     * @private
+     */
+    this._UID = PIXI._UID++;
+    
+    /**
+     * @property gl
+     * @type WebGLContext
+     */
+    this.gl = gl;
+
+    /**
+     * The WebGL program.
+     * @property program
+     * @type Any
+     */
+    this.program = null;
+
+    /**
+     * The fragment shader.
+     * @property fragmentSrc
+     * @type Array
+     */
+    this.fragmentSrc = [
+        'precision mediump float;',
+        'varying vec2 vTextureCoord;',
+     //   'varying float vColor;',
+        'uniform float alpha;',
+        'uniform sampler2D uSampler;',
+
+        'void main(void) {',
+        '   gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;',
+      //  '   gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);',//gl_FragColor * alpha;',
+        '}'
+    ];
+
+    /**
+     * The vertex shader.
+     * @property vertexSrc
+     * @type Array
+     */
+    this.vertexSrc  = [
+        'attribute vec2 aVertexPosition;',
+        'attribute vec2 aTextureCoord;',
+        'uniform mat3 translationMatrix;',
+        'uniform vec2 projectionVector;',
+        'uniform vec2 offsetVector;',
+      //  'uniform float alpha;',
+       // 'uniform vec3 tint;',
+        'varying vec2 vTextureCoord;',
+      //  'varying vec4 vColor;',
+
+        'void main(void) {',
+        '   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
+        '   v -= offsetVector.xyx;',
+        '   gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
+        '   vTextureCoord = aTextureCoord;',
+       // '   vColor = aColor * vec4(tint * alpha, alpha);',
+        '}'
+    ];
+
+    this.init();
+};
+
+PIXI.StripShader.prototype.constructor = PIXI.StripShader;
+
+/**
+* Initialises the shader.
+* 
+* @method init
+*/
+PIXI.StripShader.prototype.init = function()
+{
+    var gl = this.gl;
+
+    var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
+    gl.useProgram(program);
+
+    // get and store the uniforms for the shader
+    this.uSampler = gl.getUniformLocation(program, 'uSampler');
+    this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
+    this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
+    this.colorAttribute = gl.getAttribLocation(program, 'aColor');
+    //this.dimensions = gl.getUniformLocation(this.program, 'dimensions');
+
+    // get and store the attributes
+    this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
+    this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
+
+    this.attributes = [this.aVertexPosition, this.aTextureCoord];
+
+    this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
+    this.alpha = gl.getUniformLocation(program, 'alpha');
+
+    this.program = program;
+};
+
+/**
+* Destroys the shader.
+* 
+* @method destroy
+*/
+PIXI.StripShader.prototype.destroy = function()
+{
+    this.gl.deleteProgram( this.program );
+    this.uniforms = null;
+    this.gl = null;
+
+    this.attribute = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class PrimitiveShader
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.PrimitiveShader = function(gl)
+{
+    /**
+     * @property _UID
+     * @type Number
+     * @private
+     */
+    this._UID = PIXI._UID++;
+ 
+    /**
+     * @property gl
+     * @type WebGLContext
+     */
+    this.gl = gl;
+
+    /**
+     * The WebGL program.
+     * @property program
+     * @type Any
+     */
+    this.program = null;
+
+    /**
+     * The fragment shader.
+     * @property fragmentSrc
+     * @type Array
+     */
+    this.fragmentSrc = [
+        'precision mediump float;',
+        'varying vec4 vColor;',
+
+        'void main(void) {',
+        '   gl_FragColor = vColor;',
+        '}'
+    ];
+
+    /**
+     * The vertex shader.
+     * @property vertexSrc
+     * @type Array
+     */
+    this.vertexSrc  = [
+        'attribute vec2 aVertexPosition;',
+        'attribute vec4 aColor;',
+        'uniform mat3 translationMatrix;',
+        'uniform vec2 projectionVector;',
+        'uniform vec2 offsetVector;',
+        'uniform float alpha;',
+        'uniform float flipY;',
+        'uniform vec3 tint;',
+        'varying vec4 vColor;',
+
+        'void main(void) {',
+        '   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
+        '   v -= offsetVector.xyx;',
+        '   gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);',
+        '   vColor = aColor * vec4(tint * alpha, alpha);',
+        '}'
+    ];
+
+    this.init();
+};
+
+PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader;
+
+/**
+* Initialises the shader.
+* 
+* @method init
+*/
+PIXI.PrimitiveShader.prototype.init = function()
+{
+    var gl = this.gl;
+
+    var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
+    gl.useProgram(program);
+
+    // get and store the uniforms for the shader
+    this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
+    this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
+    this.tintColor = gl.getUniformLocation(program, 'tint');
+    this.flipY = gl.getUniformLocation(program, 'flipY');
+
+    // get and store the attributes
+    this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
+    this.colorAttribute = gl.getAttribLocation(program, 'aColor');
+
+    this.attributes = [this.aVertexPosition, this.colorAttribute];
+
+    this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
+    this.alpha = gl.getUniformLocation(program, 'alpha');
+
+    this.program = program;
+};
+
+/**
+* Destroys the shader.
+* 
+* @method destroy
+*/
+PIXI.PrimitiveShader.prototype.destroy = function()
+{
+    this.gl.deleteProgram( this.program );
+    this.uniforms = null;
+    this.gl = null;
+
+    this.attributes = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class ComplexPrimitiveShader
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.ComplexPrimitiveShader = function(gl)
+{
+    /**
+     * @property _UID
+     * @type Number
+     * @private
+     */
+    this._UID = PIXI._UID++;
+
+    /**
+     * @property gl
+     * @type WebGLContext
+     */
+    this.gl = gl;
+
+    /**
+     * The WebGL program.
+     * @property program
+     * @type Any
+     */
+    this.program = null;
+
+    /**
+     * The fragment shader.
+     * @property fragmentSrc
+     * @type Array
+     */
+    this.fragmentSrc = [
+
+        'precision mediump float;',
+
+        'varying vec4 vColor;',
+
+        'void main(void) {',
+        '   gl_FragColor = vColor;',
+        '}'
+    ];
+
+    /**
+     * The vertex shader.
+     * @property vertexSrc
+     * @type Array
+     */
+    this.vertexSrc  = [
+        'attribute vec2 aVertexPosition;',
+        //'attribute vec4 aColor;',
+        'uniform mat3 translationMatrix;',
+        'uniform vec2 projectionVector;',
+        'uniform vec2 offsetVector;',
+        
+        'uniform vec3 tint;',
+        'uniform float alpha;',
+        'uniform vec3 color;',
+        'uniform float flipY;',
+        'varying vec4 vColor;',
+
+        'void main(void) {',
+        '   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
+        '   v -= offsetVector.xyx;',
+        '   gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);',
+        '   vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);',
+        '}'
+    ];
+
+    this.init();
+};
+
+PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader;
+
+/**
+* Initialises the shader.
+* 
+* @method init
+*/
+PIXI.ComplexPrimitiveShader.prototype.init = function()
+{
+    var gl = this.gl;
+
+    var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
+    gl.useProgram(program);
+
+    // get and store the uniforms for the shader
+    this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
+    this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
+    this.tintColor = gl.getUniformLocation(program, 'tint');
+    this.color = gl.getUniformLocation(program, 'color');
+    this.flipY = gl.getUniformLocation(program, 'flipY');
+
+    // get and store the attributes
+    this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
+   // this.colorAttribute = gl.getAttribLocation(program, 'aColor');
+
+    this.attributes = [this.aVertexPosition, this.colorAttribute];
+
+    this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
+    this.alpha = gl.getUniformLocation(program, 'alpha');
+
+    this.program = program;
+};
+
+/**
+* Destroys the shader.
+* 
+* @method destroy
+*/
+PIXI.ComplexPrimitiveShader.prototype.destroy = function()
+{
+    this.gl.deleteProgram( this.program );
+    this.uniforms = null;
+    this.gl = null;
+
+    this.attribute = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * A set of functions used by the webGL renderer to draw the primitive graphics data
+ *
+ * @class WebGLGraphics
+ * @private
+ * @static
+ */
+PIXI.WebGLGraphics = function()
+{
+};
+
+/**
+ * Renders the graphics object
+ *
+ * @static
+ * @private
+ * @method renderGraphics
+ * @param graphics {Graphics}
+ * @param renderSession {Object}
+ */
+PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset)
+{
+    var gl = renderSession.gl;
+    var projection = renderSession.projection,
+        offset = renderSession.offset,
+        shader = renderSession.shaderManager.primitiveShader,
+        webGLData;
+
+    if(graphics.dirty)
+    {
+        PIXI.WebGLGraphics.updateGraphics(graphics, gl);
+    }
+
+    var webGL = graphics._webGL[gl.id];
+
+    // This  could be speeded up for sure!
+
+    for (var i = 0; i < webGL.data.length; i++)
+    {
+        if(webGL.data[i].mode === 1)
+        {
+            webGLData = webGL.data[i];
+
+            renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession);
+
+            // render quad..
+            gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
+            
+            renderSession.stencilManager.popStencil(graphics, webGLData, renderSession);
+        }
+        else
+        {
+            webGLData = webGL.data[i];
+           
+
+            renderSession.shaderManager.setShader( shader );//activatePrimitiveShader();
+            shader = renderSession.shaderManager.primitiveShader;
+            gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
+            
+            gl.uniform1f(shader.flipY, 1);
+            
+            gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
+            gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
+
+            gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
+
+            gl.uniform1f(shader.alpha, graphics.worldAlpha);
+            
+
+            gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
+
+            gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
+            gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
+
+            // set the index buffer!
+            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
+            gl.drawElements(gl.TRIANGLE_STRIP,  webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
+        }
+    }
+};
+
+/**
+ * Updates the graphics object
+ *
+ * @static
+ * @private
+ * @method updateGraphics
+ * @param graphicsData {Graphics} The graphics object to update
+ * @param gl {WebGLContext} the current WebGL drawing context
+ */
+PIXI.WebGLGraphics.updateGraphics = function(graphics, gl)
+{
+    // get the contexts graphics object
+    var webGL = graphics._webGL[gl.id];
+    // if the graphics object does not exist in the webGL context time to create it!
+    if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl};
+
+    // flag the graphics as not dirty as we are about to update it...
+    graphics.dirty = false;
+
+    var i;
+
+    // if the user cleared the graphics object we will need to clear every object
+    if(graphics.clearDirty)
+    {
+        graphics.clearDirty = false;
+
+        // lop through and return all the webGLDatas to the object pool so than can be reused later on
+        for (i = 0; i < webGL.data.length; i++)
+        {
+            var graphicsData = webGL.data[i];
+            graphicsData.reset();
+            PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData );
+        }
+
+        // clear the array and reset the index.. 
+        webGL.data = [];
+        webGL.lastIndex = 0;
+    }
+    
+    var webGLData;
+    
+    // loop through the graphics datas and construct each one..
+    // if the object is a complex fill then the new stencil buffer technique will be used
+    // other wise graphics objects will be pushed into a batch..
+    for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++)
+    {
+        var data = graphics.graphicsData[i];
+
+        if(data.type === PIXI.Graphics.POLY)
+        {
+            // need to add the points the the graphics object..
+            data.points = data.shape.points.slice();
+            if(data.shape.closed)
+            {
+                // close the poly if the value is true!
+                if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1])
+                {
+                    data.points.push(data.points[0], data.points[1]);
+                }
+            }
+
+            // MAKE SURE WE HAVE THE CORRECT TYPE..
+            if(data.fill)
+            {
+                if(data.points.length >= 6)
+                {
+                    if(data.points.length < 6 * 2)
+                    {
+                        webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
+                        
+                        var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData);
+                   //     console.log(canDrawUsingSimple);
+
+                        if(!canDrawUsingSimple)
+                        {
+                        //    console.log("<>>>")
+                            webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
+                            PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
+                        }
+                        
+                    }
+                    else
+                    {
+                        webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
+                        PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
+                    }
+                }
+            }
+
+            if(data.lineWidth > 0)
+            {
+                webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
+                PIXI.WebGLGraphics.buildLine(data, webGLData);
+
+            }
+        }
+        else
+        {
+            webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
+            
+            if(data.type === PIXI.Graphics.RECT)
+            {
+                PIXI.WebGLGraphics.buildRectangle(data, webGLData);
+            }
+            else if(data.type === PIXI.Graphics.CIRC || data.type === PIXI.Graphics.ELIP)
+            {
+                PIXI.WebGLGraphics.buildCircle(data, webGLData);
+            }
+            else if(data.type === PIXI.Graphics.RREC)
+            {
+                PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData);
+            }
+        }
+
+        webGL.lastIndex++;
+    }
+
+    // upload all the dirty data...
+    for (i = 0; i < webGL.data.length; i++)
+    {
+        webGLData = webGL.data[i];
+        if(webGLData.dirty)webGLData.upload();
+    }
+};
+
+/**
+ * @static
+ * @private
+ * @method switchMode
+ * @param webGL {WebGLContext}
+ * @param type {Number}
+ */
+PIXI.WebGLGraphics.switchMode = function(webGL, type)
+{
+    var webGLData;
+
+    if(!webGL.data.length)
+    {
+        webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
+        webGLData.mode = type;
+        webGL.data.push(webGLData);
+    }
+    else
+    {
+        webGLData = webGL.data[webGL.data.length-1];
+
+        if(webGLData.mode !== type || type === 1)
+        {
+            webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
+            webGLData.mode = type;
+            webGL.data.push(webGLData);
+        }
+    }
+
+    webGLData.dirty = true;
+
+    return webGLData;
+};
+
+/**
+ * Builds a rectangle to draw
+ *
+ * @static
+ * @private
+ * @method buildRectangle
+ * @param graphicsData {Graphics} The graphics object containing all the necessary properties
+ * @param webGLData {Object}
+ */
+PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData)
+{
+    // --- //
+    // need to convert points to a nice regular data
+    //
+    var rectData = graphicsData.shape;
+    var x = rectData.x;
+    var y = rectData.y;
+    var width = rectData.width;
+    var height = rectData.height;
+
+    if(graphicsData.fill)
+    {
+        var color = PIXI.hex2rgb(graphicsData.fillColor);
+        var alpha = graphicsData.fillAlpha;
+
+        var r = color[0] * alpha;
+        var g = color[1] * alpha;
+        var b = color[2] * alpha;
+
+        var verts = webGLData.points;
+        var indices = webGLData.indices;
+
+        var vertPos = verts.length/6;
+
+        // start
+        verts.push(x, y);
+        verts.push(r, g, b, alpha);
+
+        verts.push(x + width, y);
+        verts.push(r, g, b, alpha);
+
+        verts.push(x , y + height);
+        verts.push(r, g, b, alpha);
+
+        verts.push(x + width, y + height);
+        verts.push(r, g, b, alpha);
+
+        // insert 2 dead triangles..
+        indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3);
+    }
+
+    if(graphicsData.lineWidth)
+    {
+        var tempPoints = graphicsData.points;
+
+        graphicsData.points = [x, y,
+                  x + width, y,
+                  x + width, y + height,
+                  x, y + height,
+                  x, y];
+
+
+        PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
+
+        graphicsData.points = tempPoints;
+    }
+};
+
+/**
+ * Builds a rounded rectangle to draw
+ *
+ * @static
+ * @private
+ * @method buildRoundedRectangle
+ * @param graphicsData {Graphics} The graphics object containing all the necessary properties
+ * @param webGLData {Object}
+ */
+PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData)
+{
+    var rrectData = graphicsData.shape;
+    var x = rrectData.x;
+    var y = rrectData.y;
+    var width = rrectData.width;
+    var height = rrectData.height;
+
+    var radius = rrectData.radius;
+
+    var recPoints = [];
+    recPoints.push(x, y + radius);
+    recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height));
+    recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius));
+    recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y));
+    recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius));
+
+    if (graphicsData.fill) {
+        var color = PIXI.hex2rgb(graphicsData.fillColor);
+        var alpha = graphicsData.fillAlpha;
+
+        var r = color[0] * alpha;
+        var g = color[1] * alpha;
+        var b = color[2] * alpha;
+
+        var verts = webGLData.points;
+        var indices = webGLData.indices;
+
+        var vecPos = verts.length/6;
+
+        var triangles = PIXI.PolyK.Triangulate(recPoints);
+
+        // 
+        
+        var i = 0;
+        for (i = 0; i < triangles.length; i+=3)
+        {
+            indices.push(triangles[i] + vecPos);
+            indices.push(triangles[i] + vecPos);
+            indices.push(triangles[i+1] + vecPos);
+            indices.push(triangles[i+2] + vecPos);
+            indices.push(triangles[i+2] + vecPos);
+        }
+
+
+        for (i = 0; i < recPoints.length; i++)
+        {
+            verts.push(recPoints[i], recPoints[++i], r, g, b, alpha);
+        }
+    }
+
+    if (graphicsData.lineWidth) {
+        var tempPoints = graphicsData.points;
+
+        graphicsData.points = recPoints;
+
+        PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
+
+        graphicsData.points = tempPoints;
+    }
+};
+
+/**
+ * Calculate the points for a quadratic bezier curve. (helper function..)
+ * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
+ *
+ * @static
+ * @private
+ * @method quadraticBezierCurve
+ * @param fromX {Number} Origin point x
+ * @param fromY {Number} Origin point x
+ * @param cpX {Number} Control point x
+ * @param cpY {Number} Control point y
+ * @param toX {Number} Destination point x
+ * @param toY {Number} Destination point y
+ * @return {Array(Number)}
+ */
+PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) {
+
+    var xa,
+        ya,
+        xb,
+        yb,
+        x,
+        y,
+        n = 20,
+        points = [];
+
+    function getPt(n1 , n2, perc) {
+        var diff = n2 - n1;
+
+        return n1 + ( diff * perc );
+    }
+
+    var j = 0;
+    for (var i = 0; i <= n; i++ )
+    {
+        j = i / n;
+
+        // The Green Line
+        xa = getPt( fromX , cpX , j );
+        ya = getPt( fromY , cpY , j );
+        xb = getPt( cpX , toX , j );
+        yb = getPt( cpY , toY , j );
+
+        // The Black Dot
+        x = getPt( xa , xb , j );
+        y = getPt( ya , yb , j );
+
+        points.push(x, y);
+    }
+    return points;
+};
+
+/**
+ * Builds a circle to draw
+ *
+ * @static
+ * @private
+ * @method buildCircle
+ * @param graphicsData {Graphics} The graphics object to draw
+ * @param webGLData {Object}
+ */
+PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData)
+{
+    // need to convert points to a nice regular data
+    var circleData = graphicsData.shape;
+    var x = circleData.x;
+    var y = circleData.y;
+    var width;
+    var height;
+    
+    // TODO - bit hacky??
+    if(graphicsData.type === PIXI.Graphics.CIRC)
+    {
+        width = circleData.radius;
+        height = circleData.radius;
+    }
+    else
+    {
+        width = circleData.width;
+        height = circleData.height;
+    }
+
+    var totalSegs = 40;
+    var seg = (Math.PI * 2) / totalSegs ;
+
+    var i = 0;
+
+    if(graphicsData.fill)
+    {
+        var color = PIXI.hex2rgb(graphicsData.fillColor);
+        var alpha = graphicsData.fillAlpha;
+
+        var r = color[0] * alpha;
+        var g = color[1] * alpha;
+        var b = color[2] * alpha;
+
+        var verts = webGLData.points;
+        var indices = webGLData.indices;
+
+        var vecPos = verts.length/6;
+
+        indices.push(vecPos);
+
+        for (i = 0; i < totalSegs + 1 ; i++)
+        {
+            verts.push(x,y, r, g, b, alpha);
+
+            verts.push(x + Math.sin(seg * i) * width,
+                       y + Math.cos(seg * i) * height,
+                       r, g, b, alpha);
+
+            indices.push(vecPos++, vecPos++);
+        }
+
+        indices.push(vecPos-1);
+    }
+
+    if(graphicsData.lineWidth)
+    {
+        var tempPoints = graphicsData.points;
+
+        graphicsData.points = [];
+
+        for (i = 0; i < totalSegs + 1; i++)
+        {
+            graphicsData.points.push(x + Math.sin(seg * i) * width,
+                                     y + Math.cos(seg * i) * height);
+        }
+
+        PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
+
+        graphicsData.points = tempPoints;
+    }
+};
+
+/**
+ * Builds a line to draw
+ *
+ * @static
+ * @private
+ * @method buildLine
+ * @param graphicsData {Graphics} The graphics object containing all the necessary properties
+ * @param webGLData {Object}
+ */
+PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData)
+{
+    // TODO OPTIMISE!
+    var i = 0;
+    var points = graphicsData.points;
+    if(points.length === 0)return;
+
+    // if the line width is an odd number add 0.5 to align to a whole pixel
+    if(graphicsData.lineWidth%2)
+    {
+        for (i = 0; i < points.length; i++) {
+            points[i] += 0.5;
+        }
+    }
+
+    // get first and last point.. figure out the middle!
+    var firstPoint = new PIXI.Point( points[0], points[1] );
+    var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
+
+    // if the first point is the last point - gonna have issues :)
+    if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y)
+    {
+        // need to clone as we are going to slightly modify the shape..
+        points = points.slice();
+
+        points.pop();
+        points.pop();
+
+        lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
+
+        var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5;
+        var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5;
+
+        points.unshift(midPointX, midPointY);
+        points.push(midPointX, midPointY);
+    }
+
+    var verts = webGLData.points;
+    var indices = webGLData.indices;
+    var length = points.length / 2;
+    var indexCount = points.length;
+    var indexStart = verts.length/6;
+
+    // DRAW the Line
+    var width = graphicsData.lineWidth / 2;
+
+    // sort color
+    var color = PIXI.hex2rgb(graphicsData.lineColor);
+    var alpha = graphicsData.lineAlpha;
+    var r = color[0] * alpha;
+    var g = color[1] * alpha;
+    var b = color[2] * alpha;
+
+    var px, py, p1x, p1y, p2x, p2y, p3x, p3y;
+    var perpx, perpy, perp2x, perp2y, perp3x, perp3y;
+    var a1, b1, c1, a2, b2, c2;
+    var denom, pdist, dist;
+
+    p1x = points[0];
+    p1y = points[1];
+
+    p2x = points[2];
+    p2y = points[3];
+
+    perpx = -(p1y - p2y);
+    perpy =  p1x - p2x;
+
+    dist = Math.sqrt(perpx*perpx + perpy*perpy);
+
+    perpx /= dist;
+    perpy /= dist;
+    perpx *= width;
+    perpy *= width;
+
+    // start
+    verts.push(p1x - perpx , p1y - perpy,
+                r, g, b, alpha);
+
+    verts.push(p1x + perpx , p1y + perpy,
+                r, g, b, alpha);
+
+    for (i = 1; i < length-1; i++)
+    {
+        p1x = points[(i-1)*2];
+        p1y = points[(i-1)*2 + 1];
+
+        p2x = points[(i)*2];
+        p2y = points[(i)*2 + 1];
+
+        p3x = points[(i+1)*2];
+        p3y = points[(i+1)*2 + 1];
+
+        perpx = -(p1y - p2y);
+        perpy = p1x - p2x;
+
+        dist = Math.sqrt(perpx*perpx + perpy*perpy);
+        perpx /= dist;
+        perpy /= dist;
+        perpx *= width;
+        perpy *= width;
+
+        perp2x = -(p2y - p3y);
+        perp2y = p2x - p3x;
+
+        dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y);
+        perp2x /= dist;
+        perp2y /= dist;
+        perp2x *= width;
+        perp2y *= width;
+
+        a1 = (-perpy + p1y) - (-perpy + p2y);
+        b1 = (-perpx + p2x) - (-perpx + p1x);
+        c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y);
+        a2 = (-perp2y + p3y) - (-perp2y + p2y);
+        b2 = (-perp2x + p2x) - (-perp2x + p3x);
+        c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y);
+
+        denom = a1*b2 - a2*b1;
+
+        if(Math.abs(denom) < 0.1 )
+        {
+
+            denom+=10.1;
+            verts.push(p2x - perpx , p2y - perpy,
+                r, g, b, alpha);
+
+            verts.push(p2x + perpx , p2y + perpy,
+                r, g, b, alpha);
+
+            continue;
+        }
+
+        px = (b1*c2 - b2*c1)/denom;
+        py = (a2*c1 - a1*c2)/denom;
+
+
+        pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y);
+
+
+        if(pdist > 140 * 140)
+        {
+            perp3x = perpx - perp2x;
+            perp3y = perpy - perp2y;
+
+            dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y);
+            perp3x /= dist;
+            perp3y /= dist;
+            perp3x *= width;
+            perp3y *= width;
+
+            verts.push(p2x - perp3x, p2y -perp3y);
+            verts.push(r, g, b, alpha);
+
+            verts.push(p2x + perp3x, p2y +perp3y);
+            verts.push(r, g, b, alpha);
+
+            verts.push(p2x - perp3x, p2y -perp3y);
+            verts.push(r, g, b, alpha);
+
+            indexCount++;
+        }
+        else
+        {
+
+            verts.push(px , py);
+            verts.push(r, g, b, alpha);
+
+            verts.push(p2x - (px-p2x), p2y - (py - p2y));
+            verts.push(r, g, b, alpha);
+        }
+    }
+
+    p1x = points[(length-2)*2];
+    p1y = points[(length-2)*2 + 1];
+
+    p2x = points[(length-1)*2];
+    p2y = points[(length-1)*2 + 1];
+
+    perpx = -(p1y - p2y);
+    perpy = p1x - p2x;
+
+    dist = Math.sqrt(perpx*perpx + perpy*perpy);
+    perpx /= dist;
+    perpy /= dist;
+    perpx *= width;
+    perpy *= width;
+
+    verts.push(p2x - perpx , p2y - perpy);
+    verts.push(r, g, b, alpha);
+
+    verts.push(p2x + perpx , p2y + perpy);
+    verts.push(r, g, b, alpha);
+
+    indices.push(indexStart);
+
+    for (i = 0; i < indexCount; i++)
+    {
+        indices.push(indexStart++);
+    }
+
+    indices.push(indexStart-1);
+};
+
+/**
+ * Builds a complex polygon to draw
+ *
+ * @static
+ * @private
+ * @method buildComplexPoly
+ * @param graphicsData {Graphics} The graphics object containing all the necessary properties
+ * @param webGLData {Object}
+ */
+PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData)
+{
+    //TODO - no need to copy this as it gets turned into a FLoat32Array anyways..
+    var points = graphicsData.points.slice();
+    if(points.length < 6)return;
+
+    // get first and last point.. figure out the middle!
+    var indices = webGLData.indices;
+    webGLData.points = points;
+    webGLData.alpha = graphicsData.fillAlpha;
+    webGLData.color = PIXI.hex2rgb(graphicsData.fillColor);
+
+    /*
+        calclate the bounds..
+    */
+    var minX = Infinity;
+    var maxX = -Infinity;
+
+    var minY = Infinity;
+    var maxY = -Infinity;
+
+    var x,y;
+
+    // get size..
+    for (var i = 0; i < points.length; i+=2)
+    {
+        x = points[i];
+        y = points[i+1];
+
+        minX = x < minX ? x : minX;
+        maxX = x > maxX ? x : maxX;
+
+        minY = y < minY ? y : minY;
+        maxY = y > maxY ? y : maxY;
+    }
+
+    // add a quad to the end cos there is no point making another buffer!
+    points.push(minX, minY,
+                maxX, minY,
+                maxX, maxY,
+                minX, maxY);
+
+    // push a quad onto the end.. 
+    
+    //TODO - this aint needed!
+    var length = points.length / 2;
+    for (i = 0; i < length; i++)
+    {
+        indices.push( i );
+    }
+
+};
+
+/**
+ * Builds a polygon to draw
+ *
+ * @static
+ * @private
+ * @method buildPoly
+ * @param graphicsData {Graphics} The graphics object containing all the necessary properties
+ * @param webGLData {Object}
+ */
+PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData)
+{
+    var points = graphicsData.points;
+
+    if(points.length < 6)return;
+    // get first and last point.. figure out the middle!
+    var verts = webGLData.points;
+    var indices = webGLData.indices;
+
+    var length = points.length / 2;
+
+    // sort color
+    var color = PIXI.hex2rgb(graphicsData.fillColor);
+    var alpha = graphicsData.fillAlpha;
+    var r = color[0] * alpha;
+    var g = color[1] * alpha;
+    var b = color[2] * alpha;
+
+    var triangles = PIXI.PolyK.Triangulate(points);
+
+    if(!triangles)return false;
+
+    var vertPos = verts.length / 6;
+
+    var i = 0;
+
+    for (i = 0; i < triangles.length; i+=3)
+    {
+        indices.push(triangles[i] + vertPos);
+        indices.push(triangles[i] + vertPos);
+        indices.push(triangles[i+1] + vertPos);
+        indices.push(triangles[i+2] +vertPos);
+        indices.push(triangles[i+2] + vertPos);
+    }
+
+    for (i = 0; i < length; i++)
+    {
+        verts.push(points[i * 2], points[i * 2 + 1],
+                   r, g, b, alpha);
+    }
+
+    return true;
+};
+
+PIXI.WebGLGraphics.graphicsDataPool = [];
+
+/**
+ * @class WebGLGraphicsData
+ * @private
+ * @static
+ */
+PIXI.WebGLGraphicsData = function(gl)
+{
+    this.gl = gl;
+
+    //TODO does this need to be split before uploding??
+    this.color = [0,0,0]; // color split!
+    this.points = [];
+    this.indices = [];
+    this.buffer = gl.createBuffer();
+    this.indexBuffer = gl.createBuffer();
+    this.mode = 1;
+    this.alpha = 1;
+    this.dirty = true;
+};
+
+/**
+ * @method reset
+ */
+PIXI.WebGLGraphicsData.prototype.reset = function()
+{
+    this.points = [];
+    this.indices = [];
+};
+
+/**
+ * @method upload
+ */
+PIXI.WebGLGraphicsData.prototype.upload = function()
+{
+    var gl = this.gl;
+
+//    this.lastIndex = graphics.graphicsData.length;
+    this.glPoints = new PIXI.Float32Array(this.points);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW);
+
+    this.glIndicies = new PIXI.Uint16Array(this.indices);
+
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW);
+
+    this.dirty = false;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+PIXI.glContexts = []; // this is where we store the webGL contexts for easy access.
+PIXI.instances = [];
+
+/**
+ * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer
+ * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs.
+ * So no need for Sprite Batches or Sprite Clouds.
+ * Don't forget to add the view to your DOM or you will not see anything :)
+ *
+ * @class WebGLRenderer
+ * @constructor
+ * @param [width=0] {Number} the width of the canvas view
+ * @param [height=0] {Number} the height of the canvas view
+ * @param [options] {Object} The optional renderer parameters
+ * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional
+ * @param [options.transparent=false] {Boolean} If the render view is transparent, default false
+ * @param [options.autoResize=false] {Boolean} If the render view is automatically resized, default false
+ * @param [options.antialias=false] {Boolean} sets antialias (only applicable in chrome at the moment)
+ * @param [options.preserveDrawingBuffer=false] {Boolean} enables drawing buffer preservation, enable this if you need to call toDataUrl on the webgl context
+ * @param [options.resolution=1] {Number} the resolution of the renderer retina would be 2
+ */
+PIXI.WebGLRenderer = function(width, height, options)
+{
+    if(options)
+    {
+        for (var i in PIXI.defaultRenderOptions)
+        {
+            if (options[i] === undefined) options[i] = PIXI.defaultRenderOptions[i];
+        }
+    }
+    else
+    {
+        options = PIXI.defaultRenderOptions;
+    }
+
+    if(!PIXI.defaultRenderer)
+    {
+        PIXI.defaultRenderer = this;
+    }
+
+    /**
+     * @property type
+     * @type Number
+     */
+    this.type = PIXI.WEBGL_RENDERER;
+
+    /**
+     * The resolution of the renderer
+     *
+     * @property resolution
+     * @type Number
+     * @default 1
+     */
+    this.resolution = options.resolution;
+
+    // do a catch.. only 1 webGL renderer..
+
+    /**
+     * Whether the render view is transparent
+     *
+     * @property transparent
+     * @type Boolean
+     */
+    this.transparent = options.transparent;
+
+    /**
+     * Whether the render view should be resized automatically
+     *
+     * @property autoResize
+     * @type Boolean
+     */
+    this.autoResize = options.autoResize || false;
+
+    /**
+     * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
+     *
+     * @property preserveDrawingBuffer
+     * @type Boolean
+     */
+    this.preserveDrawingBuffer = options.preserveDrawingBuffer;
+
+    /**
+     * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true:
+     * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0).
+     * If the Stage is transparent, Pixi will clear to the target Stage's background color.
+     * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set.
+     *
+     * @property clearBeforeRender
+     * @type Boolean
+     * @default
+     */
+    this.clearBeforeRender = options.clearBeforeRender;
+
+    /**
+     * The width of the canvas view
+     *
+     * @property width
+     * @type Number
+     * @default 800
+     */
+    this.width = width || 800;
+
+    /**
+     * The height of the canvas view
+     *
+     * @property height
+     * @type Number
+     * @default 600
+     */
+    this.height = height || 600;
+
+    /**
+     * The canvas element that everything is drawn to
+     *
+     * @property view
+     * @type HTMLCanvasElement
+     */
+    this.view = options.view || document.createElement('canvas');
+
+    /**
+     * @property _contextOptions
+     * @type Object
+     * @private
+     */
+    this._contextOptions = {
+        alpha: this.transparent,
+        antialias: options.antialias, // SPEED UP??
+        premultipliedAlpha:this.transparent && this.transparent !== 'notMultiplied',
+        stencil:true,
+        preserveDrawingBuffer: options.preserveDrawingBuffer
+    };
+
+    /**
+     * @property projection
+     * @type Point
+     */
+    this.projection = new PIXI.Point();
+
+    /**
+     * @property offset
+     * @type Point
+     */
+    this.offset = new PIXI.Point(0, 0);
+
+    // time to create the render managers! each one focuses on managing a state in webGL
+
+    /**
+     * Deals with managing the shader programs and their attribs
+     * @property shaderManager
+     * @type WebGLShaderManager
+     */
+    this.shaderManager = new PIXI.WebGLShaderManager();
+
+    /**
+     * Manages the rendering of sprites
+     * @property spriteBatch
+     * @type WebGLSpriteBatch
+     */
+    this.spriteBatch = new PIXI.WebGLSpriteBatch();
+
+    /**
+     * Manages the masks using the stencil buffer
+     * @property maskManager
+     * @type WebGLMaskManager
+     */
+    this.maskManager = new PIXI.WebGLMaskManager();
+
+    /**
+     * Manages the filters
+     * @property filterManager
+     * @type WebGLFilterManager
+     */
+    this.filterManager = new PIXI.WebGLFilterManager();
+
+    /**
+     * Manages the stencil buffer
+     * @property stencilManager
+     * @type WebGLStencilManager
+     */
+    this.stencilManager = new PIXI.WebGLStencilManager();
+
+    /**
+     * Manages the blendModes
+     * @property blendModeManager
+     * @type WebGLBlendModeManager
+     */
+    this.blendModeManager = new PIXI.WebGLBlendModeManager();
+
+    /**
+     * TODO remove
+     * @property renderSession
+     * @type Object
+     */
+    this.renderSession = {};
+    this.renderSession.gl = this.gl;
+    this.renderSession.drawCount = 0;
+    this.renderSession.shaderManager = this.shaderManager;
+    this.renderSession.maskManager = this.maskManager;
+    this.renderSession.filterManager = this.filterManager;
+    this.renderSession.blendModeManager = this.blendModeManager;
+    this.renderSession.spriteBatch = this.spriteBatch;
+    this.renderSession.stencilManager = this.stencilManager;
+    this.renderSession.renderer = this;
+    this.renderSession.resolution = this.resolution;
+
+    // time init the context..
+    this.initContext();
+
+    // map some webGL blend modes..
+    this.mapBlendModes();
+};
+
+// constructor
+PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer;
+
+/**
+* @method initContext
+*/
+PIXI.WebGLRenderer.prototype.initContext = function()
+{
+    var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions);
+    this.gl = gl;
+
+    if (!gl) {
+        // fail, not able to get a context
+        throw new Error('This browser does not support webGL. Try using the canvas renderer');
+    }
+
+    this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++;
+
+    PIXI.glContexts[this.glContextId] = gl;
+
+    PIXI.instances[this.glContextId] = this;
+
+    // set up the default pixi settings..
+    gl.disable(gl.DEPTH_TEST);
+    gl.disable(gl.CULL_FACE);
+    gl.enable(gl.BLEND);
+
+    // need to set the context for all the managers...
+    this.shaderManager.setContext(gl);
+    this.spriteBatch.setContext(gl);
+    this.maskManager.setContext(gl);
+    this.filterManager.setContext(gl);
+    this.blendModeManager.setContext(gl);
+    this.stencilManager.setContext(gl);
+
+    this.renderSession.gl = this.gl;
+
+    // now resize and we are good to go!
+    this.resize(this.width, this.height);
+};
+
+/**
+ * Renders the stage to its webGL view
+ *
+ * @method render
+ * @param stage {Stage} the Stage element to be rendered
+ */
+PIXI.WebGLRenderer.prototype.render = function(stage)
+{
+    // no point rendering if our context has been blown up!
+    if (this.contextLost) return;
+
+    // if rendering a new stage clear the batches..
+    if (this.__stage !== stage)
+    {
+        // TODO make this work
+        // dont think this is needed any more?
+        this.__stage = stage;
+    }
+
+    // update the scene graph
+    stage.updateTransform();
+
+    var gl = this.gl;
+
+    // -- Does this need to be set every frame? -- //
+    gl.viewport(0, 0, this.width, this.height);
+
+    // make sure we are bound to the main frame buffer
+    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+
+    if (this.clearBeforeRender)
+    {
+        if (this.transparent)
+        {
+            gl.clearColor(0, 0, 0, 0);
+        }
+        else
+        {
+            gl.clearColor(stage.backgroundColorSplit[0],stage.backgroundColorSplit[1],stage.backgroundColorSplit[2], 1);
+        }
+
+        gl.clear (gl.COLOR_BUFFER_BIT);
+    }
+
+    this.renderDisplayObject( stage, this.projection );
+};
+
+/**
+ * Renders a Display Object.
+ *
+ * @method renderDisplayObject
+ * @param displayObject {DisplayObject} The DisplayObject to render
+ * @param projection {Point} The projection
+ * @param buffer {Array} a standard WebGL buffer
+ */
+PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix)
+{
+    this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL);
+
+    // reset the render session data..
+    this.renderSession.drawCount = 0;
+
+    // make sure to flip the Y if using a render texture..
+    this.renderSession.flipY = buffer ? -1 : 1;
+
+    // set the default projection
+    this.renderSession.projection = projection;
+
+    //set the default offset
+    this.renderSession.offset = this.offset;
+
+    // start the sprite batch
+    this.spriteBatch.begin(this.renderSession);
+
+    // start the filter manager
+    this.filterManager.begin(this.renderSession, buffer);
+
+    // render the scene!
+    displayObject._renderWebGL(this.renderSession, matrix);
+
+    // finish the sprite batch
+    this.spriteBatch.end();
+};
+
+/**
+ * Resizes the webGL view to the specified width and height.
+ *
+ * @method resize
+ * @param width {Number} the new width of the webGL view
+ * @param height {Number} the new height of the webGL view
+ */
+PIXI.WebGLRenderer.prototype.resize = function(width, height)
+{
+    this.width = width * this.resolution;
+    this.height = height * this.resolution;
+
+    this.view.width = this.width;
+    this.view.height = this.height;
+
+    if (this.autoResize) {
+        this.view.style.width = this.width / this.resolution + 'px';
+        this.view.style.height = this.height / this.resolution + 'px';
+    }
+
+    this.gl.viewport(0, 0, this.width, this.height);
+
+    this.projection.x =  this.width / 2 / this.resolution;
+    this.projection.y =  -this.height / 2 / this.resolution;
+};
+
+/**
+ * Updates and Creates a WebGL texture for the renderers context.
+ *
+ * @method updateTexture
+ * @param texture {Texture} the texture to update
+ */
+PIXI.WebGLRenderer.prototype.updateTexture = function(texture)
+{
+    if (!texture.hasLoaded)
+    {
+        return;
+    }
+
+    var gl = this.gl;
+
+    if (!texture._glTextures[gl.id])
+    {
+        texture._glTextures[gl.id] = gl.createTexture();
+    }
+
+    gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
+
+    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha);
+
+    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
+
+    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
+
+    if (texture.mipmap && PIXI.isPowerOfTwo(texture.width, texture.height))
+    {
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
+        gl.generateMipmap(gl.TEXTURE_2D);
+    }
+    else
+    {
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
+    }
+
+    if (!texture._powerOf2)
+    {
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+    }
+    else
+    {
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
+    }
+
+    texture._dirty[gl.id] = false;
+
+    return  texture._glTextures[gl.id];
+
+};
+
+/**
+ * Removes everything from the renderer (event listeners, spritebatch, etc...)
+ *
+ * @method destroy
+ */
+PIXI.WebGLRenderer.prototype.destroy = function()
+{
+    PIXI.glContexts[this.glContextId] = null;
+
+    this.projection = null;
+    this.offset = null;
+
+    this.shaderManager.destroy();
+    this.spriteBatch.destroy();
+    this.maskManager.destroy();
+    this.filterManager.destroy();
+
+    this.shaderManager = null;
+    this.spriteBatch = null;
+    this.maskManager = null;
+    this.filterManager = null;
+
+    this.gl = null;
+    this.renderSession = null;
+
+    PIXI.instances[this.glContextId] = null;
+
+    PIXI.WebGLRenderer.glContextId--;
+};
+
+/**
+ * Maps Pixi blend modes to WebGL blend modes.
+ *
+ * @method mapBlendModes
+ */
+PIXI.WebGLRenderer.prototype.mapBlendModes = function()
+{
+    var gl = this.gl;
+
+    if (!PIXI.blendModesWebGL)
+    {
+        PIXI.blendModesWebGL = [];
+
+        PIXI.blendModesWebGL[PIXI.blendModes.NORMAL]        = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.ADD]           = [gl.SRC_ALPHA, gl.DST_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.MULTIPLY]      = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.SCREEN]        = [gl.SRC_ALPHA, gl.ONE];
+        PIXI.blendModesWebGL[PIXI.blendModes.OVERLAY]       = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.DARKEN]        = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.LIGHTEN]       = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.COLOR_DODGE]   = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.COLOR_BURN]    = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.HARD_LIGHT]    = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.SOFT_LIGHT]    = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.DIFFERENCE]    = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.EXCLUSION]     = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.HUE]           = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.SATURATION]    = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.COLOR]         = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+        PIXI.blendModesWebGL[PIXI.blendModes.LUMINOSITY]    = [gl.ONE,       gl.ONE_MINUS_SRC_ALPHA];
+    }
+};
+
+PIXI.WebGLRenderer.glContextId = 0;
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class WebGLBlendModeManager
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.WebGLBlendModeManager = function()
+{
+    /**
+     * @property currentBlendMode
+     * @type Number
+     */
+    this.currentBlendMode = 99999;
+};
+
+PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager;
+
+/**
+ * Sets the WebGL Context.
+ *
+ * @method setContext
+ * @param gl {WebGLContext} the current WebGL drawing context
+ */
+PIXI.WebGLBlendModeManager.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+};
+
+/**
+* Sets-up the given blendMode from WebGL's point of view.
+* 
+* @method setBlendMode 
+* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD
+*/
+PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode)
+{
+    if(this.currentBlendMode === blendMode)return false;
+
+    this.currentBlendMode = blendMode;
+    
+    var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode];
+    this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
+    
+    return true;
+};
+
+/**
+* Destroys this object.
+* 
+* @method destroy
+*/
+PIXI.WebGLBlendModeManager.prototype.destroy = function()
+{
+    this.gl = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class WebGLMaskManager
+* @constructor
+* @private
+*/
+PIXI.WebGLMaskManager = function()
+{
+};
+
+PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager;
+
+/**
+* Sets the drawing context to the one given in parameter.
+* 
+* @method setContext 
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.WebGLMaskManager.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+};
+
+/**
+* Applies the Mask and adds it to the current filter stack.
+* 
+* @method pushMask
+* @param maskData {Array}
+* @param renderSession {Object}
+*/
+PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession)
+{
+    var gl = renderSession.gl;
+
+    if(maskData.dirty)
+    {
+        PIXI.WebGLGraphics.updateGraphics(maskData, gl);
+    }
+
+    if(!maskData._webGL[gl.id].data.length)return;
+
+    renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
+};
+
+/**
+* Removes the last filter from the filter stack and doesn't return it.
+* 
+* @method popMask
+* @param maskData {Array}
+* @param renderSession {Object} an object containing all the useful parameters
+*/
+PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession)
+{
+    var gl = this.gl;
+    renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
+};
+
+/**
+* Destroys the mask stack.
+* 
+* @method destroy
+*/
+PIXI.WebGLMaskManager.prototype.destroy = function()
+{
+    this.gl = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class WebGLStencilManager
+* @constructor
+* @private
+*/
+PIXI.WebGLStencilManager = function()
+{
+    this.stencilStack = [];
+    this.reverse = true;
+    this.count = 0;
+};
+
+/**
+* Sets the drawing context to the one given in parameter.
+* 
+* @method setContext 
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.WebGLStencilManager.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+};
+
+/**
+* Applies the Mask and adds it to the current filter stack.
+* 
+* @method pushMask
+* @param graphics {Graphics}
+* @param webGLData {Array}
+* @param renderSession {Object}
+*/
+PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession)
+{
+    var gl = this.gl;
+    this.bindGraphics(graphics, webGLData, renderSession);
+
+    if(this.stencilStack.length === 0)
+    {
+        gl.enable(gl.STENCIL_TEST);
+        gl.clear(gl.STENCIL_BUFFER_BIT);
+        this.reverse = true;
+        this.count = 0;
+    }
+
+    this.stencilStack.push(webGLData);
+
+    var level = this.count;
+
+    gl.colorMask(false, false, false, false);
+
+    gl.stencilFunc(gl.ALWAYS,0,0xFF);
+    gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
+
+    // draw the triangle strip!
+
+    if(webGLData.mode === 1)
+    {
+        gl.drawElements(gl.TRIANGLE_FAN,  webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
+       
+        if(this.reverse)
+        {
+            gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
+            gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
+        }
+        else
+        {
+            gl.stencilFunc(gl.EQUAL,level, 0xFF);
+            gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
+        }
+
+        // draw a quad to increment..
+        gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
+               
+        if(this.reverse)
+        {
+            gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
+        }
+        else
+        {
+            gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
+        }
+
+        this.reverse = !this.reverse;
+    }
+    else
+    {
+        if(!this.reverse)
+        {
+            gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
+            gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
+        }
+        else
+        {
+            gl.stencilFunc(gl.EQUAL,level, 0xFF);
+            gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
+        }
+
+        gl.drawElements(gl.TRIANGLE_STRIP,  webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
+
+        if(!this.reverse)
+        {
+            gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
+        }
+        else
+        {
+            gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
+        }
+    }
+
+    gl.colorMask(true, true, true, true);
+    gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
+
+    this.count++;
+};
+
+/**
+ * TODO this does not belong here!
+ * 
+ * @method bindGraphics
+ * @param graphics {Graphics}
+ * @param webGLData {Array}
+ * @param renderSession {Object}
+ */
+PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession)
+{
+    //if(this._currentGraphics === graphics)return;
+    this._currentGraphics = graphics;
+
+    var gl = this.gl;
+
+     // bind the graphics object..
+    var projection = renderSession.projection,
+        offset = renderSession.offset,
+        shader;// = renderSession.shaderManager.primitiveShader;
+
+    if(webGLData.mode === 1)
+    {
+        shader = renderSession.shaderManager.complexPrimitiveShader;
+
+        renderSession.shaderManager.setShader( shader );
+
+        gl.uniform1f(shader.flipY, renderSession.flipY);
+       
+        gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
+
+        gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
+        gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
+
+        gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
+        gl.uniform3fv(shader.color, webGLData.color);
+
+        gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha);
+
+        gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
+
+        gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0);
+
+
+        // now do the rest..
+        // set the index buffer!
+        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
+    }
+    else
+    {
+        //renderSession.shaderManager.activatePrimitiveShader();
+        shader = renderSession.shaderManager.primitiveShader;
+        renderSession.shaderManager.setShader( shader );
+
+        gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
+
+        gl.uniform1f(shader.flipY, renderSession.flipY);
+        gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
+        gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
+
+        gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
+
+        gl.uniform1f(shader.alpha, graphics.worldAlpha);
+        
+        gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
+
+        gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
+        gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
+
+        // set the index buffer!
+        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
+    }
+};
+
+/**
+ * @method popStencil
+ * @param graphics {Graphics}
+ * @param webGLData {Array}
+ * @param renderSession {Object}
+ */
+PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession)
+{
+	var gl = this.gl;
+    this.stencilStack.pop();
+   
+    this.count--;
+
+    if(this.stencilStack.length === 0)
+    {
+        // the stack is empty!
+        gl.disable(gl.STENCIL_TEST);
+
+    }
+    else
+    {
+
+        var level = this.count;
+
+        this.bindGraphics(graphics, webGLData, renderSession);
+
+        gl.colorMask(false, false, false, false);
+    
+        if(webGLData.mode === 1)
+        {
+            this.reverse = !this.reverse;
+
+            if(this.reverse)
+            {
+                gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
+                gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
+            }
+            else
+            {
+                gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
+                gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
+            }
+
+            // draw a quad to increment..
+            gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
+            
+            gl.stencilFunc(gl.ALWAYS,0,0xFF);
+            gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
+
+            // draw the triangle strip!
+            gl.drawElements(gl.TRIANGLE_FAN,  webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
+           
+            if(!this.reverse)
+            {
+                gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
+            }
+            else
+            {
+                gl.stencilFunc(gl.EQUAL,level, 0xFF);
+            }
+
+        }
+        else
+        {
+          //  console.log("<<>>")
+            if(!this.reverse)
+            {
+                gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
+                gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
+            }
+            else
+            {
+                gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
+                gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
+            }
+
+            gl.drawElements(gl.TRIANGLE_STRIP,  webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
+
+            if(!this.reverse)
+            {
+                gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
+            }
+            else
+            {
+                gl.stencilFunc(gl.EQUAL,level, 0xFF);
+            }
+        }
+
+        gl.colorMask(true, true, true, true);
+        gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
+
+
+    }
+};
+
+/**
+* Destroys the mask stack.
+* 
+* @method destroy
+*/
+PIXI.WebGLStencilManager.prototype.destroy = function()
+{
+    this.stencilStack = null;
+    this.gl = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class WebGLShaderManager
+* @constructor
+* @private
+*/
+PIXI.WebGLShaderManager = function()
+{
+    /**
+     * @property maxAttibs
+     * @type Number
+     */
+    this.maxAttibs = 10;
+
+    /**
+     * @property attribState
+     * @type Array
+     */
+    this.attribState = [];
+
+    /**
+     * @property tempAttribState
+     * @type Array
+     */
+    this.tempAttribState = [];
+
+    for (var i = 0; i < this.maxAttibs; i++)
+    {
+        this.attribState[i] = false;
+    }
+
+    /**
+     * @property stack
+     * @type Array
+     */
+    this.stack = [];
+
+};
+
+PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager;
+
+/**
+* Initialises the context and the properties.
+* 
+* @method setContext 
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.WebGLShaderManager.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+    
+    // the next one is used for rendering primitives
+    this.primitiveShader = new PIXI.PrimitiveShader(gl);
+
+    // the next one is used for rendering triangle strips
+    this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl);
+
+    // this shader is used for the default sprite rendering
+    this.defaultShader = new PIXI.PixiShader(gl);
+
+    // this shader is used for the fast sprite rendering
+    this.fastShader = new PIXI.PixiFastShader(gl);
+
+    // the next one is used for rendering triangle strips
+    this.stripShader = new PIXI.StripShader(gl);
+    this.setShader(this.defaultShader);
+};
+
+/**
+* Takes the attributes given in parameters.
+* 
+* @method setAttribs
+* @param attribs {Array} attribs 
+*/
+PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs)
+{
+    // reset temp state
+    var i;
+
+    for (i = 0; i < this.tempAttribState.length; i++)
+    {
+        this.tempAttribState[i] = false;
+    }
+
+    // set the new attribs
+    for (i = 0; i < attribs.length; i++)
+    {
+        var attribId = attribs[i];
+        this.tempAttribState[attribId] = true;
+    }
+
+    var gl = this.gl;
+
+    for (i = 0; i < this.attribState.length; i++)
+    {
+        if(this.attribState[i] !== this.tempAttribState[i])
+        {
+            this.attribState[i] = this.tempAttribState[i];
+
+            if(this.tempAttribState[i])
+            {
+                gl.enableVertexAttribArray(i);
+            }
+            else
+            {
+                gl.disableVertexAttribArray(i);
+            }
+        }
+    }
+};
+
+/**
+* Sets the current shader.
+* 
+* @method setShader
+* @param shader {Any}
+*/
+PIXI.WebGLShaderManager.prototype.setShader = function(shader)
+{
+    if(this._currentId === shader._UID)return false;
+    
+    this._currentId = shader._UID;
+
+    this.currentShader = shader;
+
+    this.gl.useProgram(shader.program);
+    this.setAttribs(shader.attributes);
+
+    return true;
+};
+
+/**
+* Destroys this object.
+* 
+* @method destroy
+*/
+PIXI.WebGLShaderManager.prototype.destroy = function()
+{
+    this.attribState = null;
+
+    this.tempAttribState = null;
+
+    this.primitiveShader.destroy();
+
+    this.complexPrimitiveShader.destroy();
+
+    this.defaultShader.destroy();
+
+    this.fastShader.destroy();
+
+    this.stripShader.destroy();
+
+    this.gl = null;
+};
+
+/**
+ * @author Mat Groves
+ * 
+ * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
+ * for creating the original pixi version!
+ * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer
+ * 
+ * Heavily inspired by LibGDX's WebGLSpriteBatch:
+ * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
+ */
+
+ /**
+ *
+ * @class WebGLSpriteBatch
+ * @private
+ * @constructor
+ */
+PIXI.WebGLSpriteBatch = function()
+{
+    /**
+     * @property vertSize
+     * @type Number
+     */
+    this.vertSize = 5;
+
+    /**
+     * The number of images in the SpriteBatch before it flushes
+     * @property size
+     * @type Number
+     */
+    this.size = 2000;//Math.pow(2, 16) /  this.vertSize;
+
+    //the total number of bytes in our batch
+    var numVerts = this.size * 4 * 4 * this.vertSize;
+    //the total number of indices in our batch
+    var numIndices = this.size * 6;
+
+    /**
+    * Holds the vertices
+    *
+    * @property vertices
+    * @type ArrayBuffer
+    */
+    this.vertices = new PIXI.ArrayBuffer(numVerts);
+
+    /**
+    * View on the vertices as a Float32Array
+    *
+    * @property positions
+    * @type Float32Array
+    */
+    this.positions = new PIXI.Float32Array(this.vertices);
+
+    /**
+    * View on the vertices as a Uint32Array
+    *
+    * @property colors
+    * @type Uint32Array
+    */
+    this.colors = new PIXI.Uint32Array(this.vertices);
+
+    /**
+     * Holds the indices
+     *
+     * @property indices
+     * @type Uint16Array
+     */
+    this.indices = new PIXI.Uint16Array(numIndices);
+    
+    /**
+     * @property lastIndexCount
+     * @type Number
+     */
+    this.lastIndexCount = 0;
+
+    for (var i=0, j=0; i < numIndices; i += 6, j += 4)
+    {
+        this.indices[i + 0] = j + 0;
+        this.indices[i + 1] = j + 1;
+        this.indices[i + 2] = j + 2;
+        this.indices[i + 3] = j + 0;
+        this.indices[i + 4] = j + 2;
+        this.indices[i + 5] = j + 3;
+    }
+
+    /**
+     * @property drawing
+     * @type Boolean
+     */
+    this.drawing = false;
+
+    /**
+     * @property currentBatchSize
+     * @type Number
+     */
+    this.currentBatchSize = 0;
+
+    /**
+     * @property currentBaseTexture
+     * @type BaseTexture
+     */
+    this.currentBaseTexture = null;
+
+    /**
+     * @property dirty
+     * @type Boolean
+     */
+    this.dirty = true;
+
+    /**
+     * @property textures
+     * @type Array
+     */
+    this.textures = [];
+
+    /**
+     * @property blendModes
+     * @type Array
+     */
+    this.blendModes = [];
+
+    /**
+     * @property shaders
+     * @type Array
+     */
+    this.shaders = [];
+
+    /**
+     * @property sprites
+     * @type Array
+     */
+    this.sprites = [];
+
+    /**
+     * @property defaultShader
+     * @type AbstractFilter
+     */
+    this.defaultShader = new PIXI.AbstractFilter([
+        'precision lowp float;',
+        'varying vec2 vTextureCoord;',
+        'varying vec4 vColor;',
+        'uniform sampler2D uSampler;',
+        'void main(void) {',
+        '   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
+        '}'
+    ]);
+};
+
+/**
+* @method setContext
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.WebGLSpriteBatch.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+
+    // create a couple of buffers
+    this.vertexBuffer = gl.createBuffer();
+    this.indexBuffer = gl.createBuffer();
+
+    // 65535 is max index, so 65535 / 6 = 10922.
+
+    //upload the index data
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
+
+    this.currentBlendMode = 99999;
+
+    var shader = new PIXI.PixiShader(gl);
+
+    shader.fragmentSrc = this.defaultShader.fragmentSrc;
+    shader.uniforms = {};
+    shader.init();
+
+    this.defaultShader.shaders[gl.id] = shader;
+};
+
+/**
+* @method begin
+* @param renderSession {Object} The RenderSession object
+*/
+PIXI.WebGLSpriteBatch.prototype.begin = function(renderSession)
+{
+    this.renderSession = renderSession;
+    this.shader = this.renderSession.shaderManager.defaultShader;
+
+    this.start();
+};
+
+/**
+* @method end
+*/
+PIXI.WebGLSpriteBatch.prototype.end = function()
+{
+    this.flush();
+};
+
+/**
+* @method render
+* @param sprite {Sprite} the sprite to render when using this spritebatch
+* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
+*/
+PIXI.WebGLSpriteBatch.prototype.render = function(sprite, matrix)
+{
+    var texture = sprite.texture;
+
+    //  They provided an alternative rendering matrix, so use it
+    var wt = sprite.worldTransform;
+
+    if (matrix)
+    {
+        wt = matrix;
+    }
+
+    // check texture..
+    if (this.currentBatchSize >= this.size)
+    {
+        this.flush();
+        this.currentBaseTexture = texture.baseTexture;
+    }
+
+    // get the uvs for the texture
+    var uvs = texture._uvs;
+
+    // if the uvs have not updated then no point rendering just yet!
+    if (!uvs)
+    {
+        return;
+    }
+
+    var aX = sprite.anchor.x;
+    var aY = sprite.anchor.y;
+
+    var w0, w1, h0, h1;
+        
+    if (texture.trim)
+    {
+        // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords.
+        var trim = texture.trim;
+
+        w1 = trim.x - aX * trim.width;
+        w0 = w1 + texture.crop.width;
+
+        h1 = trim.y - aY * trim.height;
+        h0 = h1 + texture.crop.height;
+    }
+    else
+    {
+        w0 = (texture.frame.width) * (1-aX);
+        w1 = (texture.frame.width) * -aX;
+
+        h0 = texture.frame.height * (1-aY);
+        h1 = texture.frame.height * -aY;
+    }
+
+    var i = this.currentBatchSize * 4 * this.vertSize;
+    var resolution = texture.baseTexture.resolution;
+
+    var a = wt.a / resolution;
+    var b = wt.b / resolution;
+    var c = wt.c / resolution;
+    var d = wt.d / resolution;
+    var tx = wt.tx;
+    var ty = wt.ty;
+
+    var colors = this.colors;
+    var positions = this.positions;
+
+    if (this.renderSession.roundPixels)
+    {
+        // xy
+        positions[i] = a * w1 + c * h1 + tx | 0;
+        positions[i+1] = d * h1 + b * w1 + ty | 0;
+
+        // xy
+        positions[i+5] = a * w0 + c * h1 + tx | 0;
+        positions[i+6] = d * h1 + b * w0 + ty | 0;
+
+         // xy
+        positions[i+10] = a * w0 + c * h0 + tx | 0;
+        positions[i+11] = d * h0 + b * w0 + ty | 0;
+
+        // xy
+        positions[i+15] = a * w1 + c * h0 + tx | 0;
+        positions[i+16] = d * h0 + b * w1 + ty | 0;
+    }
+    else
+    {
+        // xy
+        positions[i] = a * w1 + c * h1 + tx;
+        positions[i+1] = d * h1 + b * w1 + ty;
+
+        // xy
+        positions[i+5] = a * w0 + c * h1 + tx;
+        positions[i+6] = d * h1 + b * w0 + ty;
+
+         // xy
+        positions[i+10] = a * w0 + c * h0 + tx;
+        positions[i+11] = d * h0 + b * w0 + ty;
+
+        // xy
+        positions[i+15] = a * w1 + c * h0 + tx;
+        positions[i+16] = d * h0 + b * w1 + ty;
+    }
+    
+    // uv
+    positions[i+2] = uvs.x0;
+    positions[i+3] = uvs.y0;
+
+    // uv
+    positions[i+7] = uvs.x1;
+    positions[i+8] = uvs.y1;
+
+     // uv
+    positions[i+12] = uvs.x2;
+    positions[i+13] = uvs.y2;
+
+    // uv
+    positions[i+17] = uvs.x3;
+    positions[i+18] = uvs.y3;
+
+    // color and alpha
+    var tint = sprite.tint;
+
+    colors[i+4] = colors[i+9] = colors[i+14] = colors[i+19] = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24);
+
+    // increment the batchsize
+    this.sprites[this.currentBatchSize++] = sprite;
+
+};
+
+/**
+* Renders a TilingSprite using the spriteBatch.
+* 
+* @method renderTilingSprite
+* @param sprite {TilingSprite} the sprite to render
+*/
+PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function(sprite)
+{
+    var texture = sprite.tilingTexture;
+
+    // check texture..
+    if (this.currentBatchSize >= this.size)
+    {
+        this.flush();
+        this.currentBaseTexture = texture.baseTexture;
+    }
+
+    // set the textures uvs temporarily
+    if (!sprite._uvs)
+    {
+        sprite._uvs = new PIXI.TextureUvs();
+    }
+
+    var uvs = sprite._uvs;
+
+    var w = texture.baseTexture.width;
+    var h = texture.baseTexture.height;
+
+    // var w = sprite._frame.sourceSizeW;
+    // var h = sprite._frame.sourceSizeH;
+
+    // w = 16;
+    // h = 16;
+
+    sprite.tilePosition.x %= w * sprite.tileScaleOffset.x;
+    sprite.tilePosition.y %= h * sprite.tileScaleOffset.y;
+
+    var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x);
+    var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y);
+
+    var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x);
+    var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.tileScaleOffset.y);
+
+    uvs.x0 = 0 - offsetX;
+    uvs.y0 = 0 - offsetY;
+
+    uvs.x1 = (1 * scaleX) - offsetX;
+    uvs.y1 = 0 - offsetY;
+
+    uvs.x2 = (1 * scaleX) - offsetX;
+    uvs.y2 = (1 * scaleY) - offsetY;
+
+    uvs.x3 = 0 - offsetX;
+    uvs.y3 = (1 * scaleY) - offsetY;
+
+    //  Get the sprites current alpha and tint and combine them into a single color
+    var tint = sprite.tint;
+    var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24);
+
+    var positions = this.positions;
+    var colors = this.colors;
+
+    var width = sprite.width;
+    var height = sprite.height;
+
+    // TODO trim??
+    var aX = sprite.anchor.x;
+    var aY = sprite.anchor.y;
+    var w0 = width * (1-aX);
+    var w1 = width * -aX;
+
+    var h0 = height * (1-aY);
+    var h1 = height * -aY;
+
+    var i = this.currentBatchSize * 4 * this.vertSize;
+
+    var resolution = texture.baseTexture.resolution;
+
+    var wt = sprite.worldTransform;
+
+    var a = wt.a / resolution;
+    var b = wt.b / resolution;
+    var c = wt.c / resolution;
+    var d = wt.d / resolution;
+    var tx = wt.tx;
+    var ty = wt.ty;
+
+    // xy
+    positions[i++] = a * w1 + c * h1 + tx;
+    positions[i++] = d * h1 + b * w1 + ty;
+    // uv
+    positions[i++] = uvs.x0;
+    positions[i++] = uvs.y0;
+    // color
+    colors[i++] = color;
+
+    // xy
+    positions[i++] = (a * w0 + c * h1 + tx);
+    positions[i++] = d * h1 + b * w0 + ty;
+    // uv
+    positions[i++] = uvs.x1;
+    positions[i++] = uvs.y1;
+    // color
+    colors[i++] = color;
+    
+    // xy
+    positions[i++] = a * w0 + c * h0 + tx;
+    positions[i++] = d * h0 + b * w0 + ty;
+    // uv
+    positions[i++] = uvs.x2;
+    positions[i++] = uvs.y2;
+    // color
+    colors[i++] = color;
+
+    // xy
+    positions[i++] = a * w1 + c * h0 + tx;
+    positions[i++] = d * h0 + b * w1 + ty;
+    // uv
+    positions[i++] = uvs.x3;
+    positions[i++] = uvs.y3;
+    // color
+    colors[i++] = color;
+
+    // increment the batchsize
+    this.sprites[this.currentBatchSize++] = sprite;
+};
+
+/**
+* Renders the content and empties the current batch.
+*
+* @method flush
+*/
+PIXI.WebGLSpriteBatch.prototype.flush = function()
+{
+    // If the batch is length 0 then return as there is nothing to draw
+    if (this.currentBatchSize === 0)
+    {
+        return;
+    }
+
+    var gl = this.gl;
+    var shader;
+
+    if (this.dirty)
+    {
+        this.dirty = false;
+
+        // bind the main texture
+        gl.activeTexture(gl.TEXTURE0);
+
+        // bind the buffers
+        gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+
+        shader = this.defaultShader.shaders[gl.id];
+
+        // this is the same for each shader?
+        var stride = this.vertSize * 4;
+        gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
+        gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 2 * 4);
+
+        // color attributes will be interpreted as unsigned bytes and normalized
+        gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 4 * 4);
+    }
+
+    // upload the verts to the buffer  
+    if (this.currentBatchSize > (this.size * 0.5))
+    {
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
+    }
+    else
+    {
+        var view = this.positions.subarray(0, this.currentBatchSize * 4 * this.vertSize);
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
+    }
+
+    var nextTexture, nextBlendMode, nextShader;
+    var batchSize = 0;
+    var start = 0;
+
+    var currentBaseTexture = null;
+    var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode;
+    var currentShader = null;
+
+    var blendSwap = false;
+    var shaderSwap = false;
+    var sprite;
+
+    for (var i = 0, j = this.currentBatchSize; i < j; i++) {
+        
+        sprite = this.sprites[i];
+
+        if (sprite.tilingTexture)
+        {
+            nextTexture = sprite.tilingTexture.baseTexture;
+        }
+        else
+        {
+            nextTexture = sprite.texture.baseTexture;
+        }
+
+        nextBlendMode = sprite.blendMode;
+        nextShader = sprite.shader || this.defaultShader;
+
+        blendSwap = currentBlendMode !== nextBlendMode;
+        shaderSwap = currentShader !== nextShader; // should I use _UIDS???
+
+        if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap)
+        {
+            this.renderBatch(currentBaseTexture, batchSize, start);
+
+            start = i;
+            batchSize = 0;
+            currentBaseTexture = nextTexture;
+
+            if (blendSwap)
+            {
+                currentBlendMode = nextBlendMode;
+                this.renderSession.blendModeManager.setBlendMode(currentBlendMode);
+            }
+
+            if (shaderSwap)
+            {
+                currentShader = nextShader;
+                
+                shader = currentShader.shaders[gl.id];
+
+                if (!shader)
+                {
+                    shader = new PIXI.PixiShader(gl);
+
+                    shader.fragmentSrc = currentShader.fragmentSrc;
+                    shader.uniforms = currentShader.uniforms;
+                    shader.init();
+
+                    currentShader.shaders[gl.id] = shader;
+                }
+
+                // set shader function???
+                this.renderSession.shaderManager.setShader(shader);
+
+                if (shader.dirty)
+                {
+                    shader.syncUniforms();
+                }
+                
+                // both these only need to be set if they are changing..
+                // set the projection
+                var projection = this.renderSession.projection;
+                gl.uniform2f(shader.projectionVector, projection.x, projection.y);
+
+                // TODO - this is temporary!
+                var offsetVector = this.renderSession.offset;
+                gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y);
+
+                // set the pointers
+            }
+        }
+
+        batchSize++;
+    }
+
+    this.renderBatch(currentBaseTexture, batchSize, start);
+
+    // then reset the batch!
+    this.currentBatchSize = 0;
+};
+
+/**
+* @method renderBatch
+* @param texture {Texture}
+* @param size {Number}
+* @param startIndex {Number}
+*/
+PIXI.WebGLSpriteBatch.prototype.renderBatch = function(texture, size, startIndex)
+{
+    if (size === 0)
+    {
+        return;
+    }
+
+    var gl = this.gl;
+
+    // check if a texture is dirty..
+    if (texture._dirty[gl.id])
+    {
+        this.renderSession.renderer.updateTexture(texture);
+    }
+    else
+    {
+        // bind the current texture
+        gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
+    }
+
+    // now draw those suckas!
+    gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2);
+    
+    // increment the draw count
+    this.renderSession.drawCount++;
+};
+
+/**
+* @method stop
+*/
+PIXI.WebGLSpriteBatch.prototype.stop = function()
+{
+    this.flush();
+    this.dirty = true;
+};
+
+/**
+* @method start
+*/
+PIXI.WebGLSpriteBatch.prototype.start = function()
+{
+    this.dirty = true;
+};
+
+/**
+* Destroys the SpriteBatch.
+* 
+* @method destroy
+*/
+PIXI.WebGLSpriteBatch.prototype.destroy = function()
+{
+    this.vertices = null;
+    this.indices = null;
+    
+    this.gl.deleteBuffer(this.vertexBuffer);
+    this.gl.deleteBuffer(this.indexBuffer);
+    
+    this.currentBaseTexture = null;
+    
+    this.gl = null;
+};
+/**
+ * @author Mat Groves
+ * 
+ * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
+ * for creating the original pixi version!
+ *
+ * Heavily inspired by LibGDX's WebGLSpriteBatch:
+ * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
+ */
+
+/**
+* @class WebGLFastSpriteBatch
+* @constructor
+*/
+PIXI.WebGLFastSpriteBatch = function(gl)
+{
+    /**
+     * @property vertSize
+     * @type Number
+     */
+    this.vertSize = 10;
+
+    /**
+     * @property maxSize
+     * @type Number
+     */
+    this.maxSize = 6000;//Math.pow(2, 16) /  this.vertSize;
+
+    /**
+     * @property size
+     * @type Number
+     */
+    this.size = this.maxSize;
+
+    //the total number of floats in our batch
+    var numVerts = this.size * 4 *  this.vertSize;
+
+    //the total number of indices in our batch
+    var numIndices = this.maxSize * 6;
+
+    /**
+     * Vertex data
+     * @property vertices
+     * @type Float32Array
+     */
+    this.vertices = new PIXI.Float32Array(numVerts);
+
+    /**
+     * Index data
+     * @property indices
+     * @type Uint16Array
+     */
+    this.indices = new PIXI.Uint16Array(numIndices);
+    
+    /**
+     * @property vertexBuffer
+     * @type Object
+     */
+    this.vertexBuffer = null;
+
+    /**
+     * @property indexBuffer
+     * @type Object
+     */
+    this.indexBuffer = null;
+
+    /**
+     * @property lastIndexCount
+     * @type Number
+     */
+    this.lastIndexCount = 0;
+
+    for (var i=0, j=0; i < numIndices; i += 6, j += 4)
+    {
+        this.indices[i + 0] = j + 0;
+        this.indices[i + 1] = j + 1;
+        this.indices[i + 2] = j + 2;
+        this.indices[i + 3] = j + 0;
+        this.indices[i + 4] = j + 2;
+        this.indices[i + 5] = j + 3;
+    }
+
+    /**
+     * @property drawing
+     * @type Boolean
+     */
+    this.drawing = false;
+
+    /**
+     * @property currentBatchSize
+     * @type Number
+     */
+    this.currentBatchSize = 0;
+
+    /**
+     * @property currentBaseTexture
+     * @type BaseTexture
+     */
+    this.currentBaseTexture = null;
+   
+    /**
+     * @property currentBlendMode
+     * @type Number
+     */
+    this.currentBlendMode = 0;
+
+    /**
+     * @property renderSession
+     * @type Object
+     */
+    this.renderSession = null;
+    
+    /**
+     * @property shader
+     * @type Object
+     */
+    this.shader = null;
+
+    /**
+     * @property matrix
+     * @type Matrix
+     */
+    this.matrix = null;
+
+    this.setContext(gl);
+};
+
+PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch;
+
+/**
+ * Sets the WebGL Context.
+ *
+ * @method setContext
+ * @param gl {WebGLContext} the current WebGL drawing context
+ */
+PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+
+    // create a couple of buffers
+    this.vertexBuffer = gl.createBuffer();
+    this.indexBuffer = gl.createBuffer();
+
+    // 65535 is max index, so 65535 / 6 = 10922.
+
+    //upload the index data
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
+};
+
+/**
+ * @method begin
+ * @param spriteBatch {WebGLSpriteBatch}
+ * @param renderSession {Object}
+ */
+PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession)
+{
+    this.renderSession = renderSession;
+    this.shader = this.renderSession.shaderManager.fastShader;
+
+    this.matrix = spriteBatch.worldTransform.toArray(true);
+
+    this.start();
+};
+
+/**
+ * @method end
+ */
+PIXI.WebGLFastSpriteBatch.prototype.end = function()
+{
+    this.flush();
+};
+
+/**
+ * @method render
+ * @param spriteBatch {WebGLSpriteBatch}
+ */
+PIXI.WebGLFastSpriteBatch.prototype.render = function(spriteBatch)
+{
+    var children = spriteBatch.children;
+    var sprite = children[0];
+
+    // if the uvs have not updated then no point rendering just yet!
+    
+    // check texture.
+    if(!sprite.texture._uvs)return;
+   
+    this.currentBaseTexture = sprite.texture.baseTexture;
+    
+    // check blend mode
+    if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode)
+    {
+        this.flush();
+        this.renderSession.blendModeManager.setBlendMode(sprite.blendMode);
+    }
+    
+    for(var i=0,j= children.length; i<j; i++)
+    {
+        this.renderSprite(children[i]);
+    }
+
+    this.flush();
+};
+
+/**
+ * @method renderSprite
+ * @param sprite {Sprite}
+ */
+PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function(sprite)
+{
+    //sprite = children[i];
+    if(!sprite.visible)return;
+    
+    // TODO trim??
+    if(sprite.texture.baseTexture !== this.currentBaseTexture)
+    {
+        this.flush();
+        this.currentBaseTexture = sprite.texture.baseTexture;
+        
+        if(!sprite.texture._uvs)return;
+    }
+
+    var uvs, vertices = this.vertices, width, height, w0, w1, h0, h1, index;
+
+    uvs = sprite.texture._uvs;
+
+    width = sprite.texture.frame.width;
+    height = sprite.texture.frame.height;
+
+    if (sprite.texture.trim)
+    {
+        // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
+        var trim = sprite.texture.trim;
+
+        w1 = trim.x - sprite.anchor.x * trim.width;
+        w0 = w1 + sprite.texture.crop.width;
+
+        h1 = trim.y - sprite.anchor.y * trim.height;
+        h0 = h1 + sprite.texture.crop.height;
+    }
+    else
+    {
+        w0 = (sprite.texture.frame.width ) * (1-sprite.anchor.x);
+        w1 = (sprite.texture.frame.width ) * -sprite.anchor.x;
+
+        h0 = sprite.texture.frame.height * (1-sprite.anchor.y);
+        h1 = sprite.texture.frame.height * -sprite.anchor.y;
+    }
+
+    index = this.currentBatchSize * 4 * this.vertSize;
+
+    // xy
+    vertices[index++] = w1;
+    vertices[index++] = h1;
+
+    vertices[index++] = sprite.position.x;
+    vertices[index++] = sprite.position.y;
+
+    //scale
+    vertices[index++] = sprite.scale.x;
+    vertices[index++] = sprite.scale.y;
+
+    //rotation
+    vertices[index++] = sprite.rotation;
+
+    // uv
+    vertices[index++] = uvs.x0;
+    vertices[index++] = uvs.y1;
+    // color
+    vertices[index++] = sprite.alpha;
+ 
+
+    // xy
+    vertices[index++] = w0;
+    vertices[index++] = h1;
+
+    vertices[index++] = sprite.position.x;
+    vertices[index++] = sprite.position.y;
+
+    //scale
+    vertices[index++] = sprite.scale.x;
+    vertices[index++] = sprite.scale.y;
+
+     //rotation
+    vertices[index++] = sprite.rotation;
+
+    // uv
+    vertices[index++] = uvs.x1;
+    vertices[index++] = uvs.y1;
+    // color
+    vertices[index++] = sprite.alpha;
+  
+
+    // xy
+    vertices[index++] = w0;
+    vertices[index++] = h0;
+
+    vertices[index++] = sprite.position.x;
+    vertices[index++] = sprite.position.y;
+
+    //scale
+    vertices[index++] = sprite.scale.x;
+    vertices[index++] = sprite.scale.y;
+
+     //rotation
+    vertices[index++] = sprite.rotation;
+
+    // uv
+    vertices[index++] = uvs.x2;
+    vertices[index++] = uvs.y2;
+    // color
+    vertices[index++] = sprite.alpha;
+ 
+
+
+
+    // xy
+    vertices[index++] = w1;
+    vertices[index++] = h0;
+
+    vertices[index++] = sprite.position.x;
+    vertices[index++] = sprite.position.y;
+
+    //scale
+    vertices[index++] = sprite.scale.x;
+    vertices[index++] = sprite.scale.y;
+
+     //rotation
+    vertices[index++] = sprite.rotation;
+
+    // uv
+    vertices[index++] = uvs.x3;
+    vertices[index++] = uvs.y3;
+    // color
+    vertices[index++] = sprite.alpha;
+
+    // increment the batchs
+    this.currentBatchSize++;
+
+    if(this.currentBatchSize >= this.size)
+    {
+        this.flush();
+    }
+};
+
+/**
+ * @method flush
+ */
+PIXI.WebGLFastSpriteBatch.prototype.flush = function()
+{
+    // If the batch is length 0 then return as there is nothing to draw
+    if (this.currentBatchSize===0)return;
+
+    var gl = this.gl;
+    
+    // bind the current texture
+
+    if(!this.currentBaseTexture._glTextures[gl.id])this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl);
+
+    gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]);
+
+    // upload the verts to the buffer
+   
+    if(this.currentBatchSize > ( this.size * 0.5 ) )
+    {
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
+    }
+    else
+    {
+        var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
+
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
+    }
+    
+    // now draw those suckas!
+    gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0);
+   
+    // then reset the batch!
+    this.currentBatchSize = 0;
+
+    // increment the draw count
+    this.renderSession.drawCount++;
+};
+
+
+/**
+ * @method stop
+ */
+PIXI.WebGLFastSpriteBatch.prototype.stop = function()
+{
+    this.flush();
+};
+
+/**
+ * @method start
+ */
+PIXI.WebGLFastSpriteBatch.prototype.start = function()
+{
+    var gl = this.gl;
+
+    // bind the main texture
+    gl.activeTexture(gl.TEXTURE0);
+
+    // bind the buffers
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+
+    // set the projection
+    var projection = this.renderSession.projection;
+    gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
+
+    // set the matrix
+    gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix);
+
+    // set the pointers
+    var stride =  this.vertSize * 4;
+
+    gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
+    gl.vertexAttribPointer(this.shader.aPositionCoord, 2, gl.FLOAT, false, stride, 2 * 4);
+    gl.vertexAttribPointer(this.shader.aScale, 2, gl.FLOAT, false, stride, 4 * 4);
+    gl.vertexAttribPointer(this.shader.aRotation, 1, gl.FLOAT, false, stride, 6 * 4);
+    gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 7 * 4);
+    gl.vertexAttribPointer(this.shader.colorAttribute, 1, gl.FLOAT, false, stride, 9 * 4);
+    
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class WebGLFilterManager
+* @constructor
+*/
+PIXI.WebGLFilterManager = function()
+{
+    /**
+     * @property filterStack
+     * @type Array
+     */
+    this.filterStack = [];
+    
+    /**
+     * @property offsetX
+     * @type Number
+     */
+    this.offsetX = 0;
+
+    /**
+     * @property offsetY
+     * @type Number
+     */
+    this.offsetY = 0;
+};
+
+PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager;
+
+/**
+* Initialises the context and the properties.
+* 
+* @method setContext 
+* @param gl {WebGLContext} the current WebGL drawing context
+*/
+PIXI.WebGLFilterManager.prototype.setContext = function(gl)
+{
+    this.gl = gl;
+    this.texturePool = [];
+
+    this.initShaderBuffers();
+};
+
+/**
+* @method begin
+* @param renderSession {RenderSession} 
+* @param buffer {ArrayBuffer} 
+*/
+PIXI.WebGLFilterManager.prototype.begin = function(renderSession, buffer)
+{
+    this.renderSession = renderSession;
+    this.defaultShader = renderSession.shaderManager.defaultShader;
+
+    var projection = this.renderSession.projection;
+    this.width = projection.x * 2;
+    this.height = -projection.y * 2;
+    this.buffer = buffer;
+};
+
+/**
+* Applies the filter and adds it to the current filter stack.
+* 
+* @method pushFilter
+* @param filterBlock {Object} the filter that will be pushed to the current filter stack
+*/
+PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock)
+{
+    var gl = this.gl;
+
+    var projection = this.renderSession.projection;
+    var offset = this.renderSession.offset;
+
+    filterBlock._filterArea = filterBlock.target.filterArea || filterBlock.target.getBounds();
+
+    // filter program
+    // OPTIMISATION - the first filter is free if its a simple color change?
+    this.filterStack.push(filterBlock);
+
+    var filter = filterBlock.filterPasses[0];
+
+    this.offsetX += filterBlock._filterArea.x;
+    this.offsetY += filterBlock._filterArea.y;
+
+    var texture = this.texturePool.pop();
+    if(!texture)
+    {
+        texture = new PIXI.FilterTexture(this.gl, this.width, this.height);
+    }
+    else
+    {
+        texture.resize(this.width, this.height);
+    }
+
+    gl.bindTexture(gl.TEXTURE_2D,  texture.texture);
+
+    var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea;
+
+    var padding = filter.padding;
+    filterArea.x -= padding;
+    filterArea.y -= padding;
+    filterArea.width += padding * 2;
+    filterArea.height += padding * 2;
+
+    // cap filter to screen size..
+    if(filterArea.x < 0)filterArea.x = 0;
+    if(filterArea.width > this.width)filterArea.width = this.width;
+    if(filterArea.y < 0)filterArea.y = 0;
+    if(filterArea.height > this.height)filterArea.height = this.height;
+
+    //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,  filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+    gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer);
+
+    // set view port
+    gl.viewport(0, 0, filterArea.width, filterArea.height);
+
+    projection.x = filterArea.width/2;
+    projection.y = -filterArea.height/2;
+
+    offset.x = -filterArea.x;
+    offset.y = -filterArea.y;
+
+    // update projection
+    // now restore the regular shader..
+    // this.renderSession.shaderManager.setShader(this.defaultShader);
+    //gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2);
+    //gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y);
+
+    gl.colorMask(true, true, true, true);
+    gl.clearColor(0,0,0, 0);
+    gl.clear(gl.COLOR_BUFFER_BIT);
+
+    filterBlock._glFilterTexture = texture;
+
+};
+
+/**
+* Removes the last filter from the filter stack and doesn't return it.
+* 
+* @method popFilter
+*/
+PIXI.WebGLFilterManager.prototype.popFilter = function()
+{
+    var gl = this.gl;
+    var filterBlock = this.filterStack.pop();
+    var filterArea = filterBlock._filterArea;
+    var texture = filterBlock._glFilterTexture;
+    var projection = this.renderSession.projection;
+    var offset = this.renderSession.offset;
+
+    if(filterBlock.filterPasses.length > 1)
+    {
+        gl.viewport(0, 0, filterArea.width, filterArea.height);
+
+        gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+
+        this.vertexArray[0] = 0;
+        this.vertexArray[1] = filterArea.height;
+
+        this.vertexArray[2] = filterArea.width;
+        this.vertexArray[3] = filterArea.height;
+
+        this.vertexArray[4] = 0;
+        this.vertexArray[5] = 0;
+
+        this.vertexArray[6] = filterArea.width;
+        this.vertexArray[7] = 0;
+
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
+
+        gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
+        // now set the uvs..
+        this.uvArray[2] = filterArea.width/this.width;
+        this.uvArray[5] = filterArea.height/this.height;
+        this.uvArray[6] = filterArea.width/this.width;
+        this.uvArray[7] = filterArea.height/this.height;
+
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
+
+        var inputTexture = texture;
+        var outputTexture = this.texturePool.pop();
+        if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.gl, this.width, this.height);
+        outputTexture.resize(this.width, this.height);
+
+        // need to clear this FBO as it may have some left over elements from a previous filter.
+        gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
+        gl.clear(gl.COLOR_BUFFER_BIT);
+
+        gl.disable(gl.BLEND);
+
+        for (var i = 0; i < filterBlock.filterPasses.length-1; i++)
+        {
+            var filterPass = filterBlock.filterPasses[i];
+
+            gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
+
+            // set texture
+            gl.activeTexture(gl.TEXTURE0);
+            gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
+
+            // draw texture..
+            //filterPass.applyFilterPass(filterArea.width, filterArea.height);
+            this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height);
+
+            // swap the textures..
+            var temp = inputTexture;
+            inputTexture = outputTexture;
+            outputTexture = temp;
+        }
+
+        gl.enable(gl.BLEND);
+
+        texture = inputTexture;
+        this.texturePool.push(outputTexture);
+    }
+
+    var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1];
+
+    this.offsetX -= filterArea.x;
+    this.offsetY -= filterArea.y;
+
+    var sizeX = this.width;
+    var sizeY = this.height;
+
+    var offsetX = 0;
+    var offsetY = 0;
+
+    var buffer = this.buffer;
+
+    // time to render the filters texture to the previous scene
+    if(this.filterStack.length === 0)
+    {
+        gl.colorMask(true, true, true, true);//this.transparent);
+    }
+    else
+    {
+        var currentFilter = this.filterStack[this.filterStack.length-1];
+        filterArea = currentFilter._filterArea;
+
+        sizeX = filterArea.width;
+        sizeY = filterArea.height;
+
+        offsetX = filterArea.x;
+        offsetY = filterArea.y;
+
+        buffer =  currentFilter._glFilterTexture.frameBuffer;
+    }
+
+    // TODO need to remove these global elements..
+    projection.x = sizeX/2;
+    projection.y = -sizeY/2;
+
+    offset.x = offsetX;
+    offset.y = offsetY;
+
+    filterArea = filterBlock._filterArea;
+
+    var x = filterArea.x-offsetX;
+    var y = filterArea.y-offsetY;
+
+    // update the buffers..
+    // make sure to flip the y!
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+
+    this.vertexArray[0] = x;
+    this.vertexArray[1] = y + filterArea.height;
+
+    this.vertexArray[2] = x + filterArea.width;
+    this.vertexArray[3] = y + filterArea.height;
+
+    this.vertexArray[4] = x;
+    this.vertexArray[5] = y;
+
+    this.vertexArray[6] = x + filterArea.width;
+    this.vertexArray[7] = y;
+
+    gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
+
+    this.uvArray[2] = filterArea.width/this.width;
+    this.uvArray[5] = filterArea.height/this.height;
+    this.uvArray[6] = filterArea.width/this.width;
+    this.uvArray[7] = filterArea.height/this.height;
+
+    gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
+
+    gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution);
+
+    // bind the buffer
+    gl.bindFramebuffer(gl.FRAMEBUFFER, buffer );
+
+    // set the blend mode! 
+    //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
+
+    // set texture
+    gl.activeTexture(gl.TEXTURE0);
+    gl.bindTexture(gl.TEXTURE_2D, texture.texture);
+
+    // apply!
+    this.applyFilterPass(filter, filterArea, sizeX, sizeY);
+
+    // now restore the regular shader.. should happen automatically now..
+    // this.renderSession.shaderManager.setShader(this.defaultShader);
+    // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2);
+    // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY);
+
+    // return the texture to the pool
+    this.texturePool.push(texture);
+    filterBlock._glFilterTexture = null;
+};
+
+
+/**
+* Applies the filter to the specified area.
+* 
+* @method applyFilterPass
+* @param filter {AbstractFilter} the filter that needs to be applied
+* @param filterArea {Texture} TODO - might need an update
+* @param width {Number} the horizontal range of the filter
+* @param height {Number} the vertical range of the filter
+*/
+PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height)
+{
+    // use program
+    var gl = this.gl;
+    var shader = filter.shaders[gl.id];
+
+    if(!shader)
+    {
+        shader = new PIXI.PixiShader(gl);
+
+        shader.fragmentSrc = filter.fragmentSrc;
+        shader.uniforms = filter.uniforms;
+        shader.init();
+
+        filter.shaders[gl.id] = shader;
+    }
+
+    // set the shader
+    this.renderSession.shaderManager.setShader(shader);
+
+//    gl.useProgram(shader.program);
+
+    gl.uniform2f(shader.projectionVector, width/2, -height/2);
+    gl.uniform2f(shader.offsetVector, 0,0);
+
+    if(filter.uniforms.dimensions)
+    {
+        filter.uniforms.dimensions.value[0] = this.width;//width;
+        filter.uniforms.dimensions.value[1] = this.height;//height;
+        filter.uniforms.dimensions.value[2] = this.vertexArray[0];
+        filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height;
+    }
+
+    shader.syncUniforms();
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+    gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
+    gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
+    gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0);
+
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+
+    // draw the filter...
+    gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
+
+    this.renderSession.drawCount++;
+};
+
+/**
+* Initialises the shader buffers.
+* 
+* @method initShaderBuffers
+*/
+PIXI.WebGLFilterManager.prototype.initShaderBuffers = function()
+{
+    var gl = this.gl;
+
+    // create some buffers
+    this.vertexBuffer = gl.createBuffer();
+    this.uvBuffer = gl.createBuffer();
+    this.colorBuffer = gl.createBuffer();
+    this.indexBuffer = gl.createBuffer();
+
+    // bind and upload the vertexs..
+    // keep a reference to the vertexFloatData..
+    this.vertexArray = new PIXI.Float32Array([0.0, 0.0,
+                                         1.0, 0.0,
+                                         0.0, 1.0,
+                                         1.0, 1.0]);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW);
+
+    // bind and upload the uv buffer
+    this.uvArray = new PIXI.Float32Array([0.0, 0.0,
+                                     1.0, 0.0,
+                                     0.0, 1.0,
+                                     1.0, 1.0]);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW);
+
+    this.colorArray = new PIXI.Float32Array([1.0, 0xFFFFFF,
+                                        1.0, 0xFFFFFF,
+                                        1.0, 0xFFFFFF,
+                                        1.0, 0xFFFFFF]);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW);
+
+    // bind and upload the index
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
+    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW);
+
+};
+
+/**
+* Destroys the filter and removes it from the filter stack.
+* 
+* @method destroy
+*/
+PIXI.WebGLFilterManager.prototype.destroy = function()
+{
+    var gl = this.gl;
+
+    this.filterStack = null;
+    
+    this.offsetX = 0;
+    this.offsetY = 0;
+
+    // destroy textures
+    for (var i = 0; i < this.texturePool.length; i++) {
+        this.texturePool[i].destroy();
+    }
+    
+    this.texturePool = null;
+
+    //destroy buffers..
+    gl.deleteBuffer(this.vertexBuffer);
+    gl.deleteBuffer(this.uvBuffer);
+    gl.deleteBuffer(this.colorBuffer);
+    gl.deleteBuffer(this.indexBuffer);
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+* @class FilterTexture
+* @constructor
+* @param gl {WebGLContext} the current WebGL drawing context
+* @param width {Number} the horizontal range of the filter
+* @param height {Number} the vertical range of the filter
+* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+*/
+PIXI.FilterTexture = function(gl, width, height, scaleMode)
+{
+    /**
+     * @property gl
+     * @type WebGLContext
+     */
+    this.gl = gl;
+
+    // next time to create a frame buffer and texture
+
+    /**
+     * @property frameBuffer
+     * @type Any
+     */
+    this.frameBuffer = gl.createFramebuffer();
+
+    /**
+     * @property texture
+     * @type Any
+     */
+    this.texture = gl.createTexture();
+
+    /**
+     * @property scaleMode
+     * @type Number
+     */
+    scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
+
+    gl.bindTexture(gl.TEXTURE_2D,  this.texture);
+    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
+    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
+    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+    gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
+
+    gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
+    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
+
+    // required for masking a mask??
+    this.renderBuffer = gl.createRenderbuffer();
+    gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
+    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer);
+  
+    this.resize(width, height);
+};
+
+PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture;
+
+/**
+* Clears the filter texture.
+* 
+* @method clear
+*/
+PIXI.FilterTexture.prototype.clear = function()
+{
+    var gl = this.gl;
+    
+    gl.clearColor(0,0,0, 0);
+    gl.clear(gl.COLOR_BUFFER_BIT);
+};
+
+/**
+ * Resizes the texture to the specified width and height
+ *
+ * @method resize
+ * @param width {Number} the new width of the texture
+ * @param height {Number} the new height of the texture
+ */
+PIXI.FilterTexture.prototype.resize = function(width, height)
+{
+    if(this.width === width && this.height === height) return;
+
+    this.width = width;
+    this.height = height;
+
+    var gl = this.gl;
+
+    gl.bindTexture(gl.TEXTURE_2D,  this.texture);
+    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,  width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+    // update the stencil buffer width and height
+    gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
+    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height );
+};
+
+/**
+* Destroys the filter texture.
+* 
+* @method destroy
+*/
+PIXI.FilterTexture.prototype.destroy = function()
+{
+    var gl = this.gl;
+    gl.deleteFramebuffer( this.frameBuffer );
+    gl.deleteTexture( this.texture );
+
+    this.frameBuffer = null;
+    this.texture = null;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * Creates a Canvas element of the given size.
+ *
+ * @class CanvasBuffer
+ * @constructor
+ * @param width {Number} the width for the newly created canvas
+ * @param height {Number} the height for the newly created canvas
+ */
+PIXI.CanvasBuffer = function(width, height)
+{
+    /**
+     * The width of the Canvas in pixels.
+     *
+     * @property width
+     * @type Number
+     */
+    this.width = width;
+
+    /**
+     * The height of the Canvas in pixels.
+     *
+     * @property height
+     * @type Number
+     */
+    this.height = height;
+
+    /**
+     * The Canvas object that belongs to this CanvasBuffer.
+     *
+     * @property canvas
+     * @type HTMLCanvasElement
+     */
+    this.canvas = document.createElement("canvas");
+
+    /**
+     * A CanvasRenderingContext2D object representing a two-dimensional rendering context.
+     *
+     * @property context
+     * @type CanvasRenderingContext2D
+     */
+    this.context = this.canvas.getContext("2d");
+
+    this.canvas.width = width;
+    this.canvas.height = height;
+};
+
+PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer;
+
+/**
+ * Clears the canvas that was created by the CanvasBuffer class.
+ *
+ * @method clear
+ * @private
+ */
+PIXI.CanvasBuffer.prototype.clear = function()
+{
+    this.context.setTransform(1, 0, 0, 1, 0, 0);
+    this.context.clearRect(0,0, this.width, this.height);
+};
+
+/**
+ * Resizes the canvas to the specified width and height.
+ *
+ * @method resize
+ * @param width {Number} the new width of the canvas
+ * @param height {Number} the new height of the canvas
+ */
+PIXI.CanvasBuffer.prototype.resize = function(width, height)
+{
+    this.width = this.canvas.width = width;
+    this.height = this.canvas.height = height;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * A set of functions used to handle masking.
+ *
+ * @class CanvasMaskManager
+ * @constructor
+ */
+PIXI.CanvasMaskManager = function()
+{
+};
+
+PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager;
+
+/**
+ * This method adds it to the current stack of masks.
+ *
+ * @method pushMask
+ * @param maskData {Object} the maskData that will be pushed
+ * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
+ */
+PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession)
+{
+	var context = renderSession.context;
+
+    context.save();
+    
+    var cacheAlpha = maskData.alpha;
+    var transform = maskData.worldTransform;
+
+    var resolution = renderSession.resolution;
+
+    context.setTransform(transform.a * resolution,
+                         transform.b * resolution,
+                         transform.c * resolution,
+                         transform.d * resolution,
+                         transform.tx * resolution,
+                         transform.ty * resolution);
+
+    PIXI.CanvasGraphics.renderGraphicsMask(maskData, context);
+
+    context.clip();
+
+    maskData.worldAlpha = cacheAlpha;
+};
+
+/**
+ * Restores the current drawing context to the state it was before the mask was applied.
+ *
+ * @method popMask
+ * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
+ */
+PIXI.CanvasMaskManager.prototype.popMask = function(renderSession)
+{
+    renderSession.context.restore();
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * Utility methods for Sprite/Texture tinting.
+ *
+ * @class CanvasTinter
+ * @static
+ */
+PIXI.CanvasTinter = function() {};
+
+/**
+ * Basically this method just needs a sprite and a color and tints the sprite with the given color.
+ * 
+ * @method getTintedTexture 
+ * @static
+ * @param sprite {Sprite} the sprite to tint
+ * @param color {Number} the color to use to tint the sprite with
+ * @return {HTMLCanvasElement} The tinted canvas
+ */
+PIXI.CanvasTinter.getTintedTexture = function(sprite, color)
+{
+    var canvas = sprite.tintedTexture || document.createElement("canvas");
+    
+    PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas);
+
+    return canvas;
+};
+
+/**
+ * Tint a texture using the "multiply" operation.
+ * 
+ * @method tintWithMultiply
+ * @static
+ * @param texture {Texture} the texture to tint
+ * @param color {Number} the color to use to tint the sprite with
+ * @param canvas {HTMLCanvasElement} the current canvas
+ */
+PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas)
+{
+    var context = canvas.getContext("2d");
+
+    var crop = texture.crop;
+
+    if (canvas.width !== crop.width || canvas.height !== crop.height)
+    {
+        canvas.width = crop.width;
+        canvas.height = crop.height;
+    }
+
+    context.clearRect(0, 0, crop.width, crop.height);
+
+    context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6);
+    context.fillRect(0, 0, crop.width, crop.height);
+
+    context.globalCompositeOperation = "multiply";
+    context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
+
+    context.globalCompositeOperation = "destination-atop";
+    context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
+
+};
+
+/**
+ * Tint a texture pixel per pixel.
+ * 
+ * @method tintPerPixel
+ * @static
+ * @param texture {Texture} the texture to tint
+ * @param color {Number} the color to use to tint the sprite with
+ * @param canvas {HTMLCanvasElement} the current canvas
+ */ 
+PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas)
+{
+    var context = canvas.getContext("2d");
+
+    var crop = texture.crop;
+
+    canvas.width = crop.width;
+    canvas.height = crop.height;
+  
+    context.globalCompositeOperation = "copy";
+
+    context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
+
+    var rgbValues = PIXI.hex2rgb(color);
+    var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];
+
+    var pixelData = context.getImageData(0, 0, crop.width, crop.height);
+
+    var pixels = pixelData.data;
+
+    for (var i = 0; i < pixels.length; i += 4)
+    {
+        pixels[i + 0] *= r;
+        pixels[i + 1] *= g;
+        pixels[i + 2] *= b;
+
+        if (!PIXI.CanvasTinter.canHandleAlpha)
+        {
+            var alpha = pixels[i + 3];
+
+            pixels[i + 0] /= 255 / alpha;
+            pixels[i + 1] /= 255 / alpha;
+            pixels[i + 2] /= 255 / alpha;
+        }
+    }
+
+    context.putImageData(pixelData, 0, 0);
+};
+
+/**
+ * Checks if the browser correctly supports putImageData alpha channels.
+ * 
+ * @method checkInverseAlpha
+ * @static
+ */
+PIXI.CanvasTinter.checkInverseAlpha = function()
+{
+    var canvas = new PIXI.CanvasBuffer(2, 1);
+
+    canvas.context.fillStyle = "rgba(10, 20, 30, 0.5)";
+
+    //  Draw a single pixel
+    canvas.context.fillRect(0, 0, 1, 1);
+
+    //  Get the color values
+    var s1 = canvas.context.getImageData(0, 0, 1, 1);
+
+    if (s1 === null)
+    {
+        return false;
+    }
+
+    //  Plot them to x2
+    canvas.context.putImageData(s1, 1, 0);
+
+    //  Get those values
+    var s2 = canvas.context.getImageData(1, 0, 1, 1);
+
+    //  Compare and return
+    return (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]);
+};
+
+/**
+ * If the browser isn't capable of handling tinting with alpha this will be false.
+ * This property is only applicable if using tintWithPerPixel.
+ *
+ * @property canHandleAlpha
+ * @type Boolean
+ * @static
+ */
+PIXI.CanvasTinter.canHandleAlpha = PIXI.CanvasTinter.checkInverseAlpha();
+
+/**
+ * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
+ *
+ * @property canUseMultiply
+ * @type Boolean
+ * @static
+ */
+PIXI.CanvasTinter.canUseMultiply = PIXI.canUseNewCanvasBlendModes();
+
+/**
+ * The tinting method that will be used.
+ * 
+ * @method tintMethod
+ * @static
+ */
+PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.canUseMultiply ? PIXI.CanvasTinter.tintWithMultiply :  PIXI.CanvasTinter.tintWithPerPixel;
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL.
+ * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :)
+ *
+ * @class CanvasRenderer
+ * @constructor
+ * @param [width=800] {Number} the width of the canvas view
+ * @param [height=600] {Number} the height of the canvas view
+ * @param [options] {Object} The optional renderer parameters
+ * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional
+ * @param [options.transparent=false] {Boolean} If the render view is transparent, default false
+ * @param [options.autoResize=false] {Boolean} If the render view is automatically resized, default false
+ * @param [options.resolution=1] {Number} the resolution of the renderer retina would be 2
+ * @param [options.clearBeforeRender=true] {Boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
+ */
+PIXI.CanvasRenderer = function(width, height, options)
+{
+    if (options)
+    {
+        for (var i in PIXI.defaultRenderOptions)
+        {
+            if (options[i] === undefined) options[i] = PIXI.defaultRenderOptions[i];
+        }
+    }
+    else
+    {
+        options = PIXI.defaultRenderOptions;
+    }
+
+    if (!PIXI.defaultRenderer)
+    {
+        PIXI.defaultRenderer = this;
+    }
+
+    /**
+     * The renderer type.
+     *
+     * @property type
+     * @type Number
+     */
+    this.type = PIXI.CANVAS_RENDERER;
+
+    /**
+     * The resolution of the canvas.
+     *
+     * @property resolution
+     * @type Number
+     */
+    this.resolution = options.resolution;
+
+    /**
+     * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
+     * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color.
+     * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame.
+     * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set.
+     *
+     * @property clearBeforeRender
+     * @type Boolean
+     * @default
+     */
+    this.clearBeforeRender = options.clearBeforeRender;
+
+    /**
+     * Whether the render view is transparent
+     *
+     * @property transparent
+     * @type Boolean
+     */
+    this.transparent = options.transparent;
+
+    /**
+     * Whether the render view should be resized automatically
+     *
+     * @property autoResize
+     * @type Boolean
+     */
+    this.autoResize = options.autoResize || false;
+
+    /**
+     * The width of the canvas view
+     *
+     * @property width
+     * @type Number
+     * @default 800
+     */
+    this.width = width || 800;
+
+    /**
+     * The height of the canvas view
+     *
+     * @property height
+     * @type Number
+     * @default 600
+     */
+    this.height = height || 600;
+
+    this.width *= this.resolution;
+    this.height *= this.resolution;
+
+    /**
+     * The canvas element that everything is drawn to.
+     *
+     * @property view
+     * @type HTMLCanvasElement
+     */
+    this.view = options.view || document.createElement( "canvas" );
+
+    /**
+     * The canvas 2d context that everything is drawn with
+     * @property context
+     * @type CanvasRenderingContext2D
+     */
+    this.context = this.view.getContext( "2d", { alpha: this.transparent } );
+
+    /**
+     * Boolean flag controlling canvas refresh.
+     *
+     * @property refresh
+     * @type Boolean
+     */
+    this.refresh = true;
+
+    this.view.width = this.width * this.resolution;
+    this.view.height = this.height * this.resolution;
+
+    /**
+     * Internal var.
+     *
+     * @property count
+     * @type Number
+     */
+    this.count = 0;
+
+    /**
+     * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer
+     * @property CanvasMaskManager
+     * @type CanvasMaskManager
+     */
+    this.maskManager = new PIXI.CanvasMaskManager();
+
+    /**
+     * The render session is just a bunch of parameter used for rendering
+     * @property renderSession
+     * @type Object
+     */
+    this.renderSession = {
+        context: this.context,
+        maskManager: this.maskManager,
+        scaleMode: null,
+        smoothProperty: null,
+        /**
+         * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation.
+         * Handy for crisp pixel art and speed on legacy devices.
+         */
+        roundPixels: false
+    };
+
+    this.mapBlendModes();
+    
+    this.resize(width, height);
+
+    if("imageSmoothingEnabled" in this.context)
+        this.renderSession.smoothProperty = "imageSmoothingEnabled";
+    else if("webkitImageSmoothingEnabled" in this.context)
+        this.renderSession.smoothProperty = "webkitImageSmoothingEnabled";
+    else if("mozImageSmoothingEnabled" in this.context)
+        this.renderSession.smoothProperty = "mozImageSmoothingEnabled";
+    else if("oImageSmoothingEnabled" in this.context)
+        this.renderSession.smoothProperty = "oImageSmoothingEnabled";
+    else if ("msImageSmoothingEnabled" in this.context)
+        this.renderSession.smoothProperty = "msImageSmoothingEnabled";
+};
+
+// constructor
+PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer;
+
+/**
+ * Renders the Stage to this canvas view
+ *
+ * @method render
+ * @param stage {Stage} the Stage element to be rendered
+ */
+PIXI.CanvasRenderer.prototype.render = function(stage)
+{
+    stage.updateTransform();
+
+    this.context.setTransform(1,0,0,1,0,0);
+
+    this.context.globalAlpha = 1;
+
+    this.renderSession.currentBlendMode = PIXI.blendModes.NORMAL;
+    this.context.globalCompositeOperation = PIXI.blendModesCanvas[PIXI.blendModes.NORMAL];
+
+    if (navigator.isCocoonJS && this.view.screencanvas)
+    {
+        this.context.fillStyle = "black";
+        this.context.clear();
+    }
+    
+    if (this.clearBeforeRender)
+    {
+        if (this.transparent)
+        {
+            this.context.clearRect(0, 0, this.width, this.height);
+        }
+        else
+        {
+            this.context.fillStyle = stage.backgroundColorString;
+            this.context.fillRect(0, 0, this.width , this.height);
+        }
+    }
+    
+    this.renderDisplayObject(stage);
+
+};
+
+/**
+ * Removes everything from the renderer and optionally removes the Canvas DOM element.
+ *
+ * @method destroy
+ * @param [removeView=true] {boolean} Removes the Canvas element from the DOM.
+ */
+PIXI.CanvasRenderer.prototype.destroy = function(removeView)
+{
+    if (removeView === undefined) { removeView = true; }
+
+    if (removeView && this.view.parent)
+    {
+        this.view.parent.removeChild(this.view);
+    }
+
+    this.view = null;
+    this.context = null;
+    this.maskManager = null;
+    this.renderSession = null;
+
+};
+
+/**
+ * Resizes the canvas view to the specified width and height
+ *
+ * @method resize
+ * @param width {Number} the new width of the canvas view
+ * @param height {Number} the new height of the canvas view
+ */
+PIXI.CanvasRenderer.prototype.resize = function(width, height)
+{
+    this.width = width * this.resolution;
+    this.height = height * this.resolution;
+
+    this.view.width = this.width;
+    this.view.height = this.height;
+
+    if (this.autoResize) {
+        this.view.style.width = this.width / this.resolution + "px";
+        this.view.style.height = this.height / this.resolution + "px";
+    }
+};
+
+/**
+ * Renders a display object
+ *
+ * @method renderDisplayObject
+ * @param displayObject {DisplayObject} The displayObject to render
+ * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
+ * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
+ * @private
+ */
+PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject, context, matrix)
+{
+    this.renderSession.context = context || this.context;
+    this.renderSession.resolution = this.resolution;
+    displayObject._renderCanvas(this.renderSession, matrix);
+};
+
+/**
+ * Maps Pixi blend modes to canvas blend modes.
+ *
+ * @method mapBlendModes
+ * @private
+ */
+PIXI.CanvasRenderer.prototype.mapBlendModes = function()
+{
+    if(!PIXI.blendModesCanvas)
+    {
+        PIXI.blendModesCanvas = [];
+
+        if(PIXI.canUseNewCanvasBlendModes())
+        {
+            PIXI.blendModesCanvas[PIXI.blendModes.NORMAL]   = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.ADD]      = "lighter"; //IS THIS OK???
+            PIXI.blendModesCanvas[PIXI.blendModes.MULTIPLY] = "multiply";
+            PIXI.blendModesCanvas[PIXI.blendModes.SCREEN]   = "screen";
+            PIXI.blendModesCanvas[PIXI.blendModes.OVERLAY]  = "overlay";
+            PIXI.blendModesCanvas[PIXI.blendModes.DARKEN]   = "darken";
+            PIXI.blendModesCanvas[PIXI.blendModes.LIGHTEN]  = "lighten";
+            PIXI.blendModesCanvas[PIXI.blendModes.COLOR_DODGE] = "color-dodge";
+            PIXI.blendModesCanvas[PIXI.blendModes.COLOR_BURN] = "color-burn";
+            PIXI.blendModesCanvas[PIXI.blendModes.HARD_LIGHT] = "hard-light";
+            PIXI.blendModesCanvas[PIXI.blendModes.SOFT_LIGHT] = "soft-light";
+            PIXI.blendModesCanvas[PIXI.blendModes.DIFFERENCE] = "difference";
+            PIXI.blendModesCanvas[PIXI.blendModes.EXCLUSION] = "exclusion";
+            PIXI.blendModesCanvas[PIXI.blendModes.HUE]       = "hue";
+            PIXI.blendModesCanvas[PIXI.blendModes.SATURATION] = "saturation";
+            PIXI.blendModesCanvas[PIXI.blendModes.COLOR]      = "color";
+            PIXI.blendModesCanvas[PIXI.blendModes.LUMINOSITY] = "luminosity";
+        }
+        else
+        {
+            // this means that the browser does not support the cool new blend modes in canvas "cough" ie "cough"
+            PIXI.blendModesCanvas[PIXI.blendModes.NORMAL]   = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.ADD]      = "lighter"; //IS THIS OK???
+            PIXI.blendModesCanvas[PIXI.blendModes.MULTIPLY] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.SCREEN]   = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.OVERLAY]  = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.DARKEN]   = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.LIGHTEN]  = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.COLOR_DODGE] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.COLOR_BURN] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.HARD_LIGHT] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.SOFT_LIGHT] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.DIFFERENCE] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.EXCLUSION] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.HUE]       = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.SATURATION] = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.COLOR]      = "source-over";
+            PIXI.blendModesCanvas[PIXI.blendModes.LUMINOSITY] = "source-over";
+        }
+    }
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+
+/**
+ * A set of functions used by the canvas renderer to draw the primitive graphics data.
+ *
+ * @class CanvasGraphics
+ * @static
+ */
+PIXI.CanvasGraphics = function()
+{
+};
+
+/*
+ * Renders a PIXI.Graphics object to a canvas.
+ *
+ * @method renderGraphics
+ * @static
+ * @param graphics {Graphics} the actual graphics object to render
+ * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas
+ */
+PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
+{
+    var worldAlpha = graphics.worldAlpha;
+
+    if (graphics.dirty)
+    {
+        this.updateGraphicsTint(graphics);
+        graphics.dirty = false;
+    }
+
+    for (var i = 0; i < graphics.graphicsData.length; i++)
+    {
+        var data = graphics.graphicsData[i];
+        var shape = data.shape;
+
+        var fillColor = data._fillTint;
+        var lineColor = data._lineTint;
+
+        context.lineWidth = data.lineWidth;
+
+        if (data.type === PIXI.Graphics.POLY)
+        {
+            context.beginPath();
+
+            var points = shape.points;
+
+            context.moveTo(points[0], points[1]);
+
+            for (var j=1; j < points.length/2; j++)
+            {
+                context.lineTo(points[j * 2], points[j * 2 + 1]);
+            }
+
+            if (shape.closed)
+            {
+                context.lineTo(points[0], points[1]);
+            }
+
+            // if the first and last point are the same close the path - much neater :)
+            if (points[0] === points[points.length-2] && points[1] === points[points.length-1])
+            {
+                context.closePath();
+            }
+
+            if (data.fill)
+            {
+                context.globalAlpha = data.fillAlpha * worldAlpha;
+                context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
+                context.fill();
+            }
+
+            if (data.lineWidth)
+            {
+                context.globalAlpha = data.lineAlpha * worldAlpha;
+                context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
+                context.stroke();
+            }
+        }
+        else if (data.type === PIXI.Graphics.RECT)
+        {
+            if (data.fillColor || data.fillColor === 0)
+            {
+                context.globalAlpha = data.fillAlpha * worldAlpha;
+                context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
+                context.fillRect(shape.x, shape.y, shape.width, shape.height);
+            }
+
+            if (data.lineWidth)
+            {
+                context.globalAlpha = data.lineAlpha * worldAlpha;
+                context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
+                context.strokeRect(shape.x, shape.y, shape.width, shape.height);
+            }
+        }
+        else if (data.type === PIXI.Graphics.CIRC)
+        {
+            // TODO - need to be Undefined!
+            context.beginPath();
+            context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
+            context.closePath();
+
+            if (data.fill)
+            {
+                context.globalAlpha = data.fillAlpha * worldAlpha;
+                context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
+                context.fill();
+            }
+
+            if (data.lineWidth)
+            {
+                context.globalAlpha = data.lineAlpha * worldAlpha;
+                context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
+                context.stroke();
+            }
+        }
+        else if (data.type === PIXI.Graphics.ELIP)
+        {
+            // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
+
+            var w = shape.width * 2;
+            var h = shape.height * 2;
+
+            var x = shape.x - w/2;
+            var y = shape.y - h/2;
+
+            context.beginPath();
+
+            var kappa = 0.5522848,
+                ox = (w / 2) * kappa, // control point offset horizontal
+                oy = (h / 2) * kappa, // control point offset vertical
+                xe = x + w,           // x-end
+                ye = y + h,           // y-end
+                xm = x + w / 2,       // x-middle
+                ym = y + h / 2;       // y-middle
+
+            context.moveTo(x, ym);
+            context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
+            context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
+            context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
+            context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
+
+            context.closePath();
+
+            if (data.fill)
+            {
+                context.globalAlpha = data.fillAlpha * worldAlpha;
+                context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
+                context.fill();
+            }
+
+            if (data.lineWidth)
+            {
+                context.globalAlpha = data.lineAlpha * worldAlpha;
+                context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
+                context.stroke();
+            }
+        }
+        else if (data.type === PIXI.Graphics.RREC)
+        {
+            var rx = shape.x;
+            var ry = shape.y;
+            var width = shape.width;
+            var height = shape.height;
+            var radius = shape.radius;
+
+            var maxRadius = Math.min(width, height) / 2 | 0;
+            radius = radius > maxRadius ? maxRadius : radius;
+
+            context.beginPath();
+            context.moveTo(rx, ry + radius);
+            context.lineTo(rx, ry + height - radius);
+            context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
+            context.lineTo(rx + width - radius, ry + height);
+            context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
+            context.lineTo(rx + width, ry + radius);
+            context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
+            context.lineTo(rx + radius, ry);
+            context.quadraticCurveTo(rx, ry, rx, ry + radius);
+            context.closePath();
+
+            if (data.fillColor || data.fillColor === 0)
+            {
+                context.globalAlpha = data.fillAlpha * worldAlpha;
+                context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
+                context.fill();
+            }
+
+            if (data.lineWidth)
+            {
+                context.globalAlpha = data.lineAlpha * worldAlpha;
+                context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
+                context.stroke();
+            }
+        }
+    }
+};
+
+/*
+ * Renders a graphics mask
+ *
+ * @static
+ * @private
+ * @method renderGraphicsMask
+ * @param graphics {Graphics} the graphics which will be used as a mask
+ * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
+ */
+PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
+{
+    var len = graphics.graphicsData.length;
+
+    if (len === 0)
+    {
+        return;
+    }
+
+    context.beginPath();
+
+    for (var i = 0; i < len; i++)
+    {
+        var data = graphics.graphicsData[i];
+        var shape = data.shape;
+
+        if (data.type === PIXI.Graphics.POLY)
+        {
+
+            var points = shape.points;
+        
+            context.moveTo(points[0], points[1]);
+
+            for (var j=1; j < points.length/2; j++)
+            {
+                context.lineTo(points[j * 2], points[j * 2 + 1]);
+            }
+
+            // if the first and last point are the same close the path - much neater :)
+            if (points[0] === points[points.length-2] && points[1] === points[points.length-1])
+            {
+                context.closePath();
+            }
+
+        }
+        else if (data.type === PIXI.Graphics.RECT)
+        {
+            context.rect(shape.x, shape.y, shape.width, shape.height);
+            context.closePath();
+        }
+        else if (data.type === PIXI.Graphics.CIRC)
+        {
+            // TODO - need to be Undefined!
+            context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI);
+            context.closePath();
+        }
+        else if (data.type === PIXI.Graphics.ELIP)
+        {
+
+            // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
+
+            var w = shape.width * 2;
+            var h = shape.height * 2;
+
+            var x = shape.x - w/2;
+            var y = shape.y - h/2;
+
+            var kappa = 0.5522848,
+                ox = (w / 2) * kappa, // control point offset horizontal
+                oy = (h / 2) * kappa, // control point offset vertical
+                xe = x + w,           // x-end
+                ye = y + h,           // y-end
+                xm = x + w / 2,       // x-middle
+                ym = y + h / 2;       // y-middle
+
+            context.moveTo(x, ym);
+            context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
+            context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
+            context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
+            context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
+            context.closePath();
+        }
+        else if (data.type === PIXI.Graphics.RREC)
+        {
+
+            var rx = shape.x;
+            var ry = shape.y;
+            var width = shape.width;
+            var height = shape.height;
+            var radius = shape.radius;
+
+            var maxRadius = Math.min(width, height) / 2 | 0;
+            radius = radius > maxRadius ? maxRadius : radius;
+
+            context.moveTo(rx, ry + radius);
+            context.lineTo(rx, ry + height - radius);
+            context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
+            context.lineTo(rx + width - radius, ry + height);
+            context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
+            context.lineTo(rx + width, ry + radius);
+            context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
+            context.lineTo(rx + radius, ry);
+            context.quadraticCurveTo(rx, ry, rx, ry + radius);
+            context.closePath();
+        }
+    }
+};
+
+PIXI.CanvasGraphics.updateGraphicsTint = function(graphics)
+{
+    if (graphics.tint === 0xFFFFFF)
+    {
+        return;
+    }
+
+    var tintR = (graphics.tint >> 16 & 0xFF) / 255;
+    var tintG = (graphics.tint >> 8 & 0xFF) / 255;
+    var tintB = (graphics.tint & 0xFF)/ 255;
+
+    for (var i = 0; i < graphics.graphicsData.length; i++)
+    {
+        var data = graphics.graphicsData[i];
+
+        var fillColor = data.fillColor | 0;
+        var lineColor = data.lineColor | 0;
+
+        /*
+        var colorR = (fillColor >> 16 & 0xFF) / 255;
+        var colorG = (fillColor >> 8 & 0xFF) / 255;
+        var colorB = (fillColor & 0xFF) / 255; 
+
+        colorR *= tintR;
+        colorG *= tintG;
+        colorB *= tintB;
+
+        fillColor = ((colorR*255 << 16) + (colorG*255 << 8) + colorB*255);
+
+        colorR = (lineColor >> 16 & 0xFF) / 255;
+        colorG = (lineColor >> 8 & 0xFF) / 255;
+        colorB = (lineColor & 0xFF) / 255; 
+
+        colorR *= tintR;
+        colorG *= tintG;
+        colorB *= tintB;
+
+        lineColor = ((colorR*255 << 16) + (colorG*255 << 8) + colorB*255);   
+        */
+        
+        data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) +  (fillColor & 0xFF) / 255 * tintB*255);
+        data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) +  (lineColor & 0xFF) / 255 * tintB*255);
+
+    }
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+PIXI.BaseTextureCache = {};
+
+PIXI.BaseTextureCacheIdGenerator = 0;
+
+/**
+ * A texture stores the information that represents an image. All textures have a base texture.
+ *
+ * @class BaseTexture
+ * @uses EventTarget
+ * @constructor
+ * @param source {String} the source object (image or canvas)
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ */
+PIXI.BaseTexture = function(source, scaleMode)
+{
+    /**
+     * The Resolution of the texture. 
+     *
+     * @property resolution
+     * @type Number
+     */
+    this.resolution = 1;
+    
+    /**
+     * [read-only] The width of the base texture set when the image has loaded
+     *
+     * @property width
+     * @type Number
+     * @readOnly
+     */
+    this.width = 100;
+
+    /**
+     * [read-only] The height of the base texture set when the image has loaded
+     *
+     * @property height
+     * @type Number
+     * @readOnly
+     */
+    this.height = 100;
+
+    /**
+     * The scale mode to apply when scaling this texture
+     * 
+     * @property scaleMode
+     * @type {Number}
+     * @default PIXI.scaleModes.LINEAR
+     */
+    this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
+
+    /**
+     * [read-only] Set to true once the base texture has loaded
+     *
+     * @property hasLoaded
+     * @type Boolean
+     * @readOnly
+     */
+    this.hasLoaded = false;
+
+    /**
+     * The image source that is used to create the texture.
+     *
+     * @property source
+     * @type Image
+     */
+    this.source = source;
+
+    this._UID = PIXI._UID++;
+
+    /**
+     * Controls if RGB channels should be pre-multiplied by Alpha  (WebGL only)
+     *
+     * @property premultipliedAlpha
+     * @type Boolean
+     * @default true
+     */
+    this.premultipliedAlpha = true;
+
+    // used for webGL
+
+    /**
+     * @property _glTextures
+     * @type Array
+     * @private
+     */
+    this._glTextures = [];
+
+    /**
+     * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used
+     * Also the texture must be a power of two size to work
+     * 
+     * @property mipmap
+     * @type {Boolean}
+     */
+    this.mipmap = false;
+
+    /**
+     * @property _dirty
+     * @type Array
+     * @private
+     */
+    this._dirty = [true, true, true, true];
+
+    if (!source)
+    {
+        return;
+    }
+
+    if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height)
+    {
+        this.hasLoaded = true;
+        this.width = this.source.naturalWidth || this.source.width;
+        this.height = this.source.naturalHeight || this.source.height;
+        this.dirty();
+    }
+
+    /**
+     * @property imageUrl
+     * @type String
+     */
+    this.imageUrl = null;
+
+    /**
+     * @property _powerOf2
+     * @type Boolean
+     * @private
+     */
+    this._powerOf2 = false;
+
+};
+
+PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture;
+
+/**
+ * Forces this BaseTexture to be set as loaded, with the given width and height.
+ * Then calls BaseTexture.dirty.
+ * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have.
+ *
+ * @method forceLoaded
+ * @param {number} width - The new width to force the BaseTexture to be.
+ * @param {number} height - The new height to force the BaseTexture to be.
+ */
+PIXI.BaseTexture.prototype.forceLoaded = function(width, height)
+{
+    this.hasLoaded = true;
+    this.width = width;
+    this.height = height;
+    this.dirty();
+
+};
+
+/**
+ * Destroys this base texture
+ *
+ * @method destroy
+ */
+PIXI.BaseTexture.prototype.destroy = function()
+{
+    if (this.imageUrl)
+    {
+        delete PIXI.BaseTextureCache[this.imageUrl];
+        delete PIXI.TextureCache[this.imageUrl];
+
+        this.imageUrl = null;
+
+        if (!navigator.isCocoonJS) this.source.src = '';
+    }
+    else if (this.source && this.source._pixiId)
+    {
+        delete PIXI.BaseTextureCache[this.source._pixiId];
+    }
+
+    this.source = null;
+
+    this.unloadFromGPU();
+};
+
+/**
+ * Changes the source image of the texture
+ *
+ * @method updateSourceImage
+ * @param newSrc {String} the path of the image
+ */
+PIXI.BaseTexture.prototype.updateSourceImage = function(newSrc)
+{
+    this.hasLoaded = false;
+    this.source.src = null;
+    this.source.src = newSrc;
+};
+
+/**
+ * Sets all glTextures to be dirty.
+ *
+ * @method dirty
+ */
+PIXI.BaseTexture.prototype.dirty = function()
+{
+    for (var i = 0; i < this._glTextures.length; i++)
+    {
+        this._dirty[i] = true;
+    }
+};
+
+/**
+ * Removes the base texture from the GPU, useful for managing resources on the GPU.
+ * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it.
+ *
+ * @method unloadFromGPU
+ */
+PIXI.BaseTexture.prototype.unloadFromGPU = function()
+{
+    this.dirty();
+
+    // delete the webGL textures if any.
+    for (var i = this._glTextures.length - 1; i >= 0; i--)
+    {
+        var glTexture = this._glTextures[i];
+        var gl = PIXI.glContexts[i];
+
+        if(gl && glTexture)
+        {
+            gl.deleteTexture(glTexture);
+        }
+        
+    }
+
+    this._glTextures.length = 0;
+
+    this.dirty();
+};
+
+/**
+ * Helper function that creates a base texture from the given image url.
+ * If the image is not in the base texture cache it will be created and loaded.
+ *
+ * @static
+ * @method fromImage
+ * @param imageUrl {String} The image url of the texture
+ * @param crossorigin {Boolean}
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ * @return BaseTexture
+ */
+PIXI.BaseTexture.fromImage = function(imageUrl, crossorigin, scaleMode)
+{
+    var baseTexture = PIXI.BaseTextureCache[imageUrl];
+
+    if(crossorigin === undefined && imageUrl.indexOf('data:') === -1) crossorigin = true;
+
+    if(!baseTexture)
+    {
+        // new Image() breaks tex loading in some versions of Chrome.
+        // See https://code.google.com/p/chromium/issues/detail?id=238071
+        var image = new Image();//document.createElement('img');
+
+        if (crossorigin)
+        {
+            image.crossOrigin = '';
+        }
+
+        image.src = imageUrl;
+        baseTexture = new PIXI.BaseTexture(image, scaleMode);
+        baseTexture.imageUrl = imageUrl;
+        PIXI.BaseTextureCache[imageUrl] = baseTexture;
+
+        // if there is an @2x at the end of the url we are going to assume its a highres image
+        if( imageUrl.indexOf(PIXI.RETINA_PREFIX + '.') !== -1)
+        {
+            baseTexture.resolution = 2;
+        }
+    }
+
+    return baseTexture;
+};
+
+/**
+ * Helper function that creates a base texture from the given canvas element.
+ *
+ * @static
+ * @method fromCanvas
+ * @param canvas {Canvas} The canvas element source of the texture
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ * @return BaseTexture
+ */
+PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode)
+{
+    if(!canvas._pixiId)
+    {
+        canvas._pixiId = 'canvas_' + PIXI.TextureCacheIdGenerator++;
+    }
+
+    if (canvas.width === 0)
+    {
+        canvas.width = 1;
+    }
+
+    if (canvas.height === 0)
+    {
+        canvas.height = 1;
+    }
+
+    var baseTexture = PIXI.BaseTextureCache[canvas._pixiId];
+
+    if(!baseTexture)
+    {
+        baseTexture = new PIXI.BaseTexture(canvas, scaleMode);
+        PIXI.BaseTextureCache[canvas._pixiId] = baseTexture;
+    }
+
+    return baseTexture;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+PIXI.TextureCache = {};
+PIXI.FrameCache = {};
+
+/**
+ * TextureSilentFail is a boolean that defaults to `false`. 
+ * If `true` then `PIXI.Texture.setFrame` will no longer throw an error if the texture dimensions are incorrect. 
+ * Instead `Texture.valid` will be set to `false` (#1556)
+ *
+ * @type {boolean}
+ */
+PIXI.TextureSilentFail = false;
+
+PIXI.TextureCacheIdGenerator = 0;
+
+/**
+ * A texture stores the information that represents an image or part of an image. It cannot be added
+ * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used.
+ *
+ * @class Texture
+ * @uses EventTarget
+ * @constructor
+ * @param baseTexture {BaseTexture} The base texture source to create the texture from
+ * @param frame {Rectangle} The rectangle frame of the texture to show
+ * @param [crop] {Rectangle} The area of original texture 
+ * @param [trim] {Rectangle} Trimmed texture rectangle
+ */
+PIXI.Texture = function(baseTexture, frame, crop, trim)
+{
+    /**
+     * Does this Texture have any frame data assigned to it?
+     *
+     * @property noFrame
+     * @type Boolean
+     */
+    this.noFrame = false;
+
+    if (!frame)
+    {
+        this.noFrame = true;
+        frame = new PIXI.Rectangle(0,0,1,1);
+    }
+
+    if (baseTexture instanceof PIXI.Texture)
+    {
+        baseTexture = baseTexture.baseTexture;
+    }
+
+    /**
+     * The base texture that this texture uses.
+     *
+     * @property baseTexture
+     * @type BaseTexture
+     */
+    this.baseTexture = baseTexture;
+
+    /**
+     * The frame specifies the region of the base texture that this texture uses
+     *
+     * @property frame
+     * @type Rectangle
+     */
+    this.frame = frame;
+
+    /**
+     * The texture trim data.
+     *
+     * @property trim
+     * @type Rectangle
+     */
+    this.trim = trim;
+
+    /**
+     * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
+     *
+     * @property valid
+     * @type Boolean
+     */
+    this.valid = false;
+
+    /**
+     * Is this a tiling texture? As used by the likes of a TilingSprite.
+     *
+     * @property isTiling
+     * @type Boolean
+     */
+    this.isTiling = false;
+
+    /**
+     * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates)
+     *
+     * @property requiresUpdate
+     * @type Boolean
+     */
+    this.requiresUpdate = false;
+
+    /**
+     * This will let a renderer know that a tinted parent has updated its texture.
+     *
+     * @property requiresReTint
+     * @type Boolean
+     */
+    this.requiresReTint = false;
+
+    /**
+     * The WebGL UV data cache.
+     *
+     * @property _uvs
+     * @type Object
+     * @private
+     */
+    this._uvs = null;
+
+    /**
+     * The width of the Texture in pixels.
+     *
+     * @property width
+     * @type Number
+     */
+    this.width = 0;
+
+    /**
+     * The height of the Texture in pixels.
+     *
+     * @property height
+     * @type Number
+     */
+    this.height = 0;
+
+    /**
+     * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
+     * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
+     *
+     * @property crop
+     * @type Rectangle
+     */
+    this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1);
+
+    if (baseTexture.hasLoaded)
+    {
+        if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
+        this.setFrame(frame);
+    }
+
+};
+
+PIXI.Texture.prototype.constructor = PIXI.Texture;
+
+/**
+ * Called when the base texture is loaded
+ *
+ * @method onBaseTextureLoaded
+ * @private
+ */
+PIXI.Texture.prototype.onBaseTextureLoaded = function()
+{
+    var baseTexture = this.baseTexture;
+
+    if (this.noFrame)
+    {
+        this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
+    }
+
+    this.setFrame(this.frame);
+};
+
+/**
+ * Destroys this texture
+ *
+ * @method destroy
+ * @param destroyBase {Boolean} Whether to destroy the base texture as well
+ */
+PIXI.Texture.prototype.destroy = function(destroyBase)
+{
+    if (destroyBase) this.baseTexture.destroy();
+
+    this.valid = false;
+};
+
+/**
+ * Specifies the region of the baseTexture that this texture will use.
+ *
+ * @method setFrame
+ * @param frame {Rectangle} The frame of the texture to set it to
+ */
+PIXI.Texture.prototype.setFrame = function(frame)
+{
+    this.noFrame = false;
+
+    this.frame = frame;
+    this.width = frame.width;
+    this.height = frame.height;
+
+    this.crop.x = frame.x;
+    this.crop.y = frame.y;
+    this.crop.width = frame.width;
+    this.crop.height = frame.height;
+
+    if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height))
+    {
+        if (!PIXI.TextureSilentFail)
+        {
+            throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this);
+        }
+
+        this.valid = false;
+        return;
+    }
+
+    this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded;
+
+    if (this.trim)
+    {
+        this.width = this.trim.width;
+        this.height = this.trim.height;
+        this.frame.width = this.trim.width;
+        this.frame.height = this.trim.height;
+    }
+    
+    if (this.valid) this._updateUvs();
+
+};
+
+/**
+ * Updates the internal WebGL UV cache.
+ *
+ * @method _updateUvs
+ * @private
+ */
+PIXI.Texture.prototype._updateUvs = function()
+{
+    if(!this._uvs)this._uvs = new PIXI.TextureUvs();
+
+    var frame = this.crop;
+    var tw = this.baseTexture.width;
+    var th = this.baseTexture.height;
+    
+    this._uvs.x0 = frame.x / tw;
+    this._uvs.y0 = frame.y / th;
+
+    this._uvs.x1 = (frame.x + frame.width) / tw;
+    this._uvs.y1 = frame.y / th;
+
+    this._uvs.x2 = (frame.x + frame.width) / tw;
+    this._uvs.y2 = (frame.y + frame.height) / th;
+
+    this._uvs.x3 = frame.x / tw;
+    this._uvs.y3 = (frame.y + frame.height) / th;
+};
+
+/**
+ * Helper function that creates a Texture object from the given image url.
+ * If the image is not in the texture cache it will be  created and loaded.
+ *
+ * @static
+ * @method fromImage
+ * @param imageUrl {String} The image url of the texture
+ * @param crossorigin {Boolean} Whether requests should be treated as crossorigin
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ * @return Texture
+ */
+PIXI.Texture.fromImage = function(imageUrl, crossorigin, scaleMode)
+{
+    var texture = PIXI.TextureCache[imageUrl];
+
+    if(!texture)
+    {
+        texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin, scaleMode));
+        PIXI.TextureCache[imageUrl] = texture;
+    }
+
+    return texture;
+};
+
+/**
+ * Helper function that returns a Texture objected based on the given frame id.
+ * If the frame id is not in the texture cache an error will be thrown.
+ *
+ * @static
+ * @method fromFrame
+ * @param frameId {String} The frame id of the texture
+ * @return Texture
+ */
+PIXI.Texture.fromFrame = function(frameId)
+{
+    var texture = PIXI.TextureCache[frameId];
+    if(!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ');
+    return texture;
+};
+
+/**
+ * Helper function that creates a new a Texture based on the given canvas element.
+ *
+ * @static
+ * @method fromCanvas
+ * @param canvas {Canvas} The canvas element source of the texture
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ * @return Texture
+ */
+PIXI.Texture.fromCanvas = function(canvas, scaleMode)
+{
+    var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode);
+
+    return new PIXI.Texture(baseTexture);
+
+};
+
+/**
+ * Adds a texture to the global PIXI.TextureCache. This cache is shared across the whole PIXI object.
+ *
+ * @static
+ * @method addTextureToCache
+ * @param texture {Texture} The Texture to add to the cache.
+ * @param id {String} The id that the texture will be stored against.
+ */
+PIXI.Texture.addTextureToCache = function(texture, id)
+{
+    PIXI.TextureCache[id] = texture;
+};
+
+/**
+ * Remove a texture from the global PIXI.TextureCache.
+ *
+ * @static
+ * @method removeTextureFromCache
+ * @param id {String} The id of the texture to be removed
+ * @return {Texture} The texture that was removed
+ */
+PIXI.Texture.removeTextureFromCache = function(id)
+{
+    var texture = PIXI.TextureCache[id];
+    delete PIXI.TextureCache[id];
+    delete PIXI.BaseTextureCache[id];
+    return texture;
+};
+
+PIXI.TextureUvs = function()
+{
+    this.x0 = 0;
+    this.y0 = 0;
+
+    this.x1 = 0;
+    this.y1 = 0;
+
+    this.x2 = 0;
+    this.y2 = 0;
+
+    this.x3 = 0;
+    this.y3 = 0;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it.
+ *
+ * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded otherwise black rectangles will be drawn instead.
+ *
+ * A RenderTexture takes a snapshot of any Display Object given to its render method. The position and rotation of the given Display Objects is ignored. For example:
+ *
+ *    var renderTexture = new PIXI.RenderTexture(800, 600);
+ *    var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
+ *    sprite.position.x = 800/2;
+ *    sprite.position.y = 600/2;
+ *    sprite.anchor.x = 0.5;
+ *    sprite.anchor.y = 0.5;
+ *    renderTexture.render(sprite);
+ *
+ * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual position a DisplayObjectContainer should be used:
+ *
+ *    var doc = new PIXI.DisplayObjectContainer();
+ *    doc.addChild(sprite);
+ *    renderTexture.render(doc);  // Renders to center of renderTexture
+ *
+ * @class RenderTexture
+ * @extends Texture
+ * @constructor
+ * @param width {Number} The width of the render texture
+ * @param height {Number} The height of the render texture
+ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used for this RenderTexture
+ * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
+ * @param resolution {Number} The resolution of the texture being generated
+ */
+PIXI.RenderTexture = function(width, height, renderer, scaleMode, resolution)
+{
+    /**
+     * The with of the render texture
+     *
+     * @property width
+     * @type Number
+     */
+    this.width = width || 100;
+
+    /**
+     * The height of the render texture
+     *
+     * @property height
+     * @type Number
+     */
+    this.height = height || 100;
+
+    /**
+     * The Resolution of the texture.
+     *
+     * @property resolution
+     * @type Number
+     */
+    this.resolution = resolution || 1;
+
+    /**
+     * The framing rectangle of the render texture
+     *
+     * @property frame
+     * @type Rectangle
+     */
+    this.frame = new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);
+
+    /**
+     * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
+     * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
+     *
+     * @property crop
+     * @type Rectangle
+     */
+    this.crop = new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);
+
+    /**
+     * The base texture object that this texture uses
+     *
+     * @property baseTexture
+     * @type BaseTexture
+     */
+    this.baseTexture = new PIXI.BaseTexture();
+    this.baseTexture.width = this.width * this.resolution;
+    this.baseTexture.height = this.height * this.resolution;
+    this.baseTexture._glTextures = [];
+    this.baseTexture.resolution = this.resolution;
+
+    this.baseTexture.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
+
+    this.baseTexture.hasLoaded = true;
+
+    PIXI.Texture.call(this,
+        this.baseTexture,
+        new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution)
+    );
+
+    /**
+     * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL.
+     *
+     * @property renderer
+     * @type CanvasRenderer|WebGLRenderer
+     */
+    this.renderer = renderer || PIXI.defaultRenderer;
+
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        var gl = this.renderer.gl;
+        this.baseTexture._dirty[gl.id] = false;
+
+        this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode);
+        this.baseTexture._glTextures[gl.id] =  this.textureBuffer.texture;
+
+        this.render = this.renderWebGL;
+        this.projection = new PIXI.Point(this.width * 0.5, -this.height * 0.5);
+    }
+    else
+    {
+        this.render = this.renderCanvas;
+        this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution);
+        this.baseTexture.source = this.textureBuffer.canvas;
+    }
+
+    /**
+     * @property valid
+     * @type Boolean
+     */
+    this.valid = true;
+
+    this.tempMatrix = new Phaser.Matrix();
+
+    this._updateUvs();
+};
+
+PIXI.RenderTexture.prototype = Object.create(PIXI.Texture.prototype);
+PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture;
+
+/**
+ * Resizes the RenderTexture.
+ *
+ * @method resize
+ * @param width {Number} The width to resize to.
+ * @param height {Number} The height to resize to.
+ * @param updateBase {Boolean} Should the baseTexture.width and height values be resized as well?
+ */
+PIXI.RenderTexture.prototype.resize = function(width, height, updateBase)
+{
+    if (width === this.width && height === this.height)return;
+
+    this.valid = (width > 0 && height > 0);
+
+    this.width = width;
+    this.height = height;
+    this.frame.width = this.crop.width = width * this.resolution;
+    this.frame.height = this.crop.height = height * this.resolution;
+
+    if (updateBase)
+    {
+        this.baseTexture.width = this.width * this.resolution;
+        this.baseTexture.height = this.height * this.resolution;
+    }
+
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        this.projection.x = this.width / 2;
+        this.projection.y = -this.height / 2;
+    }
+
+    if(!this.valid)return;
+
+    this.textureBuffer.resize(this.width, this.height);
+};
+
+/**
+ * Clears the RenderTexture.
+ *
+ * @method clear
+ */
+PIXI.RenderTexture.prototype.clear = function()
+{
+    if (!this.valid)
+    {
+        return;
+    }
+
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
+    }
+
+    this.textureBuffer.clear();
+};
+
+/**
+ * This function will draw the display object to the texture.
+ *
+ * @method renderWebGL
+ * @param displayObject {DisplayObject} The display object to render this texture on
+ * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
+ * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn
+ * @private
+ */
+PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, matrix, clear)
+{
+    if (!this.valid || displayObject.alpha === 0)
+    {
+        return;
+    }
+   
+    //  Let's create a nice matrix to apply to our display object.
+    //  Frame buffers come in upside down so we need to flip the matrix.
+    var wt = displayObject.worldTransform;
+    wt.identity();
+    wt.translate(0, this.projection.y * 2);
+
+    if (matrix)
+    {
+        wt.append(matrix);
+    }
+
+    wt.scale(1, -1);
+
+    //  Time to update all the children of the displayObject with the new matrix.
+    for (var i = 0; i < displayObject.children.length; i++)
+    {
+        displayObject.children[i].updateTransform();
+    }
+    
+    //  Time for the webGL fun stuff!
+    var gl = this.renderer.gl;
+
+    gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution);
+
+    gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer );
+
+    if (clear)
+    {
+        this.textureBuffer.clear();
+    }
+
+    this.renderer.spriteBatch.dirty = true;
+
+    this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix);
+
+    this.renderer.spriteBatch.dirty = true;
+
+};
+
+/**
+ * This function will draw the display object to the texture.
+ *
+ * @method renderCanvas
+ * @param displayObject {DisplayObject} The display object to render this texture on
+ * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
+ * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn
+ * @private
+ */
+PIXI.RenderTexture.prototype.renderCanvas = function(displayObject, matrix, clear)
+{
+    if (!this.valid || displayObject.alpha === 0)
+    {
+        return;
+    }
+
+    // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!)
+    for (var i = 0; i < displayObject.children.length; i++)
+    {
+        displayObject.children[i].updateTransform();
+    }
+
+    if (clear)
+    {
+        this.textureBuffer.clear();
+    }
+
+    var realResolution = this.renderer.resolution;
+
+    this.renderer.resolution = this.resolution;
+
+    this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix);
+
+    this.renderer.resolution = realResolution;
+};
+
+/**
+ * Will return a HTML Image of the texture
+ *
+ * @method getImage
+ * @return {Image}
+ */
+PIXI.RenderTexture.prototype.getImage = function()
+{
+    var image = new Image();
+    image.src = this.getBase64();
+    return image;
+};
+
+/**
+ * Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that.
+ *
+ * @method getBase64
+ * @return {String} A base64 encoded string of the texture.
+ */
+PIXI.RenderTexture.prototype.getBase64 = function()
+{
+    return this.getCanvas().toDataURL();
+};
+
+/**
+ * Creates a Canvas element, renders this RenderTexture to it and then returns it.
+ *
+ * @method getCanvas
+ * @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
+ */
+PIXI.RenderTexture.prototype.getCanvas = function()
+{
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        var gl =  this.renderer.gl;
+        var width = this.textureBuffer.width;
+        var height = this.textureBuffer.height;
+
+        var webGLPixels = new Uint8Array(4 * width * height);
+
+        gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
+        gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels);
+        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+
+        var tempCanvas = new PIXI.CanvasBuffer(width, height);
+        var canvasData = tempCanvas.context.getImageData(0, 0, width, height);
+        canvasData.data.set(webGLPixels);
+
+        tempCanvas.context.putImageData(canvasData, 0, 0);
+
+        return tempCanvas.canvas;
+    }
+    else
+    {
+        return this.textureBuffer.canvas;
+    }
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * This is the base class for creating a PIXI filter. Currently only webGL supports filters.
+ * If you want to make a custom filter this should be your base class.
+ * @class AbstractFilter
+ * @constructor
+ * @param fragmentSrc {Array} The fragment source in an array of strings.
+ * @param uniforms {Object} An object containing the uniforms for this filter.
+ */
+PIXI.AbstractFilter = function(fragmentSrc, uniforms)
+{
+    /**
+    * An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
+    * For example the blur filter has two passes blurX and blurY.
+    * @property passes
+    * @type Array(Filter)
+    * @private
+    */
+    this.passes = [this];
+
+    /**
+    * @property shaders
+    * @type Array(Shader)
+    * @private
+    */
+    this.shaders = [];
+    
+    /**
+    * @property dirty
+    * @type Boolean
+    */
+    this.dirty = true;
+
+    /**
+    * @property padding
+    * @type Number
+    */
+    this.padding = 0;
+
+    /**
+    * @property uniforms
+    * @type object
+    * @private
+    */
+    this.uniforms = uniforms || {};
+
+    /**
+    * @property fragmentSrc
+    * @type Array
+    * @private
+    */
+    this.fragmentSrc = fragmentSrc || [];
+};
+
+PIXI.AbstractFilter.prototype.constructor = PIXI.AbstractFilter;
+
+/**
+ * Syncs the uniforms between the class object and the shaders.
+ *
+ * @method syncUniforms
+ */
+PIXI.AbstractFilter.prototype.syncUniforms = function()
+{
+    for(var i=0,j=this.shaders.length; i<j; i++)
+    {
+        this.shaders[i].dirty = true;
+    }
+};
+
+/*
+PIXI.AbstractFilter.prototype.apply = function(frameBuffer)
+{
+    // TODO :)
+};
+*/
+/**
+ * @author Mat Groves http://matgroves.com/
+ */
+
+ /**
+ *
+ * @class Strip
+ * @extends DisplayObjectContainer
+ * @constructor
+ * @param texture {Texture} The texture to use
+ * @param width {Number} the width
+ * @param height {Number} the height
+ *
+ */
+PIXI.Strip = function(texture)
+{
+    PIXI.DisplayObjectContainer.call( this );
+
+
+    /**
+     * The texture of the strip
+     *
+     * @property texture
+     * @type Texture
+     */
+    this.texture = texture;
+
+    // set up the main bits..
+    this.uvs = new PIXI.Float32Array([0, 1,
+                                      1, 1,
+                                      1, 0,
+                                      0, 1]);
+
+    this.vertices = new PIXI.Float32Array([0, 0,
+                                            100, 0,
+                                            100, 100,
+                                            0, 100]);
+
+    this.colors = new PIXI.Float32Array([1, 1, 1, 1]);
+
+    this.indices = new PIXI.Uint16Array([0, 1, 2, 3]);
+
+    /**
+     * Whether the strip is dirty or not
+     *
+     * @property dirty
+     * @type Boolean
+     */
+    this.dirty = true;
+
+    /**
+     * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode.
+     *
+     * @property blendMode
+     * @type Number
+     * @default PIXI.blendModes.NORMAL;
+     */
+    this.blendMode = PIXI.blendModes.NORMAL;
+
+    /**
+     * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.
+     *
+     * @property canvasPadding
+     * @type Number
+     */
+    this.canvasPadding = 0;
+
+    this.drawMode = PIXI.Strip.DrawModes.TRIANGLE_STRIP;
+
+};
+
+// constructor
+PIXI.Strip.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
+PIXI.Strip.prototype.constructor = PIXI.Strip;
+
+PIXI.Strip.prototype._renderWebGL = function(renderSession)
+{
+    // if the sprite is not visible or the alpha is 0 then no need to render this element
+    if(!this.visible || this.alpha <= 0)return;
+    // render triangle strip..
+
+    renderSession.spriteBatch.stop();
+
+    // init! init!
+    if(!this._vertexBuffer)this._initWebGL(renderSession);
+
+    renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader);
+
+    this._renderStrip(renderSession);
+
+    ///renderSession.shaderManager.activateDefaultShader();
+
+    renderSession.spriteBatch.start();
+
+    //TODO check culling
+};
+
+PIXI.Strip.prototype._initWebGL = function(renderSession)
+{
+    // build the strip!
+    var gl = renderSession.gl;
+
+    this._vertexBuffer = gl.createBuffer();
+    this._indexBuffer = gl.createBuffer();
+    this._uvBuffer = gl.createBuffer();
+    this._colorBuffer = gl.createBuffer();
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER,  this.uvs, gl.STATIC_DRAW);
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer);
+    gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW);
+
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
+    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
+};
+
+PIXI.Strip.prototype._renderStrip = function(renderSession)
+{
+    var gl = renderSession.gl;
+    var projection = renderSession.projection,
+        offset = renderSession.offset,
+        shader = renderSession.shaderManager.stripShader;
+
+    var drawMode = this.drawMode === PIXI.Strip.DrawModes.TRIANGLE_STRIP ? gl.TRIANGLE_STRIP : gl.TRIANGLES;
+
+    // gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mat4Real);
+
+    renderSession.blendModeManager.setBlendMode(this.blendMode);
+
+
+    // set uniforms
+    gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true));
+    gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
+    gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
+    gl.uniform1f(shader.alpha, this.worldAlpha);
+
+    if(!this.dirty)
+    {
+
+        gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+        gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
+        gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
+
+        // update the uvs
+        gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
+        gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
+
+        gl.activeTexture(gl.TEXTURE0);
+
+        // check if a texture is dirty..
+        if(this.texture.baseTexture._dirty[gl.id])
+        {
+            renderSession.renderer.updateTexture(this.texture.baseTexture);
+        }
+        else
+        {
+            // bind the current texture
+            gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]);
+        }
+
+        // dont need to upload!
+        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
+
+
+    }
+    else
+    {
+
+        this.dirty = false;
+        gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+        gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW);
+        gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
+
+        // update the uvs
+        gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
+        gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
+        gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
+
+        gl.activeTexture(gl.TEXTURE0);
+
+        // check if a texture is dirty..
+        if(this.texture.baseTexture._dirty[gl.id])
+        {
+            renderSession.renderer.updateTexture(this.texture.baseTexture);
+        }
+        else
+        {
+            gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]);
+        }
+
+        // dont need to upload!
+        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
+        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
+
+    }
+    //console.log(gl.TRIANGLE_STRIP)
+    //
+    //
+    gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0);
+
+
+};
+
+
+
+PIXI.Strip.prototype._renderCanvas = function(renderSession)
+{
+    var context = renderSession.context;
+
+    var transform = this.worldTransform;
+
+    if (renderSession.roundPixels)
+    {
+        context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0);
+    }
+    else
+    {
+        context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
+    }
+
+    if (this.drawMode === PIXI.Strip.DrawModes.TRIANGLE_STRIP)
+    {
+        this._renderCanvasTriangleStrip(context);
+    }
+    else
+    {
+        this._renderCanvasTriangles(context);
+    }
+};
+
+PIXI.Strip.prototype._renderCanvasTriangleStrip = function(context)
+{
+    // draw triangles!!
+    var vertices = this.vertices;
+    var uvs = this.uvs;
+
+    var length = vertices.length / 2;
+    this.count++;
+
+    for (var i = 0; i < length - 2; i++) {
+        // draw some triangles!
+        var index = i * 2;
+        this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4));
+    }
+};
+
+PIXI.Strip.prototype._renderCanvasTriangles = function(context)
+{
+    // draw triangles!!
+    var vertices = this.vertices;
+    var uvs = this.uvs;
+    var indices = this.indices;
+
+    var length = indices.length;
+    this.count++;
+
+    for (var i = 0; i < length; i += 3) {
+        // draw some triangles!
+        var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2;
+        this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2);
+    }
+};
+
+PIXI.Strip.prototype._renderCanvasDrawTriangle = function(context, vertices, uvs, index0, index1, index2)
+{
+    var textureSource = this.texture.baseTexture.source;
+    var textureWidth = this.texture.width;
+    var textureHeight = this.texture.height;
+
+    var x0 = vertices[index0], x1 = vertices[index1], x2 = vertices[index2];
+    var y0 = vertices[index0 + 1], y1 = vertices[index1 + 1], y2 = vertices[index2 + 1];
+
+    var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth;
+    var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight;
+
+    if (this.canvasPadding > 0) {
+        var paddingX = this.canvasPadding / this.worldTransform.a;
+        var paddingY = this.canvasPadding / this.worldTransform.d;
+        var centerX = (x0 + x1 + x2) / 3;
+        var centerY = (y0 + y1 + y2) / 3;
+
+        var normX = x0 - centerX;
+        var normY = y0 - centerY;
+
+        var dist = Math.sqrt(normX * normX + normY * normY);
+        x0 = centerX + (normX / dist) * (dist + paddingX);
+        y0 = centerY + (normY / dist) * (dist + paddingY);
+
+        //
+
+        normX = x1 - centerX;
+        normY = y1 - centerY;
+
+        dist = Math.sqrt(normX * normX + normY * normY);
+        x1 = centerX + (normX / dist) * (dist + paddingX);
+        y1 = centerY + (normY / dist) * (dist + paddingY);
+
+        normX = x2 - centerX;
+        normY = y2 - centerY;
+
+        dist = Math.sqrt(normX * normX + normY * normY);
+        x2 = centerX + (normX / dist) * (dist + paddingX);
+        y2 = centerY + (normY / dist) * (dist + paddingY);
+    }
+
+    context.save();
+    context.beginPath();
+
+
+    context.moveTo(x0, y0);
+    context.lineTo(x1, y1);
+    context.lineTo(x2, y2);
+
+    context.closePath();
+
+    context.clip();
+
+    // Compute matrix transform
+    var delta =  (u0 * v1)      + (v0 * u2)      + (u1 * v2)      - (v1 * u2)      - (v0 * u1)      - (u0 * v2);
+    var deltaA = (x0 * v1)      + (v0 * x2)      + (x1 * v2)      - (v1 * x2)      - (v0 * x1)      - (x0 * v2);
+    var deltaB = (u0 * x1)      + (x0 * u2)      + (u1 * x2)      - (x1 * u2)      - (x0 * u1)      - (u0 * x2);
+    var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2);
+    var deltaD = (y0 * v1)      + (v0 * y2)      + (y1 * v2)      - (v1 * y2)      - (v0 * y1)      - (y0 * v2);
+    var deltaE = (u0 * y1)      + (y0 * u2)      + (u1 * y2)      - (y1 * u2)      - (y0 * u1)      - (u0 * y2);
+    var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2);
+
+    context.transform(deltaA / delta, deltaD / delta,
+        deltaB / delta, deltaE / delta,
+        deltaC / delta, deltaF / delta);
+
+    context.drawImage(textureSource, 0, 0);
+    context.restore();
+};
+
+
+
+/**
+ * Renders a flat strip
+ *
+ * @method renderStripFlat
+ * @param strip {Strip} The Strip to render
+ * @private
+ */
+PIXI.Strip.prototype.renderStripFlat = function(strip)
+{
+    var context = this.context;
+    var vertices = strip.vertices;
+
+    var length = vertices.length/2;
+    this.count++;
+
+    context.beginPath();
+    for (var i=1; i < length-2; i++)
+    {
+        // draw some triangles!
+        var index = i*2;
+
+        var x0 = vertices[index],   x1 = vertices[index+2], x2 = vertices[index+4];
+        var y0 = vertices[index+1], y1 = vertices[index+3], y2 = vertices[index+5];
+
+        context.moveTo(x0, y0);
+        context.lineTo(x1, y1);
+        context.lineTo(x2, y2);
+    }
+
+    context.fillStyle = '#FF0000';
+    context.fill();
+    context.closePath();
+};
+
+/*
+PIXI.Strip.prototype.setTexture = function(texture)
+{
+    //TODO SET THE TEXTURES
+    //TODO VISIBILITY
+
+    // stop current texture
+    this.texture = texture;
+    this.width   = texture.frame.width;
+    this.height  = texture.frame.height;
+    this.updateFrame = true;
+};
+*/
+
+/**
+ * When the texture is updated, this event will fire to update the scale and frame
+ *
+ * @method onTextureUpdate
+ * @param event
+ * @private
+ */
+
+PIXI.Strip.prototype.onTextureUpdate = function()
+{
+    this.updateFrame = true;
+};
+
+/**
+ * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
+ *
+ * @method getBounds
+ * @param matrix {Matrix} the transformation matrix of the sprite
+ * @return {Rectangle} the framing rectangle
+ */
+PIXI.Strip.prototype.getBounds = function(matrix)
+{
+    var worldTransform = matrix || this.worldTransform;
+
+    var a = worldTransform.a;
+    var b = worldTransform.b;
+    var c = worldTransform.c;
+    var d = worldTransform.d;
+    var tx = worldTransform.tx;
+    var ty = worldTransform.ty;
+
+    var maxX = -Infinity;
+    var maxY = -Infinity;
+
+    var minX = Infinity;
+    var minY = Infinity;
+
+    var vertices = this.vertices;
+    for (var i = 0, n = vertices.length; i < n; i += 2)
+    {
+        var rawX = vertices[i], rawY = vertices[i + 1];
+        var x = (a * rawX) + (c * rawY) + tx;
+        var y = (d * rawY) + (b * rawX) + ty;
+
+        minX = x < minX ? x : minX;
+        minY = y < minY ? y : minY;
+
+        maxX = x > maxX ? x : maxX;
+        maxY = y > maxY ? y : maxY;
+    }
+
+    if (minX === -Infinity || maxY === Infinity)
+    {
+        return PIXI.EmptyRectangle;
+    }
+
+    var bounds = this._bounds;
+
+    bounds.x = minX;
+    bounds.width = maxX - minX;
+
+    bounds.y = minY;
+    bounds.height = maxY - minY;
+
+    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
+    this._currentBounds = bounds;
+
+    return bounds;
+};
+
+/**
+ * Different drawing buffer modes supported
+ *
+ * @property
+ * @type {{TRIANGLE_STRIP: number, TRIANGLES: number}}
+ * @static
+ */
+PIXI.Strip.DrawModes = {
+    TRIANGLE_STRIP: 0,
+    TRIANGLES: 1
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ * @copyright Mat Groves, Rovanion Luckey
+ */
+
+/**
+ *
+ * @class Rope
+ * @constructor
+ * @extends Strip
+ * @param {Texture} texture - The texture to use on the rope.
+ * @param {Array} points - An array of {PIXI.Point}.
+ *
+ */
+PIXI.Rope = function(texture, points)
+{
+    PIXI.Strip.call( this, texture );
+    this.points = points;
+
+    this.vertices = new PIXI.Float32Array(points.length * 4);
+    this.uvs = new PIXI.Float32Array(points.length * 4);
+    this.colors = new PIXI.Float32Array(points.length * 2);
+    this.indices = new PIXI.Uint16Array(points.length * 2);
+
+
+    this.refresh();
+};
+
+
+// constructor
+PIXI.Rope.prototype = Object.create( PIXI.Strip.prototype );
+PIXI.Rope.prototype.constructor = PIXI.Rope;
+
+/*
+ * Refreshes
+ *
+ * @method refresh
+ */
+PIXI.Rope.prototype.refresh = function()
+{
+    var points = this.points;
+    if(points.length < 1) return;
+
+    var uvs = this.uvs;
+
+    var lastPoint = points[0];
+    var indices = this.indices;
+    var colors = this.colors;
+
+    this.count-=0.2;
+
+    uvs[0] = 0;
+    uvs[1] = 0;
+    uvs[2] = 0;
+    uvs[3] = 1;
+
+    colors[0] = 1;
+    colors[1] = 1;
+
+    indices[0] = 0;
+    indices[1] = 1;
+
+    var total = points.length,
+        point, index, amount;
+
+    for (var i = 1; i < total; i++)
+    {
+        point = points[i];
+        index = i * 4;
+        // time to do some smart drawing!
+        amount = i / (total-1);
+
+        if(i%2)
+        {
+            uvs[index] = amount;
+            uvs[index+1] = 0;
+
+            uvs[index+2] = amount;
+            uvs[index+3] = 1;
+        }
+        else
+        {
+            uvs[index] = amount;
+            uvs[index+1] = 0;
+
+            uvs[index+2] = amount;
+            uvs[index+3] = 1;
+        }
+
+        index = i * 2;
+        colors[index] = 1;
+        colors[index+1] = 1;
+
+        index = i * 2;
+        indices[index] = index;
+        indices[index + 1] = index + 1;
+
+        lastPoint = point;
+    }
+};
+
+/*
+ * Updates the object transform for rendering
+ *
+ * @method updateTransform
+ * @private
+ */
+PIXI.Rope.prototype.updateTransform = function()
+{
+
+    var points = this.points;
+    if(points.length < 1)return;
+
+    var lastPoint = points[0];
+    var nextPoint;
+    var perp = {x:0, y:0};
+
+    this.count-=0.2;
+
+    var vertices = this.vertices;
+    var total = points.length,
+        point, index, ratio, perpLength, num;
+
+    for (var i = 0; i < total; i++)
+    {
+        point = points[i];
+        index = i * 4;
+
+        if(i < points.length-1)
+        {
+            nextPoint = points[i+1];
+        }
+        else
+        {
+            nextPoint = point;
+        }
+
+        perp.y = -(nextPoint.x - lastPoint.x);
+        perp.x = nextPoint.y - lastPoint.y;
+
+        ratio = (1 - (i / (total-1))) * 10;
+
+        if(ratio > 1) ratio = 1;
+
+        perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y);
+        num = this.texture.height / 2; //(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
+        perp.x /= perpLength;
+        perp.y /= perpLength;
+
+        perp.x *= num;
+        perp.y *= num;
+
+        vertices[index] = point.x + perp.x;
+        vertices[index+1] = point.y + perp.y;
+        vertices[index+2] = point.x - perp.x;
+        vertices[index+3] = point.y - perp.y;
+
+        lastPoint = point;
+    }
+
+    PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
+};
+/*
+ * Sets the texture that the Rope will use
+ *
+ * @method setTexture
+ * @param texture {Texture} the texture that will be used
+ */
+PIXI.Rope.prototype.setTexture = function(texture)
+{
+    // stop current texture
+    this.texture = texture;
+    //this.updateFrame = true;
+};
+
+/**
+ * @author Mat Groves http://matgroves.com/
+ */
+
+/**
+ * A tiling sprite is a fast way of rendering a tiling image
+ *
+ * @class TilingSprite
+ * @extends Sprite
+ * @constructor
+ * @param texture {Texture} the texture of the tiling sprite
+ * @param width {Number}  the width of the tiling sprite
+ * @param height {Number} the height of the tiling sprite
+ */
+PIXI.TilingSprite = function(texture, width, height)
+{
+    PIXI.Sprite.call(this, texture);
+
+    /**
+     * The width of the tiling sprite
+     *
+     * @property width
+     * @type Number
+     */
+    this._width = width || 128;
+
+    /**
+     * The height of the tiling sprite
+     *
+     * @property height
+     * @type Number
+     */
+    this._height = height || 128;
+
+    /**
+     * The scaling of the image that is being tiled
+     *
+     * @property tileScale
+     * @type Point
+     */
+    this.tileScale = new PIXI.Point(1, 1);
+
+    /**
+     * A point that represents the scale of the texture object
+     *
+     * @property tileScaleOffset
+     * @type Point
+     */
+    this.tileScaleOffset = new PIXI.Point(1, 1);
+    
+    /**
+     * The offset position of the image that is being tiled
+     *
+     * @property tilePosition
+     * @type Point
+     */
+    this.tilePosition = new PIXI.Point();
+
+    /**
+     * Whether this sprite is renderable or not
+     *
+     * @property renderable
+     * @type Boolean
+     * @default true
+     */
+    this.renderable = true;
+
+    /**
+     * The tint applied to the sprite. This is a hex value
+     *
+     * @property tint
+     * @type Number
+     * @default 0xFFFFFF
+     */
+    this.tint = 0xFFFFFF;
+
+    /**
+     * If enabled a green rectangle will be drawn behind the generated tiling texture, allowing you to visually
+     * debug the texture being used.
+     *
+     * @property textureDebug
+     * @type Boolean
+     */
+    this.textureDebug = false;
+    
+    /**
+     * The blend mode to be applied to the sprite
+     *
+     * @property blendMode
+     * @type Number
+     * @default PIXI.blendModes.NORMAL;
+     */
+    this.blendMode = PIXI.blendModes.NORMAL;
+
+    /**
+     * The CanvasBuffer object that the tiled texture is drawn to.
+     *
+     * @property canvasBuffer
+     * @type PIXI.CanvasBuffer
+     */
+    this.canvasBuffer = null;
+
+    /**
+     * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture.
+     *
+     * @property tilingTexture
+     * @type PIXI.Texture
+     */
+    this.tilingTexture = null;
+
+    /**
+     * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL).
+     *
+     * @property tilePattern
+     * @type PIXI.Texture
+     */
+    this.tilePattern = null;
+
+    /**
+     * If true the TilingSprite will run generateTexture on its **next** render pass.
+     * This is set by the likes of Phaser.LoadTexture.setFrame.
+     *
+     * @property refreshTexture
+     * @type Boolean
+     * @default true
+     */
+    this.refreshTexture = true;
+
+    this.frameWidth = 0;
+    this.frameHeight = 0;
+
+};
+
+PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
+PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;
+
+PIXI.TilingSprite.prototype.setTexture = function(texture)
+{
+    if (this.texture !== texture)
+    {
+        this.texture = texture;
+        this.refreshTexture = true;
+        this.cachedTint = 0xFFFFFF;
+    }
+
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method _renderWebGL
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
+{
+    if (this.visible === false || this.alpha === 0)
+    {
+        return;
+    }
+
+    if (this._mask)
+    {
+        renderSession.spriteBatch.stop();
+        renderSession.maskManager.pushMask(this.mask, renderSession);
+        renderSession.spriteBatch.start();
+    }
+
+    if (this._filters)
+    {
+        renderSession.spriteBatch.flush();
+        renderSession.filterManager.pushFilter(this._filterBlock);
+    }
+
+    if (this.refreshTexture)
+    {
+        this.generateTilingTexture(true);
+
+        if (this.tilingTexture)
+        {
+            if (this.tilingTexture.needsUpdate)
+            {
+                renderSession.renderer.updateTexture(this.tilingTexture.baseTexture);
+                this.tilingTexture.needsUpdate = false;
+            }
+        }
+        else
+        {
+            return;
+        }
+    }
+    
+    renderSession.spriteBatch.renderTilingSprite(this);
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i]._renderWebGL(renderSession);
+    }
+
+    renderSession.spriteBatch.stop();
+
+    if (this._filters)
+    {
+        renderSession.filterManager.popFilter();
+    }
+
+    if (this._mask)
+    {
+        renderSession.maskManager.popMask(this._mask, renderSession);
+    }
+    
+    renderSession.spriteBatch.start();
+
+};
+
+/**
+* Renders the object using the Canvas renderer
+*
+* @method _renderCanvas
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
+{
+    if (this.visible === false || this.alpha === 0)
+    {
+        return;
+    }
+    
+    var context = renderSession.context;
+
+    if (this._mask)
+    {
+        renderSession.maskManager.pushMask(this._mask, renderSession);
+    }
+
+    context.globalAlpha = this.worldAlpha;
+    
+    var wt = this.worldTransform;
+    var resolution = renderSession.resolution;
+
+    context.setTransform(wt.a * resolution,
+                         wt.b * resolution,
+                         wt.c * resolution,
+                         wt.d * resolution,
+                         wt.tx * resolution,
+                         wt.ty * resolution);
+
+    if (this.refreshTexture)
+    {
+        this.generateTilingTexture(false);
+    
+        if (this.tilingTexture)
+        {
+            this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
+        }
+        else
+        {
+            return;
+        }
+    }
+
+    var sessionBlendMode = renderSession.currentBlendMode;
+
+    //  Check blend mode
+    if (this.blendMode !== renderSession.currentBlendMode)
+    {
+        renderSession.currentBlendMode = this.blendMode;
+        context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
+    }
+
+    var tilePosition = this.tilePosition;
+    var tileScale = this.tileScale;
+
+    tilePosition.x %= this.tilingTexture.baseTexture.width;
+    tilePosition.y %= this.tilingTexture.baseTexture.height;
+
+    //  Translate
+    context.scale(tileScale.x, tileScale.y);
+    context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height));
+
+    context.fillStyle = this.tilePattern;
+
+    var tx = -tilePosition.x;
+    var ty = -tilePosition.y;
+    var tw = this._width / tileScale.x;
+    var th = this._height / tileScale.y;
+
+    //  Allow for pixel rounding
+    if (renderSession.roundPixels)
+    {
+        tx | 0;
+        ty | 0;
+        tw | 0;
+        th | 0;
+    }
+
+    context.fillRect(tx, ty, tw, th);
+
+    //  Translate back again
+    context.scale(1 / tileScale.x, 1 / tileScale.y);
+    context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height));
+
+    if (this._mask)
+    {
+        renderSession.maskManager.popMask(renderSession);
+    }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i]._renderCanvas(renderSession);
+    }
+
+    //  Reset blend mode
+    if (sessionBlendMode !== this.blendMode)
+    {
+        renderSession.currentBlendMode = sessionBlendMode;
+        context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode];
+    }
+
+};
+
+/**
+ * When the texture is updated, this event will fire to update the scale and frame
+ *
+ * @method onTextureUpdate
+ * @param event
+ * @private
+ */
+PIXI.TilingSprite.prototype.onTextureUpdate = function()
+{
+   // overriding the sprite version of this!
+};
+
+/**
+* 
+* @method generateTilingTexture
+* 
+* @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
+*/
+PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
+{
+    if (!this.texture.baseTexture.hasLoaded)
+    {
+        return;
+    }
+
+    var texture = this.texture;
+    var frame = texture.frame;
+
+    var targetWidth = this._frame.sourceSizeW;
+    var targetHeight = this._frame.sourceSizeH;
+
+    var dx = 0;
+    var dy = 0;
+
+    if (this._frame.trimmed)
+    {
+        dx = this._frame.spriteSourceSizeX;
+        dy = this._frame.spriteSourceSizeY;
+    }
+
+    if (forcePowerOfTwo)
+    {
+        targetWidth = PIXI.getNextPowerOfTwo(targetWidth);
+        targetHeight = PIXI.getNextPowerOfTwo(targetHeight);
+    }
+
+    if (this.canvasBuffer)
+    {
+        this.canvasBuffer.resize(targetWidth, targetHeight);
+        this.tilingTexture.baseTexture.width = targetWidth;
+        this.tilingTexture.baseTexture.height = targetHeight;
+        this.tilingTexture.needsUpdate = true;
+    }
+    else
+    {
+        this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
+        this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas);
+        this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas);
+        this.tilingTexture.isTiling = true;
+        this.tilingTexture.needsUpdate = true;
+    }
+
+    if (this.textureDebug)
+    {
+        this.canvasBuffer.context.strokeStyle = '#00ff00';
+        this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight);
+    }
+
+    //  If a sprite sheet we need this:
+    var w = texture.crop.width;
+    var h = texture.crop.height;
+
+    if (w !== targetWidth || h !== targetHeight)
+    {
+        w = targetWidth;
+        h = targetHeight;
+    }
+
+    this.canvasBuffer.context.drawImage(texture.baseTexture.source,
+                           texture.crop.x,
+                           texture.crop.y,
+                           texture.crop.width,
+                           texture.crop.height,
+                           dx,
+                           dy,
+                           w,
+                           h);
+
+    this.tileScaleOffset.x = frame.width / targetWidth;
+    this.tileScaleOffset.y = frame.height / targetHeight;
+
+    this.refreshTexture = false;
+
+    this.tilingTexture.baseTexture._powerOf2 = true;
+
+};
+
+/**
+* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
+*
+* @method getBounds
+* @return {Rectangle} the framing rectangle
+*/
+PIXI.TilingSprite.prototype.getBounds = function()
+{
+    var width = this._width;
+    var height = this._height;
+
+    var w0 = width * (1-this.anchor.x);
+    var w1 = width * -this.anchor.x;
+
+    var h0 = height * (1-this.anchor.y);
+    var h1 = height * -this.anchor.y;
+
+    var worldTransform = this.worldTransform;
+
+    var a = worldTransform.a;
+    var b = worldTransform.b;
+    var c = worldTransform.c;
+    var d = worldTransform.d;
+    var tx = worldTransform.tx;
+    var ty = worldTransform.ty;
+    
+    var x1 = a * w1 + c * h1 + tx;
+    var y1 = d * h1 + b * w1 + ty;
+
+    var x2 = a * w0 + c * h1 + tx;
+    var y2 = d * h1 + b * w0 + ty;
+
+    var x3 = a * w0 + c * h0 + tx;
+    var y3 = d * h0 + b * w0 + ty;
+
+    var x4 =  a * w1 + c * h0 + tx;
+    var y4 =  d * h0 + b * w1 + ty;
+
+    var maxX = -Infinity;
+    var maxY = -Infinity;
+
+    var minX = Infinity;
+    var minY = Infinity;
+
+    minX = x1 < minX ? x1 : minX;
+    minX = x2 < minX ? x2 : minX;
+    minX = x3 < minX ? x3 : minX;
+    minX = x4 < minX ? x4 : minX;
+
+    minY = y1 < minY ? y1 : minY;
+    minY = y2 < minY ? y2 : minY;
+    minY = y3 < minY ? y3 : minY;
+    minY = y4 < minY ? y4 : minY;
+
+    maxX = x1 > maxX ? x1 : maxX;
+    maxX = x2 > maxX ? x2 : maxX;
+    maxX = x3 > maxX ? x3 : maxX;
+    maxX = x4 > maxX ? x4 : maxX;
+
+    maxY = y1 > maxY ? y1 : maxY;
+    maxY = y2 > maxY ? y2 : maxY;
+    maxY = y3 > maxY ? y3 : maxY;
+    maxY = y4 > maxY ? y4 : maxY;
+
+    var bounds = this._bounds;
+
+    bounds.x = minX;
+    bounds.width = maxX - minX;
+
+    bounds.y = minY;
+    bounds.height = maxY - minY;
+
+    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
+    this._currentBounds = bounds;
+
+    return bounds;
+};
+
+PIXI.TilingSprite.prototype.destroy = function () {
+
+    PIXI.Sprite.prototype.destroy.call(this);
+
+    this.tileScale = null;
+    this.tileScaleOffset = null;
+    this.tilePosition = null;
+
+    if (this.tilingTexture)
+    {
+        this.tilingTexture.destroy(true);
+        this.tilingTexture = null;
+    }
+
+};
+
+/**
+ * The width of the sprite, setting this will actually modify the scale to achieve the value set
+ *
+ * @property width
+ * @type Number
+ */
+Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
+
+    get: function() {
+        return this._width;
+    },
+
+    set: function(value) {
+        this._width = value;
+    }
+
+});
+
+/**
+ * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
+ *
+ * @property height
+ * @type Number
+ */
+Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
+
+    get: function() {
+        return  this._height;
+    },
+
+    set: function(value) {
+        this._height = value;
+    }
+
+});
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+    if (typeof exports !== 'undefined') {
+        if (typeof module !== 'undefined' && module.exports) {
+            exports = module.exports = PIXI;
+        }
+        exports.PIXI = PIXI;
+    } else if (typeof define !== 'undefined' && define.amd) {
+        define('PIXI', (function() { return root.PIXI = PIXI; })() );
+    } else {
+        root.PIXI = PIXI;
+    }
+
+    return PIXI;
+}).call(this);
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+(function(){
+
+    var root = this;
+
+/* global Phaser:true */
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* @namespace Phaser
+*/
+var Phaser = Phaser || {
+
+    /**
+    * The Phaser version number.
+    * @constant
+    * @type {string}
+    */
+    VERSION: '2.4.2',
+
+    /**
+    * An array of Phaser game instances.
+    * @constant
+    * @type {array}
+    */
+    GAMES: [],
+
+    /**
+    * AUTO renderer - picks between WebGL or Canvas based on device.
+    * @constant
+    * @type {integer}
+    */
+    AUTO: 0,
+
+    /**
+    * Canvas Renderer.
+    * @constant
+    * @type {integer}
+    */
+    CANVAS: 1,
+
+    /**
+    * WebGL Renderer.
+    * @constant
+    * @type {integer}
+    */
+    WEBGL: 2,
+
+    /**
+    * Headless renderer (not visual output)
+    * @constant
+    * @type {integer}
+    */
+    HEADLESS: 3,
+
+    /**
+    * Direction constant.
+    * @constant
+    * @type {integer}
+    */
+    NONE: 0,
+
+    /**
+    * Direction constant.
+    * @constant
+    * @type {integer}
+    */
+    LEFT: 1,
+
+    /**
+    * Direction constant.
+    * @constant
+    * @type {integer}
+    */
+    RIGHT: 2,
+
+    /**
+    * Direction constant.
+    * @constant
+    * @type {integer}
+    */
+    UP: 3,
+
+    /**
+    * Direction constant.
+    * @constant
+    * @type {integer}
+    */
+    DOWN: 4,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    SPRITE: 0,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    BUTTON: 1,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    IMAGE: 2,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    GRAPHICS: 3,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    TEXT: 4,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    TILESPRITE: 5,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    BITMAPTEXT: 6,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    GROUP: 7,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    RENDERTEXTURE: 8,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    TILEMAP: 9,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    TILEMAPLAYER: 10,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    EMITTER: 11,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    POLYGON: 12,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    BITMAPDATA: 13,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    CANVAS_FILTER: 14,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    WEBGL_FILTER: 15,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    ELLIPSE: 16,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    SPRITEBATCH: 17,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    RETROFONT: 18,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    POINTER: 19,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    ROPE: 20,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    CIRCLE: 21,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    RECTANGLE: 22,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    LINE: 23,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    MATRIX: 24,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    POINT: 25,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    ROUNDEDRECTANGLE: 26,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    CREATURE: 27,
+
+    /**
+    * Game Object type.
+    * @constant
+    * @type {integer}
+    */
+    VIDEO: 28,
+
+    /**
+     * Various blend modes supported by Pixi.
+     * 
+     * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
+     * 
+     * @constant
+     * @property {Number} blendModes.NORMAL
+     * @property {Number} blendModes.ADD
+     * @property {Number} blendModes.MULTIPLY
+     * @property {Number} blendModes.SCREEN
+     * @property {Number} blendModes.OVERLAY
+     * @property {Number} blendModes.DARKEN
+     * @property {Number} blendModes.LIGHTEN
+     * @property {Number} blendModes.COLOR_DODGE
+     * @property {Number} blendModes.COLOR_BURN
+     * @property {Number} blendModes.HARD_LIGHT
+     * @property {Number} blendModes.SOFT_LIGHT
+     * @property {Number} blendModes.DIFFERENCE
+     * @property {Number} blendModes.EXCLUSION
+     * @property {Number} blendModes.HUE
+     * @property {Number} blendModes.SATURATION
+     * @property {Number} blendModes.COLOR
+     * @property {Number} blendModes.LUMINOSITY
+     * @static
+     */
+    blendModes: {
+        NORMAL:0,
+        ADD:1,
+        MULTIPLY:2,
+        SCREEN:3,
+        OVERLAY:4,
+        DARKEN:5,
+        LIGHTEN:6,
+        COLOR_DODGE:7,
+        COLOR_BURN:8,
+        HARD_LIGHT:9,
+        SOFT_LIGHT:10,
+        DIFFERENCE:11,
+        EXCLUSION:12,
+        HUE:13,
+        SATURATION:14,
+        COLOR:15,
+        LUMINOSITY:16
+    },
+
+    /**
+     * The scale modes that are supported by Pixi.
+     *
+     * The DEFAULT scale mode affects the default scaling mode of future operations.
+     * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
+     *
+     * @constant
+     * @property {Object} Phaser.scaleModes
+     * @property {Number} scaleModes.DEFAULT=LINEAR
+     * @property {Number} scaleModes.LINEAR Smooth scaling
+     * @property {Number} scaleModes.NEAREST Pixelating scaling
+     * @static
+     */
+    scaleModes: {
+        DEFAULT:0,
+        LINEAR:0,
+        NEAREST:1
+    },
+
+    PIXI: PIXI || {}
+
+};
+
+/**
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
+if (!Math.trunc) {
+    Math.trunc = function trunc(x) {
+        return x < 0 ? Math.ceil(x) : Math.floor(x);
+    };
+}
+
+/**
+* A polyfill for Function.prototype.bind
+*/
+if (!Function.prototype.bind) {
+
+    /* jshint freeze: false */
+    Function.prototype.bind = (function () {
+
+        var slice = Array.prototype.slice;
+
+        return function (thisArg) {
+
+            var target = this, boundArgs = slice.call(arguments, 1);
+
+            if (typeof target !== 'function')
+            {
+                throw new TypeError();
+            }
+
+            function bound() {
+                var args = boundArgs.concat(slice.call(arguments));
+                target.apply(this instanceof bound ? this : thisArg, args);
+            }
+
+            bound.prototype = (function F(proto) {
+                if (proto)
+                {
+                    F.prototype = proto;
+                }
+
+                if (!(this instanceof F))
+                {
+                    /* jshint supernew: true */
+                    return new F;
+                }
+            })(target.prototype);
+
+            return bound;
+        };
+    })();
+}
+
+/**
+* A polyfill for Array.isArray
+*/
+if (!Array.isArray)
+{
+    Array.isArray = function (arg)
+    {
+        return Object.prototype.toString.call(arg) == '[object Array]';
+    };
+}
+
+/**
+* A polyfill for Array.forEach
+* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
+*/
+if (!Array.prototype.forEach)
+{
+    Array.prototype.forEach = function(fun /*, thisArg */)
+    {
+        "use strict";
+
+        if (this === void 0 || this === null)
+        {
+            throw new TypeError();
+        }
+
+        var t = Object(this);
+        var len = t.length >>> 0;
+
+        if (typeof fun !== "function")
+        {
+            throw new TypeError();
+        }
+
+        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+
+        for (var i = 0; i < len; i++)
+        {
+            if (i in t)
+            {
+                fun.call(thisArg, t[i], i, t);
+            }
+        }
+    };
+}
+
+/**
+* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9
+* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/
+* Cameron Foale (http://www.kibibu.com)
+*/
+if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object")
+{
+    var CheapArray = function(type)
+    {
+        var proto = new Array(); // jshint ignore:line
+
+        window[type] = function(arg) {
+
+            if (typeof(arg) === "number")
+            {
+                Array.call(this, arg);
+                this.length = arg;
+
+                for (var i = 0; i < this.length; i++)
+                {
+                    this[i] = 0;
+                }
+            }
+            else
+            {
+                Array.call(this, arg.length);
+
+                this.length = arg.length;
+
+                for (var i = 0; i < this.length; i++)
+                {
+                    this[i] = arg[i];
+                }
+            }
+        };
+
+        window[type].prototype = proto;
+        window[type].constructor = window[type];
+    };
+
+    CheapArray('Uint32Array'); // jshint ignore:line
+    CheapArray('Int16Array');  // jshint ignore:line
+}
+
+/**
+ * Also fix for the absent console in IE9
+ */
+if (!window.console)
+{
+    window.console = {};
+    window.console.log = window.console.assert = function(){};
+    window.console.warn = window.console.assert = function(){};
+}
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* @class Phaser.Utils
+* @static
+*/
+Phaser.Utils = {
+
+    /**
+     * Gets an objects property by string.
+     *
+     * @method Phaser.Utils.getProperty
+     * @param {object} obj - The object to traverse.
+     * @param {string} prop - The property whose value will be returned.
+     * @return {*} the value of the property or null if property isn't found .
+     */
+    getProperty: function(obj, prop) {
+
+        var parts = prop.split('.'),
+            last = parts.pop(),
+            l = parts.length,
+            i = 1,
+            current = parts[0];
+
+        while (i < l && (obj = obj[current]))
+        {
+            current = parts[i];
+            i++;
+        }
+
+        if (obj)
+        {
+            return obj[last];
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+     * Sets an objects property by string.
+     *
+     * @method Phaser.Utils.setProperty
+     * @param {object} obj - The object to traverse
+     * @param {string} prop - The property whose value will be changed
+     * @return {object} The object on which the property was set.
+     */
+    setProperty: function(obj, prop, value) {
+
+        var parts = prop.split('.'),
+            last = parts.pop(),
+            l = parts.length,
+            i = 1,
+            current = parts[0];
+
+        while (i < l && (obj = obj[current]))
+        {
+            current = parts[i];
+            i++;
+        }
+
+        if (obj)
+        {
+            obj[last] = value;
+        }
+
+        return obj;
+
+    },
+
+    /**
+    * Generate a random bool result based on the chance value.
+    *
+    * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
+    * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
+    *
+    * @method Phaser.Math#chanceRoll
+    * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
+    * @return {boolean} True if the roll passed, or false otherwise.
+    */
+    chanceRoll: function (chance) {
+        if (chance === undefined) { chance = 50; }
+        return chance > 0 && (Math.random() * 100 <= chance);
+    },
+
+    /**
+    * Choose between one of two values randomly.
+    *
+    * @method Phaser.Utils#randomChoice
+    * @param {any} choice1
+    * @param {any} choice2
+    * @return {any} The randomly selected choice
+    */
+    randomChoice: function (choice1, choice2) {
+        return (Math.random() < 0.5) ? choice1 : choice2;
+    },
+
+    /**
+    * Get a unit dimension from a string.
+    *
+    * @method Phaser.Utils.parseDimension
+    * @param {string|number} size - The size to parse.
+    * @param {number} dimension - The window dimension to check.
+    * @return {number} The parsed dimension.
+    */
+    parseDimension: function (size, dimension) {
+
+        var f = 0;
+        var px = 0;
+
+        if (typeof size === 'string')
+        {
+            //  %?
+            if (size.substr(-1) === '%')
+            {
+                f = parseInt(size, 10) / 100;
+
+                if (dimension === 0)
+                {
+                    px = window.innerWidth * f;
+                }
+                else
+                {
+                    px = window.innerHeight * f;
+                }
+            }
+            else
+            {
+                px = parseInt(size, 10);
+            }
+        }
+        else
+        {
+            px = size;
+        }
+
+        return px;
+
+    },
+
+    /**
+    * JavaScript string pad http://www.webtoolkit.info/.
+    *
+    * @method Phaser.Utils.pad
+    * @param {string} str - The target string.
+    * @param {integer} [len=0] - The number of characters to be added.
+    * @param {string} [pad=" "] - The string to pad it out with (defaults to a space).
+    * @param {integer} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
+    * @return {string} The padded string
+    */
+    pad: function (str, len, pad, dir) {
+
+        if (len === undefined) { var len = 0; }
+        if (pad === undefined) { var pad = ' '; }
+        if (dir === undefined) { var dir = 3; }
+
+        var padlen = 0;
+
+        if (len + 1 >= str.length)
+        {
+            switch (dir)
+            {
+                case 1:
+                    str = new Array(len + 1 - str.length).join(pad) + str;
+                    break;
+
+                case 3:
+                    var right = Math.ceil((padlen = len - str.length) / 2);
+                    var left = padlen - right;
+                    str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
+                    break;
+
+                default:
+                    str = str + new Array(len + 1 - str.length).join(pad);
+                    break;
+            }
+        }
+
+        return str;
+
+    },
+
+    /**
+    * This is a slightly modified version of jQuery.isPlainObject.
+    * A plain object is an object whose internal class property is [object Object].
+    * @method Phaser.Utils.isPlainObject
+    * @param {object} obj - The object to inspect.
+    * @return {boolean} - true if the object is plain, otherwise false.
+    */
+    isPlainObject: function (obj) {
+
+        // Not plain objects:
+        // - Any object or value whose internal [[Class]] property is not "[object Object]"
+        // - DOM nodes
+        // - window
+        if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
+        {
+            return false;
+        }
+
+        // Support: Firefox <20
+        // The try/catch suppresses exceptions thrown when attempting to access
+        // the "constructor" property of certain host objects, ie. |window.location|
+        // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
+        try {
+            if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
+            {
+                return false;
+            }
+        } catch (e) {
+            return false;
+        }
+
+        // If the function hasn't returned already, we're confident that
+        // |obj| is a plain object, created by {} or constructed with new Object
+        return true;
+    },
+
+    /**
+    * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
+    * 
+    * @method Phaser.Utils.extend
+    * @param {boolean} deep - Perform a deep copy?
+    * @param {object} target - The target object to copy to.
+    * @return {object} The extended object.
+    */
+    extend: function () {
+
+        var options, name, src, copy, copyIsArray, clone,
+            target = arguments[0] || {},
+            i = 1,
+            length = arguments.length,
+            deep = false;
+
+        // Handle a deep copy situation
+        if (typeof target === "boolean")
+        {
+            deep = target;
+            target = arguments[1] || {};
+            // skip the boolean and the target
+            i = 2;
+        }
+
+        // extend Phaser if only one argument is passed
+        if (length === i)
+        {
+            target = this;
+            --i;
+        }
+
+        for (; i < length; i++)
+        {
+            // Only deal with non-null/undefined values
+            if ((options = arguments[i]) != null)
+            {
+                // Extend the base object
+                for (name in options)
+                {
+                    src = target[name];
+                    copy = options[name];
+
+                    // Prevent never-ending loop
+                    if (target === copy)
+                    {
+                        continue;
+                    }
+
+                    // Recurse if we're merging plain objects or arrays
+                    if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
+                    {
+                        if (copyIsArray)
+                        {
+                            copyIsArray = false;
+                            clone = src && Array.isArray(src) ? src : [];
+                        }
+                        else
+                        {
+                            clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
+                        }
+
+                        // Never move original objects, clone them
+                        target[name] = Phaser.Utils.extend(deep, clone, copy);
+
+                    // Don't bring in undefined values
+                    }
+                    else if (copy !== undefined)
+                    {
+                        target[name] = copy;
+                    }
+                }
+            }
+        }
+
+        // Return the modified object
+        return target;
+
+    },
+
+    /**
+    * Mixes in an existing mixin object with the target.
+    *
+    * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty`
+    * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and
+    * the result is assigned directly.
+    *
+    * @method Phaser.Utils.mixinPrototype
+    * @param {object} target - The target object to receive the new functions.
+    * @param {object} mixin - The object to copy the functions from.
+    * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not?
+    */
+    mixinPrototype: function (target, mixin, replace) {
+    
+        if (replace === undefined) { replace = false; }
+
+        var mixinKeys = Object.keys(mixin);
+
+        for (var i = 0; i < mixinKeys.length; i++)
+        {
+            var key = mixinKeys[i];
+            var value = mixin[key];
+
+            if (!replace && (key in target))
+            {
+                //  Not overwriting existing property
+                continue;
+            }
+            else
+            {
+                if (value &&
+                    (typeof value.get === 'function' || typeof value.set === 'function'))
+                {
+                    //  Special case for classes like Phaser.Point which has a 'set' function!
+                    if (typeof value.clone === 'function')
+                    {
+                        target[key] = value.clone();
+                    }
+                    else
+                    {
+                        Object.defineProperty(target, key, value);
+                    }
+                }
+                else
+                {
+                    target[key] = value;
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Mixes the source object into the destination object, returning the newly modified destination object.
+    * Based on original code by @mudcube
+    *
+    * @method Phaser.Utils.mixin
+    * @param {object} from - The object to copy (the source object).
+    * @param {object} to - The object to copy to (the destination object).
+    * @return {object} The modified destination object.
+    */
+    mixin: function (from, to) {
+
+        if (!from || typeof (from) !== "object")
+        {
+            return to;
+        }
+
+        for (var key in from)
+        {
+            var o = from[key];
+
+            if (o.childNodes || o.cloneNode)
+            {
+                continue;
+            }
+
+            var type = typeof (from[key]);
+
+            if (!from[key] || type !== "object")
+            {
+                to[key] = from[key];
+            }
+            else
+            {
+                //  Clone sub-object
+                if (typeof (to[key]) === type)
+                {
+                    to[key] = Phaser.Utils.mixin(from[key], to[key]);
+                }
+                else
+                {
+                    to[key] = Phaser.Utils.mixin(from[key], new o.constructor());
+                }
+            }
+        }
+
+        return to;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter.
+* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
+* 
+* @class Phaser.Circle
+* @constructor
+* @param {number} [x=0] - The x coordinate of the center of the circle.
+* @param {number} [y=0] - The y coordinate of the center of the circle.
+* @param {number} [diameter=0] - The diameter of the circle.
+*/
+Phaser.Circle = function (x, y, diameter) {
+
+    x = x || 0;
+    y = y || 0;
+    diameter = diameter || 0;
+
+    /**
+    * @property {number} x - The x coordinate of the center of the circle.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - The y coordinate of the center of the circle.
+    */
+    this.y = y;
+
+    /**
+    * @property {number} _diameter - The diameter of the circle.
+    * @private
+    */
+    this._diameter = diameter;
+
+    /**
+   * @property {number} _radius - The radius of the circle.
+   * @private
+   */
+    this._radius = 0;
+
+    if (diameter > 0)
+    {
+        this._radius = diameter * 0.5;
+    }
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.CIRCLE;
+
+};
+
+Phaser.Circle.prototype = {
+
+    /**
+    * The circumference of the circle.
+    * 
+    * @method Phaser.Circle#circumference
+    * @return {number} The circumference of the circle.
+    */
+    circumference: function () {
+
+        return 2 * (Math.PI * this._radius);
+
+    },
+
+    /**
+    * Returns a uniformly distributed random point from anywhere within this Circle.
+    * 
+    * @method Phaser.Circle#random
+    * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
+    *     If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
+    * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
+    */
+    random: function (out) {
+
+        if (out === undefined) { out = new Phaser.Point(); }
+
+        var t = 2 * Math.PI * Math.random();
+        var u = Math.random() + Math.random();
+        var r = (u > 1) ? 2 - u : u;
+        var x = r * Math.cos(t);
+        var y = r * Math.sin(t);
+
+        out.x = this.x + (x * this.radius);
+        out.y = this.y + (y * this.radius);
+
+        return out;
+
+    },
+
+    /**
+    * Returns the framing rectangle of the circle as a Phaser.Rectangle object.
+    * 
+    * @method Phaser.Circle#getBounds
+    * @return {Phaser.Rectangle} The bounds of the Circle.
+    */
+    getBounds: function () {
+
+        return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter);
+
+    },
+
+    /**
+    * Sets the members of Circle to the specified values.
+    * @method Phaser.Circle#setTo
+    * @param {number} x - The x coordinate of the center of the circle.
+    * @param {number} y - The y coordinate of the center of the circle.
+    * @param {number} diameter - The diameter of the circle.
+    * @return {Circle} This circle object.
+    */
+    setTo: function (x, y, diameter) {
+
+        this.x = x;
+        this.y = y;
+        this._diameter = diameter;
+        this._radius = diameter * 0.5;
+
+        return this;
+
+    },
+
+    /**
+    * Copies the x, y and diameter properties from any given object to this Circle.
+    * @method Phaser.Circle#copyFrom
+    * @param {any} source - The object to copy from.
+    * @return {Circle} This Circle object.
+    */
+    copyFrom: function (source) {
+
+        return this.setTo(source.x, source.y, source.diameter);
+
+    },
+
+    /**
+    * Copies the x, y and diameter properties from this Circle to any given object.
+    * @method Phaser.Circle#copyTo
+    * @param {any} dest - The object to copy to.
+    * @return {object} This dest object.
+    */
+    copyTo: function (dest) {
+
+        dest.x = this.x;
+        dest.y = this.y;
+        dest.diameter = this._diameter;
+
+        return dest;
+
+    },
+
+    /**
+    * Returns the distance from the center of the Circle object to the given object
+    * (can be Circle, Point or anything with x/y properties)
+    * @method Phaser.Circle#distance
+    * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
+    * @param {boolean} [round=false] - Round the distance to the nearest integer.
+    * @return {number} The distance between this Point object and the destination Point object.
+    */
+    distance: function (dest, round) {
+
+        var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
+        return round ? Math.round(distance) : distance;
+
+    },
+
+    /**
+    * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
+    * @method Phaser.Circle#clone
+    * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
+    * @return {Phaser.Circle} The cloned Circle object.
+    */
+    clone: function (output) {
+
+        if (output === undefined || output === null)
+        {
+            output = new Phaser.Circle(this.x, this.y, this.diameter);
+        }
+        else
+        {
+            output.setTo(this.x, this.y, this.diameter);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Return true if the given x/y coordinates are within this Circle object.
+    * @method Phaser.Circle#contains
+    * @param {number} x - The X value of the coordinate to test.
+    * @param {number} y - The Y value of the coordinate to test.
+    * @return {boolean} True if the coordinates are within this circle, otherwise false.
+    */
+    contains: function (x, y) {
+
+        return Phaser.Circle.contains(this, x, y);
+
+    },
+
+    /**
+    * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
+    * @method Phaser.Circle#circumferencePoint
+    * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
+    * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
+    * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
+    * @return {Phaser.Point} The Point object holding the result.
+    */
+    circumferencePoint: function (angle, asDegrees, out) {
+
+        return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
+
+    },
+
+    /**
+    * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
+    * @method Phaser.Circle#offset
+    * @param {number} dx - Moves the x value of the Circle object by this amount.
+    * @param {number} dy - Moves the y value of the Circle object by this amount.
+    * @return {Circle} This Circle object.
+    */
+    offset: function (dx, dy) {
+
+        this.x += dx;
+        this.y += dy;
+
+        return this;
+
+    },
+
+    /**
+    * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter.
+    * @method Phaser.Circle#offsetPoint
+    * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
+    * @return {Circle} This Circle object.
+    */
+    offsetPoint: function (point) {
+        return this.offset(point.x, point.y);
+    },
+
+    /**
+    * Returns a string representation of this object.
+    * @method Phaser.Circle#toString
+    * @return {string} a string representation of the instance.
+    */
+    toString: function () {
+        return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
+    }
+
+};
+
+Phaser.Circle.prototype.constructor = Phaser.Circle;
+
+/**
+* The largest distance between any two points on the circle. The same as the radius * 2.
+* 
+* @name Phaser.Circle#diameter
+* @property {number} diameter - Gets or sets the diameter of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "diameter", {
+
+    get: function () {
+        return this._diameter;
+    },
+
+    set: function (value) {
+
+        if (value > 0)
+        {
+            this._diameter = value;
+            this._radius = value * 0.5;
+        }
+    }
+
+});
+
+/**
+* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
+* @name Phaser.Circle#radius
+* @property {number} radius - Gets or sets the radius of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "radius", {
+
+    get: function () {
+        return this._radius;
+    },
+
+    set: function (value) {
+
+        if (value > 0)
+        {
+            this._radius = value;
+            this._diameter = value * 2;
+        }
+
+    }
+
+});
+
+/**
+* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
+* @name Phaser.Circle#left
+* @propety {number} left - Gets or sets the value of the leftmost point of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "left", {
+
+    get: function () {
+        return this.x - this._radius;
+    },
+
+    set: function (value) {
+
+        if (value > this.x)
+        {
+            this._radius = 0;
+            this._diameter = 0;
+        }
+        else
+        {
+            this.radius = this.x - value;
+        }
+
+    }
+
+});
+
+/**
+* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
+* @name Phaser.Circle#right
+* @property {number} right - Gets or sets the value of the rightmost point of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "right", {
+
+    get: function () {
+        return this.x + this._radius;
+    },
+
+    set: function (value) {
+
+        if (value < this.x)
+        {
+            this._radius = 0;
+            this._diameter = 0;
+        }
+        else
+        {
+            this.radius = value - this.x;
+        }
+
+    }
+
+});
+
+/**
+* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
+* @name Phaser.Circle#top
+* @property {number} top - Gets or sets the top of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "top", {
+
+    get: function () {
+        return this.y - this._radius;
+    },
+
+    set: function (value) {
+
+        if (value > this.y)
+        {
+            this._radius = 0;
+            this._diameter = 0;
+        }
+        else
+        {
+            this.radius = this.y - value;
+        }
+
+    }
+
+});
+
+/**
+* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
+* @name Phaser.Circle#bottom
+* @property {number} bottom - Gets or sets the bottom of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "bottom", {
+
+    get: function () {
+        return this.y + this._radius;
+    },
+
+    set: function (value) {
+
+        if (value < this.y)
+        {
+            this._radius = 0;
+            this._diameter = 0;
+        }
+        else
+        {
+            this.radius = value - this.y;
+        }
+
+    }
+
+});
+
+/**
+* The area of this Circle.
+* @name Phaser.Circle#area
+* @property {number} area - The area of this circle.
+* @readonly
+*/
+Object.defineProperty(Phaser.Circle.prototype, "area", {
+
+    get: function () {
+
+        if (this._radius > 0)
+        {
+            return Math.PI * this._radius * this._radius;
+        }
+        else
+        {
+            return 0;
+        }
+
+    }
+
+});
+
+/**
+* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false.
+* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0.
+* @name Phaser.Circle#empty
+* @property {boolean} empty - Gets or sets the empty state of the circle.
+*/
+Object.defineProperty(Phaser.Circle.prototype, "empty", {
+
+    get: function () {
+        return (this._diameter === 0);
+    },
+
+    set: function (value) {
+
+        if (value === true)
+        {
+            this.setTo(0, 0, 0);
+        }
+
+    }
+
+});
+
+/**
+* Return true if the given x/y coordinates are within the Circle object.
+* @method Phaser.Circle.contains
+* @param {Phaser.Circle} a - The Circle to be checked.
+* @param {number} x - The X value of the coordinate to test.
+* @param {number} y - The Y value of the coordinate to test.
+* @return {boolean} True if the coordinates are within this circle, otherwise false.
+*/
+Phaser.Circle.contains = function (a, x, y) {
+
+    //  Check if x/y are within the bounds first
+    if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
+    {
+        var dx = (a.x - x) * (a.x - x);
+        var dy = (a.y - y) * (a.y - y);
+
+        return (dx + dy) <= (a.radius * a.radius);
+    }
+    else
+    {
+        return false;
+    }
+
+};
+
+/**
+* Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
+* @method Phaser.Circle.equals
+* @param {Phaser.Circle} a - The first Circle object.
+* @param {Phaser.Circle} b - The second Circle object.
+* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false.
+*/
+Phaser.Circle.equals = function (a, b) {
+    return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
+};
+
+/**
+* Determines whether the two Circle objects intersect.
+* This method checks the radius distances between the two Circle objects to see if they intersect.
+* @method Phaser.Circle.intersects
+* @param {Phaser.Circle} a - The first Circle object.
+* @param {Phaser.Circle} b - The second Circle object.
+* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
+*/
+Phaser.Circle.intersects = function (a, b) {
+    return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
+};
+
+/**
+* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
+* @method Phaser.Circle.circumferencePoint
+* @param {Phaser.Circle} a - The first Circle object.
+* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
+* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
+* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
+* @return {Phaser.Point} The Point object holding the result.
+*/
+Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
+
+    if (asDegrees === undefined) { asDegrees = false; }
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    if (asDegrees === true)
+    {
+        angle = Phaser.Math.degToRad(angle);
+    }
+
+    out.x = a.x + a.radius * Math.cos(angle);
+    out.y = a.y + a.radius * Math.sin(angle);
+
+    return out;
+
+};
+
+/**
+* Checks if the given Circle and Rectangle objects intersect.
+* @method Phaser.Circle.intersectsRectangle
+* @param {Phaser.Circle} c - The Circle object to test.
+* @param {Phaser.Rectangle} r - The Rectangle object to test.
+* @return {boolean} True if the two objects intersect, otherwise false.
+*/
+Phaser.Circle.intersectsRectangle = function (c, r) {
+
+    var cx = Math.abs(c.x - r.x - r.halfWidth);
+    var xDist = r.halfWidth + c.radius;
+
+    if (cx > xDist)
+    {
+        return false;
+    }
+
+    var cy = Math.abs(c.y - r.y - r.halfHeight);
+    var yDist = r.halfHeight + c.radius;
+
+    if (cy > yDist)
+    {
+        return false;
+    }
+
+    if (cx <= r.halfWidth || cy <= r.halfHeight)
+    {
+        return true;
+    }
+
+    var xCornerDist = cx - r.halfWidth;
+    var yCornerDist = cy - r.halfHeight;
+    var xCornerDistSq = xCornerDist * xCornerDist;
+    var yCornerDistSq = yCornerDist * yCornerDist;
+    var maxCornerDistSq = c.radius * c.radius;
+
+    return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
+
+};
+
+//   Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.Circle = Phaser.Circle;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @author       Chad Engler <chad@pantherdev.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a Ellipse object. A curve on a plane surrounding two focal points.
+* 
+* @class Phaser.Ellipse
+* @constructor
+* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
+* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
+* @param {number} [width=0] - The overall width of this ellipse.
+* @param {number} [height=0] - The overall height of this ellipse.
+*/
+Phaser.Ellipse = function (x, y, width, height) {
+
+    x = x || 0;
+    y = y || 0;
+    width = width || 0;
+    height = height || 0;
+
+    /**
+    * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
+    */
+    this.y = y;
+
+    /**
+    * @property {number} width - The overall width of this ellipse.
+    */
+    this.width = width;
+
+    /**
+    * @property {number} height - The overall height of this ellipse.
+    */
+    this.height = height;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.ELLIPSE;
+
+};
+
+Phaser.Ellipse.prototype = {
+
+    /**
+    * Sets the members of the Ellipse to the specified values.
+    * @method Phaser.Ellipse#setTo
+    * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
+    * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
+    * @param {number} width - The overall width of this ellipse.
+    * @param {number} height - The overall height of this ellipse.
+    * @return {Phaser.Ellipse} This Ellipse object.
+    */
+    setTo: function (x, y, width, height) {
+
+        this.x = x;
+        this.y = y;
+        this.width = width;
+        this.height = height;
+
+        return this;
+
+    },
+
+    /**
+    * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
+    * 
+    * @method Phaser.Ellipse#getBounds
+    * @return {Phaser.Rectangle} The bounds of the Ellipse.
+    */
+    getBounds: function () {
+
+        return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
+
+    },
+
+    /**
+    * Copies the x, y, width and height properties from any given object to this Ellipse.
+    * 
+    * @method Phaser.Ellipse#copyFrom
+    * @param {any} source - The object to copy from.
+    * @return {Phaser.Ellipse} This Ellipse object.
+    */
+    copyFrom: function (source) {
+
+        return this.setTo(source.x, source.y, source.width, source.height);
+
+    },
+
+    /**
+    * Copies the x, y, width and height properties from this Ellipse to any given object.
+    * @method Phaser.Ellipse#copyTo
+    * @param {any} dest - The object to copy to.
+    * @return {object} This dest object.
+    */
+    copyTo: function(dest) {
+
+        dest.x = this.x;
+        dest.y = this.y;
+        dest.width = this.width;
+        dest.height = this.height;
+
+        return dest;
+
+    },
+
+    /**
+    * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
+    * @method Phaser.Ellipse#clone
+    * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned.
+    * @return {Phaser.Ellipse} The cloned Ellipse object.
+    */
+    clone: function(output) {
+
+        if (output === undefined || output === null)
+        {
+            output = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
+        }
+        else
+        {
+            output.setTo(this.x, this.y, this.width, this.height);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Return true if the given x/y coordinates are within this Ellipse object.
+    * 
+    * @method Phaser.Ellipse#contains
+    * @param {number} x - The X value of the coordinate to test.
+    * @param {number} y - The Y value of the coordinate to test.
+    * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
+    */
+    contains: function (x, y) {
+
+        return Phaser.Ellipse.contains(this, x, y);
+
+    },
+
+    /**
+    * Returns a uniformly distributed random point from anywhere within this Ellipse.
+    * 
+    * @method Phaser.Ellipse#random
+    * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
+    *     If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
+    * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
+    */
+    random: function (out) {
+
+        if (out === undefined) { out = new Phaser.Point(); }
+
+        var p = Math.random() * Math.PI * 2;
+        var r = Math.random();
+
+        out.x = Math.sqrt(r) * Math.cos(p);
+        out.y = Math.sqrt(r) * Math.sin(p);
+
+        out.x = this.x + (out.x * this.width / 2.0);
+        out.y = this.y + (out.y * this.height / 2.0);
+
+        return out;
+
+    },
+
+    /**
+    * Returns a string representation of this object.
+    * @method Phaser.Ellipse#toString
+    * @return {string} A string representation of the instance.
+    */
+    toString: function () {
+        return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
+    }
+
+};
+
+Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
+
+/**
+* The left coordinate of the Ellipse. The same as the X coordinate.
+* @name Phaser.Ellipse#left
+* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
+*/
+Object.defineProperty(Phaser.Ellipse.prototype, "left", {
+
+    get: function () {
+        return this.x;
+    },
+
+    set: function (value) {
+
+        this.x = value;
+
+    }
+
+});
+
+/**
+* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width.
+* @name Phaser.Ellipse#right
+* @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
+*/
+Object.defineProperty(Phaser.Ellipse.prototype, "right", {
+
+    get: function () {
+        return this.x + this.width;
+    },
+
+    set: function (value) {
+
+        if (value < this.x)
+        {
+            this.width = 0;
+        }
+        else
+        {
+            this.width = value - this.x;
+        }
+    }
+
+});
+
+/**
+* The top of the Ellipse. The same as its y property.
+* @name Phaser.Ellipse#top
+* @property {number} top - Gets or sets the top of the ellipse.
+*/
+Object.defineProperty(Phaser.Ellipse.prototype, "top", {
+
+    get: function () {
+        return this.y;
+    },
+
+    set: function (value) {
+        this.y = value;
+    }
+
+});
+
+/**
+* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height.
+* @name Phaser.Ellipse#bottom
+* @property {number} bottom - Gets or sets the bottom of the ellipse.
+*/
+Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
+
+    get: function () {
+        return this.y + this.height;
+    },
+
+    set: function (value) {
+
+        if (value < this.y)
+        {
+            this.height = 0;
+        }
+        else
+        {
+            this.height = value - this.y;
+        }
+    }
+
+});
+
+/**
+* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false.
+* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0.
+* @name Phaser.Ellipse#empty
+* @property {boolean} empty - Gets or sets the empty state of the ellipse.
+*/
+Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
+
+    get: function () {
+        return (this.width === 0 || this.height === 0);
+    },
+
+    set: function (value) {
+
+        if (value === true)
+        {
+            this.setTo(0, 0, 0, 0);
+        }
+
+    }
+
+});
+
+/**
+* Return true if the given x/y coordinates are within the Ellipse object.
+* 
+* @method Phaser.Ellipse.contains
+* @param {Phaser.Ellipse} a - The Ellipse to be checked.
+* @param {number} x - The X value of the coordinate to test.
+* @param {number} y - The Y value of the coordinate to test.
+* @return {boolean} True if the coordinates are within this ellipse, otherwise false.
+*/
+Phaser.Ellipse.contains = function (a, x, y) {
+ 
+    if (a.width <= 0 || a.height <= 0) {
+        return false;
+    }
+ 
+    //  Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
+    var normx = ((x - a.x) / a.width) - 0.5;
+    var normy = ((y - a.y) / a.height) - 0.5;
+ 
+    normx *= normx;
+    normy *= normy;
+ 
+    return (normx + normy < 0.25);
+ 
+};
+
+//   Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.Ellipse = Phaser.Ellipse;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a new Line object with a start and an end point.
+* 
+* @class Phaser.Line
+* @constructor
+* @param {number} [x1=0] - The x coordinate of the start of the line.
+* @param {number} [y1=0] - The y coordinate of the start of the line.
+* @param {number} [x2=0] - The x coordinate of the end of the line.
+* @param {number} [y2=0] - The y coordinate of the end of the line.
+*/
+Phaser.Line = function (x1, y1, x2, y2) {
+
+    x1 = x1 || 0;
+    y1 = y1 || 0;
+    x2 = x2 || 0;
+    y2 = y2 || 0;
+
+    /**
+    * @property {Phaser.Point} start - The start point of the line.
+    */
+    this.start = new Phaser.Point(x1, y1);
+
+    /**
+    * @property {Phaser.Point} end - The end point of the line.
+    */
+    this.end = new Phaser.Point(x2, y2);
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.LINE;
+
+};
+
+Phaser.Line.prototype = {
+
+    /**
+    * Sets the components of the Line to the specified values.
+    * 
+    * @method Phaser.Line#setTo
+    * @param {number} [x1=0] - The x coordinate of the start of the line.
+    * @param {number} [y1=0] - The y coordinate of the start of the line.
+    * @param {number} [x2=0] - The x coordinate of the end of the line.
+    * @param {number} [y2=0] - The y coordinate of the end of the line.
+    * @return {Phaser.Line} This line object
+    */
+    setTo: function (x1, y1, x2, y2) {
+
+        this.start.setTo(x1, y1);
+        this.end.setTo(x2, y2);
+
+        return this;
+
+    },
+
+    /**
+    * Sets the line to match the x/y coordinates of the two given sprites.
+    * Can optionally be calculated from their center coordinates.
+    * 
+    * @method Phaser.Line#fromSprite
+    * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
+    * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
+    * @param {boolean} [useCenter=false] - If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class.
+    * @return {Phaser.Line} This line object
+    */
+    fromSprite: function (startSprite, endSprite, useCenter) {
+
+        if (useCenter === undefined) { useCenter = false; }
+
+        if (useCenter)
+        {
+            return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
+        }
+
+        return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
+
+    },
+
+    /**
+    * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`.
+    * 
+    * @method Phaser.Line#fromAngle
+    * @param {number} x - The x coordinate of the start of the line.
+    * @param {number} y - The y coordinate of the start of the line.
+    * @param {number} angle - The angle of the line in radians.
+    * @param {number} length - The length of the line in pixels.
+    * @return {Phaser.Line} This line object
+    */
+    fromAngle: function (x, y, angle, length) {
+
+        this.start.setTo(x, y);
+        this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length));
+
+        return this;
+
+    },
+
+    /**
+    * Rotates the line by the amount specified in `angle`.
+    * 
+    * Rotation takes place from the center of the line.
+    * 
+    * If you wish to rotate from either end see Line.start.rotate or Line.end.rotate.
+    * 
+    * @method Phaser.Line#rotate
+    * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by.
+    * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
+    * @return {Phaser.Line} This line object
+    */
+    rotate: function (angle, asDegrees) {
+
+        var x = this.start.x;
+        var y = this.start.y;
+
+        this.start.rotate(this.end.x, this.end.y, angle, asDegrees, this.length);
+        this.end.rotate(x, y, angle, asDegrees, this.length);
+
+        return this;
+
+    },
+
+    /**
+    * Checks for intersection between this line and another Line.
+    * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
+    * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
+    *
+    * @method Phaser.Line#intersects
+    * @param {Phaser.Line} line - The line to check against this one.
+    * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
+    * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
+    * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
+    */
+    intersects: function (line, asSegment, result) {
+
+        return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
+
+    },
+
+    /**
+    * Returns the reflected angle between two lines.
+    * This is the outgoing angle based on the angle of this line and the normalAngle of the given line.
+    *
+    * @method Phaser.Line#reflect
+    * @param {Phaser.Line} line - The line to reflect off this line.
+    * @return {number} The reflected angle in radians.
+    */
+    reflect: function (line) {
+
+        return Phaser.Line.reflect(this, line);
+
+    },
+
+    /**
+    * Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
+    * 
+    * @method Phaser.Line#pointOnLine
+    * @param {number} x - The line to check against this one.
+    * @param {number} y - The line to check against this one.
+    * @return {boolean} True if the point is on the line, false if not.
+    */
+    pointOnLine: function (x, y) {
+
+        return ((x - this.start.x) * (this.end.y - this.start.y) === (this.end.x - this.start.x) * (y - this.start.y));
+
+    },
+
+    /**
+    * Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
+    * 
+    * @method Phaser.Line#pointOnSegment
+    * @param {number} x - The line to check against this one.
+    * @param {number} y - The line to check against this one.
+    * @return {boolean} True if the point is on the line and segment, false if not.
+    */
+    pointOnSegment: function (x, y) {
+
+        var xMin = Math.min(this.start.x, this.end.x);
+        var xMax = Math.max(this.start.x, this.end.x);
+        var yMin = Math.min(this.start.y, this.end.y);
+        var yMax = Math.max(this.start.y, this.end.y);
+
+        return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
+
+    },
+
+    /**
+    * Picks a random point from anywhere on the Line segment and returns it.
+    * 
+    * @method Phaser.Line#random
+    * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
+    *     If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object.
+    * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
+    */
+    random: function (out) {
+
+        if (out === undefined) { out = new Phaser.Point(); }
+
+        var t = Math.random();
+
+        out.x = this.start.x + t * (this.end.x - this.start.x);
+        out.y = this.start.y + t * (this.end.y - this.start.y);
+
+        return out;
+
+    },
+
+    /**
+    * Using Bresenham's line algorithm this will return an array of all coordinates on this line.
+    * The start and end points are rounded before this runs as the algorithm works on integers.
+    *
+    * @method Phaser.Line#coordinatesOnLine
+    * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
+    * @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
+    * @return {array} An array of coordinates.
+    */
+    coordinatesOnLine: function (stepRate, results) {
+
+        if (stepRate === undefined) { stepRate = 1; }
+        if (results === undefined) { results = []; }
+
+        var x1 = Math.round(this.start.x);
+        var y1 = Math.round(this.start.y);
+        var x2 = Math.round(this.end.x);
+        var y2 = Math.round(this.end.y);
+
+        var dx = Math.abs(x2 - x1);
+        var dy = Math.abs(y2 - y1);
+        var sx = (x1 < x2) ? 1 : -1;
+        var sy = (y1 < y2) ? 1 : -1;
+        var err = dx - dy;
+
+        results.push([x1, y1]);
+
+        var i = 1;
+
+        while (!((x1 == x2) && (y1 == y2)))
+        {
+            var e2 = err << 1;
+
+            if (e2 > -dy)
+            {
+                err -= dy;
+                x1 += sx;
+            }
+
+            if (e2 < dx)
+            {
+                err += dx;
+                y1 += sy;
+            }
+
+            if (i % stepRate === 0)
+            {
+                results.push([x1, y1]);
+            }
+
+            i++;
+
+        }
+
+        return results;
+
+    },
+
+    /**
+     * Returns a new Line object with the same values for the start and end properties as this Line object.
+     * @method Phaser.Line#clone
+     * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned.
+     * @return {Phaser.Line} The cloned Line object.
+     */
+    clone: function (output) {
+
+        if (output === undefined || output === null)
+        {
+            output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y);
+        }
+        else
+        {
+            output.setTo(this.start.x, this.start.y, this.end.x, this.end.y);
+        }
+
+        return output;
+
+    }
+
+};
+
+/**
+* @name Phaser.Line#length
+* @property {number} length - Gets the length of the line segment.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "length", {
+
+    get: function () {
+        return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y));
+    }
+
+});
+
+/**
+* @name Phaser.Line#angle
+* @property {number} angle - Gets the angle of the line in radians.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "angle", {
+
+    get: function () {
+        return Math.atan2(this.end.y - this.start.y, this.end.x - this.start.x);
+    }
+
+});
+
+/**
+* @name Phaser.Line#slope
+* @property {number} slope - Gets the slope of the line (y/x).
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "slope", {
+
+    get: function () {
+        return (this.end.y - this.start.y) / (this.end.x - this.start.x);
+    }
+
+});
+
+/**
+* @name Phaser.Line#perpSlope
+* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
+
+    get: function () {
+        return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
+    }
+
+});
+
+/**
+* @name Phaser.Line#x
+* @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "x", {
+
+    get: function () {
+        return Math.min(this.start.x, this.end.x);
+    }
+
+});
+
+/**
+* @name Phaser.Line#y
+* @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "y", {
+
+    get: function () {
+        return Math.min(this.start.y, this.end.y);
+    }
+
+});
+
+/**
+* @name Phaser.Line#left
+* @property {number} left - Gets the left-most point of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "left", {
+
+    get: function () {
+        return Math.min(this.start.x, this.end.x);
+    }
+
+});
+
+/**
+* @name Phaser.Line#right
+* @property {number} right - Gets the right-most point of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "right", {
+
+    get: function () {
+        return Math.max(this.start.x, this.end.x);
+    }
+
+});
+
+/**
+* @name Phaser.Line#top
+* @property {number} top - Gets the top-most point of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "top", {
+
+    get: function () {
+        return Math.min(this.start.y, this.end.y);
+    }
+
+});
+
+/**
+* @name Phaser.Line#bottom
+* @property {number} bottom - Gets the bottom-most point of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "bottom", {
+
+    get: function () {
+        return Math.max(this.start.y, this.end.y);
+    }
+
+});
+
+/**
+* @name Phaser.Line#width
+* @property {number} width - Gets the width of this bounds of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "width", {
+
+    get: function () {
+        return Math.abs(this.start.x - this.end.x);
+    }
+
+});
+
+/**
+* @name Phaser.Line#height
+* @property {number} height - Gets the height of this bounds of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "height", {
+
+    get: function () {
+        return Math.abs(this.start.y - this.end.y);
+    }
+
+});
+
+/**
+* @name Phaser.Line#normalX
+* @property {number} normalX - Gets the x component of the left-hand normal of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "normalX", {
+
+    get: function () {
+        return Math.cos(this.angle - 1.5707963267948966);
+    }
+
+});
+
+/**
+* @name Phaser.Line#normalY
+* @property {number} normalY - Gets the y component of the left-hand normal of this line.
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "normalY", {
+
+    get: function () {
+        return Math.sin(this.angle - 1.5707963267948966);
+    }
+
+});
+
+/**
+* @name Phaser.Line#normalAngle
+* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.)
+* @readonly
+*/
+Object.defineProperty(Phaser.Line.prototype, "normalAngle", {
+
+    get: function () {
+        return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI);
+    }
+
+});
+
+/**
+* Checks for intersection between two lines as defined by the given start and end points.
+* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
+* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
+* Adapted from code by Keith Hair
+*
+* @method Phaser.Line.intersectsPoints
+* @param {Phaser.Point} a - The start of the first Line to be checked.
+* @param {Phaser.Point} b - The end of the first line to be checked.
+* @param {Phaser.Point} e - The start of the second Line to be checked.
+* @param {Phaser.Point} f - The end of the second line to be checked.
+* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
+* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created.
+* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
+*/
+Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
+
+    if (asSegment === undefined) { asSegment = true; }
+    if (result === undefined) { result = new Phaser.Point(); }
+
+    var a1 = b.y - a.y;
+    var a2 = f.y - e.y;
+    var b1 = a.x - b.x;
+    var b2 = e.x - f.x;
+    var c1 = (b.x * a.y) - (a.x * b.y);
+    var c2 = (f.x * e.y) - (e.x * f.y);
+    var denom = (a1 * b2) - (a2 * b1);
+
+    if (denom === 0)
+    {
+        return null;
+    }
+
+    result.x = ((b1 * c2) - (b2 * c1)) / denom;
+    result.y = ((a2 * c1) - (a1 * c2)) / denom;
+
+    if (asSegment)
+    {
+        var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y));
+        var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc;
+        var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc;
+
+        if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1)
+        {
+            return result;
+        }
+        else
+        {
+            return null;
+        }
+    }
+
+    return result;
+
+};
+
+/**
+* Checks for intersection between two lines.
+* If asSegment is true it will check for segment intersection.
+* If asSegment is false it will check for line intersection.
+* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
+* Adapted from code by Keith Hair
+*
+* @method Phaser.Line.intersects
+* @param {Phaser.Line} a - The first Line to be checked.
+* @param {Phaser.Line} b - The second Line to be checked.
+* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
+* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
+* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
+*/
+Phaser.Line.intersects = function (a, b, asSegment, result) {
+
+    return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
+
+};
+
+/**
+* Returns the reflected angle between two lines.
+* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2.
+*
+* @method Phaser.Line.reflect
+* @param {Phaser.Line} a - The base line.
+* @param {Phaser.Line} b - The line to be reflected from the base line.
+* @return {number} The reflected angle in radians.
+*/
+Phaser.Line.reflect = function (a, b) {
+
+    return 2 * b.normalAngle - 3.141592653589793 - a.angle;
+
+};
+
+/**
+* @author       Mat Groves http://matgroves.com/ @Doormat23
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer.
+* 
+* It is represented like so:
+* 
+* | a | b | tx |
+* | c | d | ty |
+* | 0 | 0 | 1 |
+*
+* @class Phaser.Matrix
+* @constructor
+* @param {number} [a=1]
+* @param {number} [b=0]
+* @param {number} [c=0]
+* @param {number} [d=1]
+* @param {number} [tx=0]
+* @param {number} [ty=0]
+*/
+Phaser.Matrix = function (a, b, c, d, tx, ty) {
+
+    a = a || 1;
+    b = b || 0;
+    c = c || 0;
+    d = d || 1;
+    tx = tx || 0;
+    ty = ty || 0;
+
+    /**
+    * @property {number} a
+    * @default 1
+    */
+    this.a = a;
+
+    /**
+    * @property {number} b
+    * @default 0
+    */
+    this.b = b;
+
+    /**
+    * @property {number} c
+    * @default 0
+    */
+    this.c = c;
+
+    /**
+    * @property {number} d
+    * @default 1
+    */
+    this.d = d;
+
+    /**
+    * @property {number} tx
+    * @default 0
+    */
+    this.tx = tx;
+
+    /**
+    * @property {number} ty
+    * @default 0
+    */
+    this.ty = ty;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.MATRIX;
+
+};
+
+Phaser.Matrix.prototype = {
+
+    /**
+    * Sets the values of this Matrix to the values in the given array.
+    * 
+    * The Array elements should be set as follows:
+    *
+    * a = array[0]
+    * b = array[1]
+    * c = array[3]
+    * d = array[4]
+    * tx = array[2]
+    * ty = array[5]
+    *
+    * @method Phaser.Matrix#fromArray
+    * @param {Array} array - The array to copy from.
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    fromArray: function (array) {
+
+        return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]);
+
+    },
+
+    /**
+    * Sets the values of this Matrix to the given values.
+    *
+    * @method Phaser.Matrix#setTo
+    * @param {number} a
+    * @param {number} b
+    * @param {number} c
+    * @param {number} d
+    * @param {number} tx
+    * @param {number} ty
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    setTo: function (a, b, c, d, tx, ty) {
+
+        this.a = a;
+        this.b = b;
+        this.c = c;
+        this.d = d;
+        this.tx = tx;
+        this.ty = ty;
+
+        return this;
+
+    },
+
+    /**
+     * Creates a new Matrix object based on the values of this Matrix.
+     * If you provide the output parameter the values of this Matrix will be copied over to it.
+     * If the output parameter is blank a new Matrix object will be created.
+     *
+     * @method Phaser.Matrix#clone
+     * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created.
+     * @return {Phaser.Matrix} A clone of this Matrix.
+     */
+    clone: function (output) {
+
+        if (output === undefined || output === null)
+        {
+            output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty);
+        }
+        else
+        {
+            output.a = this.a;
+            output.b = this.b;
+            output.c = this.c;
+            output.d = this.d;
+            output.tx = this.tx;
+            output.ty = this.ty;
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Copies the properties from this Matrix to the given Matrix.
+    *
+    * @method Phaser.Matrix#copyTo
+    * @param {Phaser.Matrix} matrix - The Matrix to copy from.
+    * @return {Phaser.Matrix} The destination Matrix object.
+    */
+    copyTo: function (matrix) {
+
+        matrix.copyFrom(this);
+
+        return matrix;
+
+    },
+
+    /**
+    * Copies the properties from the given Matrix into this Matrix.
+    *
+    * @method Phaser.Matrix#copyFrom
+    * @param {Phaser.Matrix} matrix - The Matrix to copy from.
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    copyFrom: function (matrix) {
+
+        this.a = matrix.a;
+        this.b = matrix.b;
+        this.c = matrix.c;
+        this.d = matrix.d;
+        this.tx = matrix.tx;
+        this.ty = matrix.ty;
+
+        return this;
+
+    },
+
+    /**
+    * Creates a Float32 Array with values populated from this Matrix object.
+    *
+    * @method Phaser.Matrix#toArray
+    * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not.
+    * @param {PIXI.Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created.
+    * @return {PIXI.Float32Array} The newly created array which contains the matrix.
+    */
+    toArray: function (transpose, array) {
+
+        if (array === undefined) { array = new PIXI.Float32Array(9); }
+
+        if (transpose)
+        {
+            array[0] = this.a;
+            array[1] = this.b;
+            array[2] = 0;
+            array[3] = this.c;
+            array[4] = this.d;
+            array[5] = 0;
+            array[6] = this.tx;
+            array[7] = this.ty;
+            array[8] = 1;
+        }
+        else
+        {
+            array[0] = this.a;
+            array[1] = this.c;
+            array[2] = this.tx;
+            array[3] = this.b;
+            array[4] = this.d;
+            array[5] = this.ty;
+            array[6] = 0;
+            array[7] = 0;
+            array[8] = 1;
+        }
+
+        return array;
+
+    },
+
+    /**
+    * Get a new position with the current transformation applied.
+    * 
+    * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering)
+    *
+    * @method Phaser.Matrix#apply
+    * @param {Phaser.Point} pos - The origin Point.
+    * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point.
+    * @return {Phaser.Point} The new point, transformed through this matrix.
+    */
+    apply: function (pos, newPos) {
+
+        if (newPos === undefined) { newPos = new Phaser.Point(); }
+
+        newPos.x = this.a * pos.x + this.c * pos.y + this.tx;
+        newPos.y = this.b * pos.x + this.d * pos.y + this.ty;
+
+        return newPos;
+
+    },
+
+    /**
+    * Get a new position with the inverse of the current transformation applied.
+    * 
+    * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input)
+    *
+    * @method Phaser.Matrix#applyInverse
+    * @param {Phaser.Point} pos - The origin Point.
+    * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point.
+    * @return {Phaser.Point} The new point, inverse transformed through this matrix.
+    */
+    applyInverse: function (pos, newPos) {
+
+        if (newPos === undefined) { newPos = new Phaser.Point(); }
+
+        var id = 1 / (this.a * this.d + this.c * -this.b);
+        var x = pos.x;
+        var y = pos.y;
+
+        newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id;
+        newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id;
+
+        return newPos;
+
+    },
+
+    /**
+    * Translates the matrix on the x and y.
+    * This is the same as Matrix.tx += x.
+    * 
+    * @method Phaser.Matrix#translate
+    * @param {number} x - The x value to translate on.
+    * @param {number} y - The y value to translate on.
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    translate: function (x, y) {
+
+        this.tx += x;
+        this.ty += y;
+        
+        return this;
+
+    },
+
+    /**
+    * Applies a scale transformation to this matrix.
+    * 
+    * @method Phaser.Matrix#scale
+    * @param {number} x - The amount to scale horizontally.
+    * @param {number} y - The amount to scale vertically.
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    scale: function (x, y) {
+
+        this.a *= x;
+        this.d *= y;
+        this.c *= x;
+        this.b *= y;
+        this.tx *= x;
+        this.ty *= y;
+
+        return this;
+
+    },
+
+    /**
+    * Applies a rotation transformation to this matrix.
+    * 
+    * @method Phaser.Matrix#rotate
+    * @param {number} angle - The angle to rotate by, given in radians.
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    rotate: function (angle) {
+
+        var cos = Math.cos(angle);
+        var sin = Math.sin(angle);
+
+        var a1 = this.a;
+        var c1 = this.c;
+        var tx1 = this.tx;
+
+        this.a = a1 * cos-this.b * sin;
+        this.b = a1 * sin+this.b * cos;
+        this.c = c1 * cos-this.d * sin;
+        this.d = c1 * sin+this.d * cos;
+        this.tx = tx1 * cos - this.ty * sin;
+        this.ty = tx1 * sin + this.ty * cos;
+     
+        return this;
+
+    },
+
+    /**
+    * Appends the given Matrix to this Matrix.
+    * 
+    * @method Phaser.Matrix#append
+    * @param {Phaser.Matrix} matrix - The matrix to append to this one.
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    append: function (matrix) {
+
+        var a1 = this.a;
+        var b1 = this.b;
+        var c1 = this.c;
+        var d1 = this.d;
+
+        this.a  = matrix.a * a1 + matrix.b * c1;
+        this.b  = matrix.a * b1 + matrix.b * d1;
+        this.c  = matrix.c * a1 + matrix.d * c1;
+        this.d  = matrix.c * b1 + matrix.d * d1;
+
+        this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx;
+        this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty;
+        
+        return this;
+
+    },
+
+    /**
+    * Resets this Matrix to an identity (default) matrix.
+    * 
+    * @method Phaser.Matrix#identity
+    * @return {Phaser.Matrix} This Matrix object.
+    */
+    identity: function () {
+
+        return this.setTo(1, 0, 0, 1, 0, 0);
+
+    }
+
+};
+
+Phaser.identityMatrix = new Phaser.Matrix();
+
+//  Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.Matrix = Phaser.Matrix;
+PIXI.identityMatrix = Phaser.identityMatrix;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
+* The following code creates a point at (0,0):
+* `var myPoint = new Phaser.Point();`
+* You can also use them as 2D Vectors and you'll find different vector related methods in this class.
+* 
+* @class Phaser.Point
+* @constructor
+* @param {number} [x=0] - The horizontal position of this Point.
+* @param {number} [y=0] - The vertical position of this Point.
+*/
+Phaser.Point = function (x, y) {
+
+    x = x || 0;
+    y = y || 0;
+
+    /**
+    * @property {number} x - The x value of the point.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - The y value of the point.
+    */
+    this.y = y;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.POINT;
+
+};
+
+Phaser.Point.prototype = {
+
+    /**
+    * Copies the x and y properties from any given object to this Point.
+    *
+    * @method Phaser.Point#copyFrom
+    * @param {any} source - The object to copy from.
+    * @return {Phaser.Point} This Point object.
+    */
+    copyFrom: function (source) {
+
+        return this.setTo(source.x, source.y);
+
+    },
+
+    /**
+    * Inverts the x and y values of this Point
+    *
+    * @method Phaser.Point#invert
+    * @return {Phaser.Point} This Point object.
+    */
+    invert: function () {
+
+        return this.setTo(this.y, this.x);
+
+    },
+
+    /**
+    * Sets the `x` and `y` values of this Point object to the given values.
+    * If you omit the `y` value then the `x` value will be applied to both, for example:
+    * `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
+    *
+    * @method Phaser.Point#setTo
+    * @param {number} x - The horizontal value of this point.
+    * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
+    * @return {Phaser.Point} This Point object. Useful for chaining method calls.
+    */
+    setTo: function (x, y) {
+
+        this.x = x || 0;
+        this.y = y || ( (y !== 0) ? this.x : 0 );
+
+        return this;
+
+    },
+
+    /**
+    * Sets the `x` and `y` values of this Point object to the given values.
+    * If you omit the `y` value then the `x` value will be applied to both, for example:
+    * `Point.set(2)` is the same as `Point.set(2, 2)`
+    *
+    * @method Phaser.Point#set
+    * @param {number} x - The horizontal value of this point.
+    * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
+    * @return {Phaser.Point} This Point object. Useful for chaining method calls.
+    */
+    set: function (x, y) {
+
+        this.x = x || 0;
+        this.y = y || ( (y !== 0) ? this.x : 0 );
+
+        return this;
+
+    },
+
+    /**
+    * Adds the given x and y values to this Point.
+    *
+    * @method Phaser.Point#add
+    * @param {number} x - The value to add to Point.x.
+    * @param {number} y - The value to add to Point.y.
+    * @return {Phaser.Point} This Point object. Useful for chaining method calls.
+    */
+    add: function (x, y) {
+
+        this.x += x;
+        this.y += y;
+        return this;
+
+    },
+
+    /**
+    * Subtracts the given x and y values from this Point.
+    *
+    * @method Phaser.Point#subtract
+    * @param {number} x - The value to subtract from Point.x.
+    * @param {number} y - The value to subtract from Point.y.
+    * @return {Phaser.Point} This Point object. Useful for chaining method calls.
+    */
+    subtract: function (x, y) {
+
+        this.x -= x;
+        this.y -= y;
+        return this;
+
+    },
+
+    /**
+    * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`.
+    *
+    * @method Phaser.Point#multiply
+    * @param {number} x - The value to multiply Point.x by.
+    * @param {number} y - The value to multiply Point.x by.
+    * @return {Phaser.Point} This Point object. Useful for chaining method calls.
+    */
+    multiply: function (x, y) {
+
+        this.x *= x;
+        this.y *= y;
+        return this;
+
+    },
+
+    /**
+    * Divides Point.x and Point.y by the given x and y values.
+    *
+    * @method Phaser.Point#divide
+    * @param {number} x - The value to divide Point.x by.
+    * @param {number} y - The value to divide Point.x by.
+    * @return {Phaser.Point} This Point object. Useful for chaining method calls.
+    */
+    divide: function (x, y) {
+
+        this.x /= x;
+        this.y /= y;
+        return this;
+
+    },
+
+    /**
+    * Clamps the x value of this Point to be between the given min and max.
+    *
+    * @method Phaser.Point#clampX
+    * @param {number} min - The minimum value to clamp this Point to.
+    * @param {number} max - The maximum value to clamp this Point to.
+    * @return {Phaser.Point} This Point object.
+    */
+    clampX: function (min, max) {
+
+        this.x = Phaser.Math.clamp(this.x, min, max);
+        return this;
+
+    },
+
+    /**
+    * Clamps the y value of this Point to be between the given min and max
+    *
+    * @method Phaser.Point#clampY
+    * @param {number} min - The minimum value to clamp this Point to.
+    * @param {number} max - The maximum value to clamp this Point to.
+    * @return {Phaser.Point} This Point object.
+    */
+    clampY: function (min, max) {
+
+        this.y = Phaser.Math.clamp(this.y, min, max);
+        return this;
+
+    },
+
+    /**
+    * Clamps this Point object values to be between the given min and max.
+    *
+    * @method Phaser.Point#clamp
+    * @param {number} min - The minimum value to clamp this Point to.
+    * @param {number} max - The maximum value to clamp this Point to.
+    * @return {Phaser.Point} This Point object.
+    */
+    clamp: function (min, max) {
+
+        this.x = Phaser.Math.clamp(this.x, min, max);
+        this.y = Phaser.Math.clamp(this.y, min, max);
+        return this;
+
+    },
+
+    /**
+    * Creates a copy of the given Point.
+    *
+    * @method Phaser.Point#clone
+    * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
+    * @return {Phaser.Point} The new Point object.
+    */
+    clone: function (output) {
+
+        if (output === undefined || output === null)
+        {
+            output = new Phaser.Point(this.x, this.y);
+        }
+        else
+        {
+            output.setTo(this.x, this.y);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Copies the x and y properties from this Point to any given object.
+    *
+    * @method Phaser.Point#copyTo
+    * @param {any} dest - The object to copy to.
+    * @return {object} The dest object.
+    */
+    copyTo: function (dest) {
+
+        dest.x = this.x;
+        dest.y = this.y;
+
+        return dest;
+
+    },
+
+    /**
+    * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
+    *
+    * @method Phaser.Point#distance
+    * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
+    * @param {boolean} [round] - Round the distance to the nearest integer (default false).
+    * @return {number} The distance between this Point object and the destination Point object.
+    */
+    distance: function (dest, round) {
+
+        return Phaser.Point.distance(this, dest, round);
+
+    },
+
+    /**
+    * Determines whether the given objects x/y values are equal to this Point object.
+    *
+    * @method Phaser.Point#equals
+    * @param {Phaser.Point|any} a - The object to compare with this Point.
+    * @return {boolean} A value of true if the x and y points are equal, otherwise false.
+    */
+    equals: function (a) {
+
+        return (a.x === this.x && a.y === this.y);
+
+    },
+
+    /**
+    * Returns the angle between this Point object and another object with public x and y properties.
+    *
+    * @method Phaser.Point#angle
+    * @param {Phaser.Point|any} a - The object to get the angle from this Point to.
+    * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
+    * @return {number} The angle between the two objects.
+    */
+    angle: function (a, asDegrees) {
+
+        if (asDegrees === undefined) { asDegrees = false; }
+
+        if (asDegrees)
+        {
+            return Phaser.Math.radToDeg(Math.atan2(a.y - this.y, a.x - this.x));
+        }
+        else
+        {
+            return Math.atan2(a.y - this.y, a.x - this.x);
+        }
+
+    },
+
+    /**
+    * Rotates this Point around the x/y coordinates given to the desired angle.
+    *
+    * @method Phaser.Point#rotate
+    * @param {number} x - The x coordinate of the anchor point.
+    * @param {number} y - The y coordinate of the anchor point.
+    * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
+    * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
+    * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
+    * @return {Phaser.Point} The modified point object.
+    */
+    rotate: function (x, y, angle, asDegrees, distance) {
+
+        return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
+
+    },
+
+    /**
+    * Calculates the length of the Point object.
+    *
+    * @method Phaser.Point#getMagnitude
+    * @return {number} The length of the Point.
+    */
+    getMagnitude: function () {
+
+        return Math.sqrt((this.x * this.x) + (this.y * this.y));
+
+    },
+
+    /**
+    * Calculates the length squared of the Point object.
+    *
+    * @method Phaser.Point#getMagnitudeSq
+    * @return {number} The length ^ 2 of the Point.
+    */
+    getMagnitudeSq: function () {
+
+        return (this.x * this.x) + (this.y * this.y);
+
+    },
+
+    /**
+    * Alters the length of the Point without changing the direction.
+    *
+    * @method Phaser.Point#setMagnitude
+    * @param {number} magnitude - The desired magnitude of the resulting Point.
+    * @return {Phaser.Point} This Point object.
+    */
+    setMagnitude: function (magnitude) {
+
+        return this.normalize().multiply(magnitude, magnitude);
+
+    },
+
+    /**
+    * Alters the Point object so that its length is 1, but it retains the same direction.
+    *
+    * @method Phaser.Point#normalize
+    * @return {Phaser.Point} This Point object.
+    */
+    normalize: function () {
+
+        if (!this.isZero())
+        {
+            var m = this.getMagnitude();
+            this.x /= m;
+            this.y /= m;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Determine if this point is at 0,0.
+    *
+    * @method Phaser.Point#isZero
+    * @return {boolean} True if this Point is 0,0, otherwise false.
+    */
+    isZero: function () {
+
+        return (this.x === 0 && this.y === 0);
+
+    },
+
+    /**
+    * The dot product of this and another Point object.
+    * 
+    * @method Phaser.Point#dot
+    * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point.
+    * @return {number} The result.
+    */
+    dot: function (a) {
+
+        return ((this.x * a.x) + (this.y * a.y));
+
+    },
+
+    /**
+    * The cross product of this and another Point object.
+    * 
+    * @method Phaser.Point#cross
+    * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point.
+    * @return {number} The result.
+    */
+    cross: function (a) {
+
+        return ((this.x * a.y) - (this.y * a.x));
+
+    },
+
+    /**
+    * Make this Point perpendicular (90 degrees rotation)
+    * 
+    * @method Phaser.Point#perp
+    * @return {Phaser.Point} This Point object.
+    */
+    perp: function () {
+
+        return this.setTo(-this.y, this.x);
+
+    },
+
+    /**
+    * Make this Point perpendicular (-90 degrees rotation)
+    * 
+    * @method Phaser.Point#rperp
+    * @return {Phaser.Point} This Point object.
+    */
+    rperp: function () {
+
+        return this.setTo(this.y, -this.x);
+
+    },
+
+    /**
+    * Right-hand normalize (make unit length) this Point.
+    *
+    * @method Phaser.Point#normalRightHand
+    * @return {Phaser.Point} This Point object.
+    */
+    normalRightHand: function () {
+
+        return this.setTo(this.y * -1, this.x);
+
+    },
+
+    /**
+    * Math.floor() both the x and y properties of this Point.
+    *
+    * @method Phaser.Point#floor
+    * @return {Phaser.Point} This Point object.
+    */
+    floor: function () {
+
+        return this.setTo(Math.floor(this.x), Math.floor(this.y));
+
+    },
+
+    /**
+    * Math.ceil() both the x and y properties of this Point.
+    *
+    * @method Phaser.Point#ceil
+    * @return {Phaser.Point} This Point object.
+    */
+    ceil: function () {
+
+        return this.setTo(Math.ceil(this.x), Math.ceil(this.y));
+
+    },
+
+    /**
+    * Returns a string representation of this object.
+    *
+    * @method Phaser.Point#toString
+    * @return {string} A string representation of the instance.
+    */
+    toString: function () {
+
+        return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
+
+    }
+
+};
+
+Phaser.Point.prototype.constructor = Phaser.Point;
+
+/**
+* Adds the coordinates of two points together to create a new point.
+*
+* @method Phaser.Point.add
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.add = function (a, b, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    out.x = a.x + b.x;
+    out.y = a.y + b.y;
+
+    return out;
+
+};
+
+/**
+* Subtracts the coordinates of two points to create a new point.
+*
+* @method Phaser.Point.subtract
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.subtract = function (a, b, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    out.x = a.x - b.x;
+    out.y = a.y - b.y;
+
+    return out;
+
+};
+
+/**
+* Multiplies the coordinates of two points to create a new point.
+*
+* @method Phaser.Point.multiply
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.multiply = function (a, b, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    out.x = a.x * b.x;
+    out.y = a.y * b.y;
+
+    return out;
+
+};
+
+/**
+* Divides the coordinates of two points to create a new point.
+*
+* @method Phaser.Point.divide
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.divide = function (a, b, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    out.x = a.x / b.x;
+    out.y = a.y / b.y;
+
+    return out;
+
+};
+
+/**
+* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
+*
+* @method Phaser.Point.equals
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @return {boolean} A value of true if the Points are equal, otherwise false.
+*/
+Phaser.Point.equals = function (a, b) {
+
+    return (a.x === b.x && a.y === b.y);
+
+};
+
+/**
+* Returns the angle between two Point objects.
+*
+* @method Phaser.Point.angle
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @return {number} The angle between the two Points.
+*/
+Phaser.Point.angle = function (a, b) {
+
+    // return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y);
+    return Math.atan2(a.y - b.y, a.x - b.x);
+
+};
+
+/**
+* Creates a negative Point.
+*
+* @method Phaser.Point.negative
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.negative = function (a, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    return out.setTo(-a.x, -a.y);
+
+};
+
+/**
+* Adds two 2D Points together and multiplies the result by the given scalar.
+* 
+* @method Phaser.Point.multiplyAdd
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {number} s - The scaling value.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.multiplyAdd = function (a, b, s, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    return out.setTo(a.x + b.x * s, a.y + b.y * s);
+
+};
+
+/**
+* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point.
+* 
+* @method Phaser.Point.interpolate
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.interpolate = function (a, b, f, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
+
+};
+
+/**
+* Return a perpendicular vector (90 degrees rotation)
+*
+* @method Phaser.Point.perp
+* @param {Phaser.Point} a - The Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.perp = function (a, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    return out.setTo(-a.y, a.x);
+
+};
+
+/**
+* Return a perpendicular vector (-90 degrees rotation)
+*
+* @method Phaser.Point.rperp
+* @param {Phaser.Point} a - The Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.rperp = function (a, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    return out.setTo(a.y, -a.x);
+
+};
+
+/**
+* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
+*
+* @method Phaser.Point.distance
+* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
+* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
+* @param {boolean} [round=false] - Round the distance to the nearest integer.
+* @return {number} The distance between this Point object and the destination Point object.
+*/
+Phaser.Point.distance = function (a, b, round) {
+
+    var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y);
+    return round ? Math.round(distance) : distance;
+
+};
+
+/**
+* Project two Points onto another Point.
+* 
+* @method Phaser.Point.project
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.project = function (a, b, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    var amt = a.dot(b) / b.getMagnitudeSq();
+
+    if (amt !== 0)
+    {
+        out.setTo(amt * b.x, amt * b.y);
+    }
+
+    return out;
+
+};
+
+/**
+* Project two Points onto a Point of unit length.
+* 
+* @method Phaser.Point.projectUnit
+* @param {Phaser.Point} a - The first Point object.
+* @param {Phaser.Point} b - The second Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.projectUnit = function (a, b, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    var amt = a.dot(b);
+
+    if (amt !== 0)
+    {
+        out.setTo(amt * b.x, amt * b.y);
+    }
+
+    return out;
+
+};
+
+/**
+* Right-hand normalize (make unit length) a Point.
+*
+* @method Phaser.Point.normalRightHand
+* @param {Phaser.Point} a - The Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.normalRightHand = function (a, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    return out.setTo(a.y * -1, a.x);
+
+};
+
+/**
+* Normalize (make unit length) a Point.
+*
+* @method Phaser.Point.normalize
+* @param {Phaser.Point} a - The Point object.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.normalize = function (a, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    var m = a.getMagnitude();
+
+    if (m !== 0)
+    {
+        out.setTo(a.x / m, a.y / m);
+    }
+
+    return out;
+
+};
+
+/**
+* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by
+* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument
+* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle.
+*
+* The distance allows you to specify a distance constraint for the rotation between the point and the 
+* coordinates. If none is given the distance between the two is calculated and used.
+*
+* @method Phaser.Point.rotate
+* @param {Phaser.Point} a - The Point object to rotate.
+* @param {number} x - The x coordinate of the anchor point
+* @param {number} y - The y coordinate of the anchor point
+* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by.
+* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
+* @param {number} [distance] - An optional distance constraint between the Point and the anchor.
+* @return {Phaser.Point} The modified point object.
+*/
+Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
+
+    if (asDegrees === undefined) { asDegrees = false; }
+    if (distance === undefined) { distance = null; }
+
+    if (asDegrees)
+    {
+        angle = Phaser.Math.degToRad(angle);
+    }
+
+    if (distance === null)
+    {
+        //  Get distance from origin (cx/cy) to this point
+        distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y)));
+    }
+
+    var t = angle + Math.atan2(a.y - y, a.x - x);
+
+    a.x = x + distance * Math.cos(t);
+    a.y = y + distance * Math.sin(t);
+
+    return a;
+
+};
+
+/**
+* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
+*
+* @method Phaser.Point.centroid
+* @param {Phaser.Point[]} points - The array of one or more points.
+* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.centroid = function (points, out) {
+
+    if (out === undefined) { out = new Phaser.Point(); }
+
+    if (Object.prototype.toString.call(points) !== '[object Array]')
+    {
+        throw new Error("Phaser.Point. Parameter 'points' must be an array");
+    }
+
+    var pointslength = points.length;
+
+    if (pointslength < 1)
+    {
+        throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
+    }
+
+    if (pointslength === 1)
+    {
+        out.copyFrom(points[0]);
+        return out;
+    }
+
+    for (var i = 0; i < pointslength; i++)
+    {
+        Phaser.Point.add(out, points[i], out);
+    }
+
+    out.divide(pointslength, pointslength);
+
+    return out;
+
+};
+
+/**
+* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values.
+* If the object doesn't contain those properties a Point with x/y of zero will be returned.
+*
+* @method Phaser.Point.parse
+* @static
+* @param {object} obj - The object to parse.
+* @param {string} [xProp='x'] - The property used to set the Point.x value.
+* @param {string} [yProp='y'] - The property used to set the Point.y value.
+* @return {Phaser.Point} The new Point object.
+*/
+Phaser.Point.parse = function(obj, xProp, yProp) {
+
+    xProp = xProp || 'x';
+    yProp = yProp || 'y';
+
+    var point = new Phaser.Point();
+
+    if (obj[xProp])
+    {
+        point.x = parseInt(obj[xProp], 10);
+    }
+
+    if (obj[yProp])
+    {
+        point.y = parseInt(obj[yProp], 10);
+    }
+
+    return point;
+
+};
+
+//   Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.Point = Phaser.Point;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @author       Adrien Brault <adrien.brault@gmail.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a new Polygon.
+* 
+* The points can be set from a variety of formats:
+*
+* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]`
+* - An array of objects with public x/y properties: `[obj1, obj2, ...]`
+* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]`
+* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)`
+* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)`
+* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)`
+*
+* @class Phaser.Polygon
+* @constructor
+* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set.
+*/
+Phaser.Polygon = function () {
+
+    /**
+    * @property {number} area - The area of this Polygon.
+    */
+    this.area = 0;
+
+    /**
+    * @property {array} _points - An array of Points that make up this Polygon.
+    * @private
+    */
+    this._points = [];
+
+    if (arguments.length > 0)
+    {
+        this.setTo.apply(this, arguments);
+    }
+
+    /**
+    * @property {boolean} closed - Is the Polygon closed or not?
+    */
+    this.closed = true;
+
+    /**
+     * @property {number} type - The base object type.
+     */
+    this.type = Phaser.POLYGON;
+
+};
+
+Phaser.Polygon.prototype = {
+
+    /**
+     * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ]
+     *
+     * @method Phaser.Polygon#toNumberArray
+     * @param {array} [output] - The array to append the points to. If not specified a new array will be created.
+     * @return {array} The flattened array.
+     */
+    toNumberArray: function (output) {
+
+        if (output === undefined) { output = []; }
+
+        for (var i = 0; i < this._points.length; i++)
+        {
+            if (typeof this._points[i] === 'number')
+            {
+                output.push(this._points[i]);
+                output.push(this._points[i + 1]);
+                i++;
+            }
+            else
+            {
+                output.push(this._points[i].x);
+                output.push(this._points[i].y);
+            }
+        }
+
+        return output;
+
+    },
+
+    /**
+     * Flattens this Polygon so the points are a sequence of numbers. Any Point objects found are removed and replaced with two numbers.
+     *
+     * @method Phaser.Polygon#flatten
+     * @return {Phaser.Polygon} This Polygon object
+     */
+    flatten: function () {
+
+        this._points = this.toNumberArray();
+
+        return this;
+
+    },
+
+    /**
+     * Creates a copy of the given Polygon.
+     * This is a deep clone, the resulting copy contains new Phaser.Point objects
+     *
+     * @method Phaser.Polygon#clone
+     * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created.
+     * @return {Phaser.Polygon} The cloned (`output`) polygon object.
+     */
+    clone: function (output) {
+
+        var points = this._points.slice();
+
+        if (output === undefined || output === null)
+        {
+            output = new Phaser.Polygon(points);
+        }
+        else
+        {
+            output.setTo(points);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Checks whether the x and y coordinates are contained within this polygon.
+    *
+    * @method Phaser.Polygon#contains
+    * @param {number} x - The X value of the coordinate to test.
+    * @param {number} y - The Y value of the coordinate to test.
+    * @return {boolean} True if the coordinates are within this polygon, otherwise false.
+    */
+    contains: function (x, y) {
+
+        //  Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva
+
+        var length = this._points.length;
+        var inside = false;
+
+        for (var i = -1, j = length - 1; ++i < length; j = i)
+        {
+            var ix = this._points[i].x;
+            var iy = this._points[i].y;
+
+            var jx = this._points[j].x;
+            var jy = this._points[j].y;
+
+            if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix))
+            {
+                inside = !inside;
+            }
+        }
+
+        return inside;
+
+    },
+
+    /**
+     * Sets this Polygon to the given points.
+     *
+     * The points can be set from a variety of formats:
+     *
+     * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]`
+     * - An array of objects with public x/y properties: `[obj1, obj2, ...]`
+     * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]`
+     * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)`
+     * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)`
+     * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)`
+     *
+     * `setTo` may also be called without any arguments to remove all points.
+     *
+     * @method Phaser.Polygon#setTo
+     * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set.
+     * @return {Phaser.Polygon} This Polygon object
+     */
+    setTo: function (points) {
+
+        this.area = 0;
+        this._points = [];
+
+        if (arguments.length > 0)
+        {
+            //  If points isn't an array, use arguments as the array
+            if (!Array.isArray(points))
+            {
+                points = Array.prototype.slice.call(arguments);
+            }
+
+            var y0 = Number.MAX_VALUE;
+
+            //  Allows for mixed-type arguments
+            for (var i = 0, len = points.length; i < len; i++)
+            {
+                if (typeof points[i] === 'number')
+                {
+                    var p = new PIXI.Point(points[i], points[i + 1]);
+                    i++;
+                }
+                else
+                {
+                    var p = new PIXI.Point(points[i].x, points[i].y);
+                }
+
+                this._points.push(p);
+
+                //  Lowest boundary
+                if (p.y < y0)
+                {
+                    y0 = p.y;
+                }
+            }
+
+            this.calculateArea(y0);
+        }
+
+        return this;
+
+    },
+
+    /**
+     * Calcuates the area of the Polygon. This is available in the property Polygon.area
+     *
+     * @method Phaser.Polygon#calculateArea
+     * @private
+     * @param {number} y0 - The lowest boundary
+     * @return {number} The area of the Polygon.
+     */
+    calculateArea: function (y0) {
+
+        var p1;
+        var p2;
+        var avgHeight;
+        var width;
+
+        for (var i = 0, len = this._points.length; i < len; i++)
+        {
+            p1 = this._points[i];
+
+            if (i === len - 1)
+            {
+                p2 = this._points[0];
+            }
+            else
+            {
+                p2 = this._points[i + 1];
+            }
+
+            avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2;
+            width = p1.x - p2.x;
+            this.area += avgHeight * width;
+        }
+
+        return this.area;
+
+    }
+
+};
+
+Phaser.Polygon.prototype.constructor = Phaser.Polygon;
+
+/**
+* Sets and modifies the points of this polygon.
+*
+* See {@link Phaser.Polygon#setTo setTo} for the different kinds of arrays formats that can be assigned.
+*
+* @name Phaser.Polygon#points
+* @property {Phaser.Point[]} points - The array of vertex points.
+* @deprecated Use `setTo`.
+*/
+Object.defineProperty(Phaser.Polygon.prototype, 'points', {
+
+    get: function() {
+        return this._points;
+    },
+
+    set: function(points) {
+
+        if (points != null)
+        {
+            this.setTo(points);
+        }
+        else
+        {
+            //  Clear the points
+            this.setTo();
+        }
+
+    }
+
+});
+
+//  Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.Polygon = Phaser.Polygon;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters.
+* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created.
+*
+* @class Phaser.Rectangle
+* @constructor
+* @param {number} x - The x coordinate of the top-left corner of the Rectangle.
+* @param {number} y - The y coordinate of the top-left corner of the Rectangle.
+* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
+* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
+*/
+Phaser.Rectangle = function (x, y, width, height) {
+
+    x = x || 0;
+    y = y || 0;
+    width = width || 0;
+    height = height || 0;
+
+    /**
+    * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
+    */
+    this.y = y;
+
+    /**
+    * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
+    */
+    this.width = width;
+
+    /**
+    * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
+    */
+    this.height = height;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.RECTANGLE;
+
+};
+
+Phaser.Rectangle.prototype = {
+
+    /**
+    * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
+    * @method Phaser.Rectangle#offset
+    * @param {number} dx - Moves the x value of the Rectangle object by this amount.
+    * @param {number} dy - Moves the y value of the Rectangle object by this amount.
+    * @return {Phaser.Rectangle} This Rectangle object.
+    */
+    offset: function (dx, dy) {
+
+        this.x += dx;
+        this.y += dy;
+
+        return this;
+
+    },
+
+    /**
+    * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
+    * @method Phaser.Rectangle#offsetPoint
+    * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
+    * @return {Phaser.Rectangle} This Rectangle object.
+    */
+    offsetPoint: function (point) {
+
+        return this.offset(point.x, point.y);
+
+    },
+
+    /**
+    * Sets the members of Rectangle to the specified values.
+    * @method Phaser.Rectangle#setTo
+    * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
+    * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
+    * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
+    * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
+    * @return {Phaser.Rectangle} This Rectangle object
+    */
+    setTo: function (x, y, width, height) {
+
+        this.x = x;
+        this.y = y;
+        this.width = width;
+        this.height = height;
+
+        return this;
+
+    },
+
+    /**
+    * Scales the width and height of this Rectangle by the given amounts.
+    * 
+    * @method Phaser.Rectangle#scale
+    * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc.
+    * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc.
+    * @return {Phaser.Rectangle} This Rectangle object
+    */
+    scale: function (x, y) {
+
+        if (y === undefined) { y = x; }
+
+        this.width *= x;
+        this.height *= y;
+
+        return this;
+
+    },
+
+    /**
+    * Centers this Rectangle so that the center coordinates match the given x and y values.
+    *
+    * @method Phaser.Rectangle#centerOn
+    * @param {number} x - The x coordinate to place the center of the Rectangle at.
+    * @param {number} y - The y coordinate to place the center of the Rectangle at.
+    * @return {Phaser.Rectangle} This Rectangle object
+    */
+    centerOn: function (x, y) {
+
+        this.centerX = x;
+        this.centerY = y;
+
+        return this;
+
+    },
+
+    /**
+    * Runs Math.floor() on both the x and y values of this Rectangle.
+    * @method Phaser.Rectangle#floor
+    */
+    floor: function () {
+
+        this.x = Math.floor(this.x);
+        this.y = Math.floor(this.y);
+
+    },
+
+    /**
+    * Runs Math.floor() on the x, y, width and height values of this Rectangle.
+    * @method Phaser.Rectangle#floorAll
+    */
+    floorAll: function () {
+
+        this.x = Math.floor(this.x);
+        this.y = Math.floor(this.y);
+        this.width = Math.floor(this.width);
+        this.height = Math.floor(this.height);
+
+    },
+
+    /**
+    * Runs Math.ceil() on both the x and y values of this Rectangle.
+    * @method Phaser.Rectangle#ceil
+    */
+    ceil: function () {
+
+        this.x = Math.ceil(this.x);
+        this.y = Math.ceil(this.y);
+
+    },
+
+    /**
+    * Runs Math.ceil() on the x, y, width and height values of this Rectangle.
+    * @method Phaser.Rectangle#ceilAll
+    */
+    ceilAll: function () {
+
+        this.x = Math.ceil(this.x);
+        this.y = Math.ceil(this.y);
+        this.width = Math.ceil(this.width);
+        this.height = Math.ceil(this.height);
+
+    },
+
+    /**
+    * Copies the x, y, width and height properties from any given object to this Rectangle.
+    * @method Phaser.Rectangle#copyFrom
+    * @param {any} source - The object to copy from.
+    * @return {Phaser.Rectangle} This Rectangle object.
+    */
+    copyFrom: function (source) {
+
+        return this.setTo(source.x, source.y, source.width, source.height);
+
+    },
+
+    /**
+    * Copies the x, y, width and height properties from this Rectangle to any given object.
+    * @method Phaser.Rectangle#copyTo
+    * @param {any} source - The object to copy to.
+    * @return {object} This object.
+    */
+    copyTo: function (dest) {
+
+        dest.x = this.x;
+        dest.y = this.y;
+        dest.width = this.width;
+        dest.height = this.height;
+
+        return dest;
+
+    },
+
+    /**
+    * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
+    * @method Phaser.Rectangle#inflate
+    * @param {number} dx - The amount to be added to the left side of the Rectangle.
+    * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
+    * @return {Phaser.Rectangle} This Rectangle object.
+    */
+    inflate: function (dx, dy) {
+
+        return Phaser.Rectangle.inflate(this, dx, dy);
+
+    },
+
+    /**
+    * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
+    * @method Phaser.Rectangle#size
+    * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
+    * @return {Phaser.Point} The size of the Rectangle object.
+    */
+    size: function (output) {
+
+        return Phaser.Rectangle.size(this, output);
+
+    },
+
+    /**
+    * Resize the Rectangle by providing a new width and height.
+    * The x and y positions remain unchanged.
+    * 
+    * @method Phaser.Rectangle#resize
+    * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
+    * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
+    * @return {Phaser.Rectangle} This Rectangle object
+    */
+    resize: function (width, height) {
+
+        this.width = width;
+        this.height = height;
+
+        return this;
+
+    },
+
+    /**
+    * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
+    * @method Phaser.Rectangle#clone
+    * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
+    * @return {Phaser.Rectangle}
+    */
+    clone: function (output) {
+
+        return Phaser.Rectangle.clone(this, output);
+
+    },
+
+    /**
+    * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
+    * @method Phaser.Rectangle#contains
+    * @param {number} x - The x coordinate of the point to test.
+    * @param {number} y - The y coordinate of the point to test.
+    * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
+    */
+    contains: function (x, y) {
+
+        return Phaser.Rectangle.contains(this, x, y);
+
+    },
+
+    /**
+    * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
+    * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
+    * @method Phaser.Rectangle#containsRect
+    * @param {Phaser.Rectangle} b - The second Rectangle object.
+    * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
+    */
+    containsRect: function (b) {
+
+        return Phaser.Rectangle.containsRect(b, this);
+
+    },
+
+    /**
+    * Determines whether the two Rectangles are equal.
+    * This method compares the x, y, width and height properties of each Rectangle.
+    * @method Phaser.Rectangle#equals
+    * @param {Phaser.Rectangle} b - The second Rectangle object.
+    * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
+    */
+    equals: function (b) {
+
+        return Phaser.Rectangle.equals(this, b);
+
+    },
+
+    /**
+    * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
+    * @method Phaser.Rectangle#intersection
+    * @param {Phaser.Rectangle} b - The second Rectangle object.
+    * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
+    * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
+    */
+    intersection: function (b, out) {
+
+        return Phaser.Rectangle.intersection(this, b, out);
+
+    },
+
+    /**
+    * Determines whether this Rectangle and another given Rectangle intersect with each other.
+    * This method checks the x, y, width, and height properties of the two Rectangles.
+    * 
+    * @method Phaser.Rectangle#intersects
+    * @param {Phaser.Rectangle} b - The second Rectangle object.
+    * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
+    */
+    intersects: function (b) {
+
+        return Phaser.Rectangle.intersects(this, b);
+
+    },
+
+    /**
+    * Determines whether the coordinates given intersects (overlaps) with this Rectangle.
+    *
+    * @method Phaser.Rectangle#intersectsRaw
+    * @param {number} left - The x coordinate of the left of the area.
+    * @param {number} right - The right coordinate of the area.
+    * @param {number} top - The y coordinate of the area.
+    * @param {number} bottom - The bottom coordinate of the area.
+    * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
+    * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
+    */
+    intersectsRaw: function (left, right, top, bottom, tolerance) {
+
+        return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
+
+    },
+
+    /**
+    * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
+    * @method Phaser.Rectangle#union
+    * @param {Phaser.Rectangle} b - The second Rectangle object.
+    * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
+    * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
+    */
+    union: function (b, out) {
+
+        return Phaser.Rectangle.union(this, b, out);
+
+    },
+
+    /**
+    * Returns a uniformly distributed random point from anywhere within this Rectangle.
+    * 
+    * @method Phaser.Rectangle#random
+    * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
+    *     If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
+    * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
+    */
+    random: function (out) {
+
+        if (out === undefined) { out = new Phaser.Point(); }
+
+        out.x = this.randomX;
+        out.y = this.randomY;
+
+        return out;
+
+    },
+
+    /**
+    * Returns a string representation of this object.
+    * @method Phaser.Rectangle#toString
+    * @return {string} A string representation of the instance.
+    */
+    toString: function () {
+
+        return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
+
+    }
+
+};
+
+/**
+* @name Phaser.Rectangle#halfWidth
+* @property {number} halfWidth - Half of the width of the Rectangle.
+* @readonly
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
+
+    get: function () {
+        return Math.round(this.width / 2);
+    }
+
+});
+
+/**
+* @name Phaser.Rectangle#halfHeight
+* @property {number} halfHeight - Half of the height of the Rectangle.
+* @readonly
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
+
+    get: function () {
+        return Math.round(this.height / 2);
+    }
+
+});
+
+/**
+* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
+* @name Phaser.Rectangle#bottom
+* @property {number} bottom - The sum of the y and height properties.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
+
+    get: function () {
+        return this.y + this.height;
+    },
+
+    set: function (value) {
+
+        if (value <= this.y)
+        {
+            this.height = 0;
+        }
+        else
+        {
+            this.height = value - this.y;
+        }
+
+    }
+
+});
+
+/**
+* The location of the Rectangles bottom left corner as a Point object.
+* @name Phaser.Rectangle#bottomLeft
+* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", {
+
+    get: function () {
+        return new Phaser.Point(this.x, this.bottom);
+    },
+
+    set: function (value) {
+        this.x = value.x;
+        this.bottom = value.y;
+    }
+
+});
+
+/**
+* The location of the Rectangles bottom right corner as a Point object.
+* @name Phaser.Rectangle#bottomRight
+* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
+
+    get: function () {
+        return new Phaser.Point(this.right, this.bottom);
+    },
+
+    set: function (value) {
+        this.right = value.x;
+        this.bottom = value.y;
+    }
+
+});
+
+/**
+* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property.
+* @name Phaser.Rectangle#left
+* @property {number} left - The x coordinate of the left of the Rectangle.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "left", {
+
+    get: function () {
+        return this.x;
+    },
+
+    set: function (value) {
+        if (value >= this.right) {
+            this.width = 0;
+        } else {
+            this.width = this.right - value;
+        }
+        this.x = value;
+    }
+
+});
+
+/**
+* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property.
+* @name Phaser.Rectangle#right
+* @property {number} right - The sum of the x and width properties.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "right", {
+
+    get: function () {
+        return this.x + this.width;
+    },
+
+    set: function (value) {
+        if (value <= this.x) {
+            this.width = 0;
+        } else {
+            this.width = value - this.x;
+        }
+    }
+
+});
+
+/**
+* The volume of the Rectangle derived from width * height.
+* @name Phaser.Rectangle#volume
+* @property {number} volume - The volume of the Rectangle derived from width * height.
+* @readonly
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
+
+    get: function () {
+        return this.width * this.height;
+    }
+
+});
+
+/**
+* The perimeter size of the Rectangle. This is the sum of all 4 sides.
+* @name Phaser.Rectangle#perimeter
+* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
+* @readonly
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
+
+    get: function () {
+        return (this.width * 2) + (this.height * 2);
+    }
+
+});
+
+/**
+* The x coordinate of the center of the Rectangle.
+* @name Phaser.Rectangle#centerX
+* @property {number} centerX - The x coordinate of the center of the Rectangle.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
+
+    get: function () {
+        return this.x + this.halfWidth;
+    },
+
+    set: function (value) {
+        this.x = value - this.halfWidth;
+    }
+
+});
+
+/**
+* The y coordinate of the center of the Rectangle.
+* @name Phaser.Rectangle#centerY
+* @property {number} centerY - The y coordinate of the center of the Rectangle.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
+
+    get: function () {
+        return this.y + this.halfHeight;
+    },
+
+    set: function (value) {
+        this.y = value - this.halfHeight;
+    }
+
+});
+
+/**
+* A random value between the left and right values (inclusive) of the Rectangle.
+*
+* @name Phaser.Rectangle#randomX
+* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "randomX", {
+
+    get: function () {
+
+        return this.x + (Math.random() * this.width);
+
+    }
+
+});
+
+/**
+* A random value between the top and bottom values (inclusive) of the Rectangle.
+*
+* @name Phaser.Rectangle#randomY
+* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "randomY", {
+
+    get: function () {
+
+        return this.y + (Math.random() * this.height);
+
+    }
+
+});
+
+/**
+* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties.
+* However it does affect the height property, whereas changing the y value does not affect the height property.
+* @name Phaser.Rectangle#top
+* @property {number} top - The y coordinate of the top of the Rectangle.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "top", {
+
+    get: function () {
+        return this.y;
+    },
+
+    set: function (value) {
+        if (value >= this.bottom) {
+            this.height = 0;
+            this.y = value;
+        } else {
+            this.height = (this.bottom - value);
+        }
+    }
+
+});
+
+/**
+* The location of the Rectangles top left corner as a Point object.
+* @name Phaser.Rectangle#topLeft
+* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
+
+    get: function () {
+        return new Phaser.Point(this.x, this.y);
+    },
+
+    set: function (value) {
+        this.x = value.x;
+        this.y = value.y;
+    }
+
+});
+
+/**
+* The location of the Rectangles top right corner as a Point object.
+* @name Phaser.Rectangle#topRight
+* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "topRight", {
+
+    get: function () {
+        return new Phaser.Point(this.x + this.width, this.y);
+    },
+
+    set: function (value) {
+        this.right = value.x;
+        this.y = value.y;
+    }
+
+});
+
+/**
+* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0.
+* If set to true then all of the Rectangle properties are set to 0.
+* @name Phaser.Rectangle#empty
+* @property {boolean} empty - Gets or sets the Rectangles empty state.
+*/
+Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
+
+    get: function () {
+        return (!this.width || !this.height);
+    },
+
+    set: function (value) {
+
+        if (value === true)
+        {
+            this.setTo(0, 0, 0, 0);
+        }
+
+    }
+
+});
+
+Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
+
+/**
+* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
+* @method Phaser.Rectangle.inflate
+* @param {Phaser.Rectangle} a - The Rectangle object.
+* @param {number} dx - The amount to be added to the left side of the Rectangle.
+* @param {number} dy - The amount to be added to the bottom side of the Rectangle.
+* @return {Phaser.Rectangle} This Rectangle object.
+*/
+Phaser.Rectangle.inflate = function (a, dx, dy) {
+
+    a.x -= dx;
+    a.width += 2 * dx;
+    a.y -= dy;
+    a.height += 2 * dy;
+
+    return a;
+
+};
+
+/**
+* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
+* @method Phaser.Rectangle.inflatePoint
+* @param {Phaser.Rectangle} a - The Rectangle object.
+* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
+* @return {Phaser.Rectangle} The Rectangle object.
+*/
+Phaser.Rectangle.inflatePoint = function (a, point) {
+
+    return Phaser.Rectangle.inflate(a, point.x, point.y);
+
+};
+
+/**
+* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
+* @method Phaser.Rectangle.size
+* @param {Phaser.Rectangle} a - The Rectangle object.
+* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
+* @return {Phaser.Point} The size of the Rectangle object
+*/
+Phaser.Rectangle.size = function (a, output) {
+
+    if (output === undefined || output === null)
+    {
+        output = new Phaser.Point(a.width, a.height);
+    }
+    else
+    {
+        output.setTo(a.width, a.height);
+    }
+
+    return output;
+
+};
+
+/**
+* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
+* @method Phaser.Rectangle.clone
+* @param {Phaser.Rectangle} a - The Rectangle object.
+* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
+* @return {Phaser.Rectangle}
+*/
+Phaser.Rectangle.clone = function (a, output) {
+
+    if (output === undefined || output === null)
+    {
+        output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
+    }
+    else
+    {
+        output.setTo(a.x, a.y, a.width, a.height);
+    }
+
+    return output;
+
+};
+
+/**
+* Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
+* @method Phaser.Rectangle.contains
+* @param {Phaser.Rectangle} a - The Rectangle object.
+* @param {number} x - The x coordinate of the point to test.
+* @param {number} y - The y coordinate of the point to test.
+* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
+*/
+Phaser.Rectangle.contains = function (a, x, y) {
+
+    if (a.width <= 0 || a.height <= 0)
+    {
+        return false;
+    }
+
+    return (x >= a.x && x < a.right && y >= a.y && y < a.bottom);
+
+};
+
+/**
+* Determines whether the specified coordinates are contained within the region defined by the given raw values.
+* @method Phaser.Rectangle.containsRaw
+* @param {number} rx - The x coordinate of the top left of the area.
+* @param {number} ry - The y coordinate of the top left of the area.
+* @param {number} rw - The width of the area.
+* @param {number} rh - The height of the area.
+* @param {number} x - The x coordinate of the point to test.
+* @param {number} y - The y coordinate of the point to test.
+* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
+*/
+Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
+
+    return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh));
+
+};
+
+/**
+* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
+* @method Phaser.Rectangle.containsPoint
+* @param {Phaser.Rectangle} a - The Rectangle object.
+* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
+* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
+*/
+Phaser.Rectangle.containsPoint = function (a, point) {
+
+    return Phaser.Rectangle.contains(a, point.x, point.y);
+
+};
+
+/**
+* Determines whether the first Rectangle object is fully contained within the second Rectangle object.
+* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
+* @method Phaser.Rectangle.containsRect
+* @param {Phaser.Rectangle} a - The first Rectangle object.
+* @param {Phaser.Rectangle} b - The second Rectangle object.
+* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
+*/
+Phaser.Rectangle.containsRect = function (a, b) {
+
+    //  If the given rect has a larger volume than this one then it can never contain it
+    if (a.volume > b.volume)
+    {
+        return false;
+    }
+
+    return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom);
+
+};
+
+/**
+* Determines whether the two Rectangles are equal.
+* This method compares the x, y, width and height properties of each Rectangle.
+* @method Phaser.Rectangle.equals
+* @param {Phaser.Rectangle} a - The first Rectangle object.
+* @param {Phaser.Rectangle} b - The second Rectangle object.
+* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
+*/
+Phaser.Rectangle.equals = function (a, b) {
+
+    return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
+
+};
+
+/**
+* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality.
+* @method Phaser.Rectangle.sameDimensions
+* @param {Rectangle-like} a - The first Rectangle object.
+* @param {Rectangle-like} b - The second Rectangle object.
+* @return {boolean} True if the object have equivalent values for the width and height properties.
+*/
+Phaser.Rectangle.sameDimensions = function (a, b) {
+
+    return (a.width === b.width && a.height === b.height);
+
+};
+
+/**
+* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
+* @method Phaser.Rectangle.intersection
+* @param {Phaser.Rectangle} a - The first Rectangle object.
+* @param {Phaser.Rectangle} b - The second Rectangle object.
+* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
+* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
+*/
+Phaser.Rectangle.intersection = function (a, b, output) {
+
+    if (output === undefined)
+    {
+        output = new Phaser.Rectangle();
+    }
+
+    if (Phaser.Rectangle.intersects(a, b))
+    {
+        output.x = Math.max(a.x, b.x);
+        output.y = Math.max(a.y, b.y);
+        output.width = Math.min(a.right, b.right) - output.x;
+        output.height = Math.min(a.bottom, b.bottom) - output.y;
+    }
+
+    return output;
+
+};
+
+/**
+* Determines whether the two Rectangles intersect with each other.
+* This method checks the x, y, width, and height properties of the Rectangles.
+* @method Phaser.Rectangle.intersects
+* @param {Phaser.Rectangle} a - The first Rectangle object.
+* @param {Phaser.Rectangle} b - The second Rectangle object.
+* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
+*/
+Phaser.Rectangle.intersects = function (a, b) {
+
+    if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
+    {
+        return false;
+    }
+
+    return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
+
+};
+
+/**
+* Determines whether the object specified intersects (overlaps) with the given values.
+* @method Phaser.Rectangle.intersectsRaw
+* @param {number} left - The x coordinate of the left of the area.
+* @param {number} right - The right coordinate of the area.
+* @param {number} top - The y coordinate of the area.
+* @param {number} bottom - The bottom coordinate of the area.
+* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
+* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
+*/
+Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
+
+    if (tolerance === undefined) { tolerance = 0; }
+
+    return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
+
+};
+
+/**
+* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
+* @method Phaser.Rectangle.union
+* @param {Phaser.Rectangle} a - The first Rectangle object.
+* @param {Phaser.Rectangle} b - The second Rectangle object.
+* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
+* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
+*/
+Phaser.Rectangle.union = function (a, b, output) {
+
+    if (output === undefined)
+    {
+        output = new Phaser.Rectangle();
+    }
+
+    return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top));
+
+};
+
+/**
+* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points.
+*
+* @method Phaser.Rectangle#aabb
+* @param {Phaser.Point[]} points - The array of one or more points.
+* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created.
+* @return {Phaser.Rectangle} The new Rectangle object.
+* @static
+*/
+Phaser.Rectangle.aabb = function(points, out) {
+
+    if (out === undefined) {
+        out = new Phaser.Rectangle();
+    }
+
+    var xMax = Number.MIN_VALUE,
+        xMin = Number.MAX_VALUE,
+        yMax = Number.MIN_VALUE,
+        yMin = Number.MAX_VALUE;
+
+    points.forEach(function(point) {
+        if (point.x > xMax) {
+            xMax = point.x;
+        }
+        if (point.x < xMin) {
+            xMin = point.x;
+        }
+
+        if (point.y > yMax) {
+            yMax = point.y;
+        }
+        if (point.y < yMin) {
+            yMin = point.y;
+        }
+    });
+
+    out.setTo(xMin, yMin, xMax - xMin, yMax - yMin);
+
+    return out;
+};
+
+//   Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.Rectangle = Phaser.Rectangle;
+PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
+
+/**
+* @author       Mat Groves http://matgroves.com/
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, 
+* as indicated by its top-left corner point (x, y) and by its width and its height.
+*
+* @class Phaser.RoundedRectangle
+* @constructor
+* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle.
+* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle.
+* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value.
+* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value.
+* @param {number} [radius=20] - Controls the radius of the rounded corners.
+*/
+Phaser.RoundedRectangle = function(x, y, width, height, radius)
+{
+    if (x === undefined) { x = 0; }
+    if (y === undefined) { y = 0; }
+    if (width === undefined) { width = 0; }
+    if (height === undefined) { height = 0; }
+    if (radius === undefined) { radius = 20; }
+
+    /**
+    * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
+    */
+    this.y = y;
+
+    /**
+    * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
+    */
+    this.width = width;
+
+    /**
+    * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
+    */
+    this.height = height;
+
+    /**
+    * @property {number} radius - The radius of the rounded corners.
+    */
+    this.radius = radius || 20;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.ROUNDEDRECTANGLE;
+};
+
+Phaser.RoundedRectangle.prototype = {
+
+    /**
+    * Returns a new RoundedRectangle object with the same values for the x, y, width, height and
+    * radius properties as this RoundedRectangle object.
+    * 
+    * @method Phaser.RoundedRectangle#clone
+    * @return {Phaser.RoundedRectangle}
+    */
+    clone: function () {
+
+        return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
+
+    },
+
+    /**
+    * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object.
+    * 
+    * @method Phaser.RoundedRectangle#contains
+    * @param {number} x - The x coordinate of the point to test.
+    * @param {number} y - The y coordinate of the point to test.
+    * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false.
+    */
+    contains: function (x, y) {
+
+        if (this.width <= 0 || this.height <= 0)
+        {
+            return false;
+        }
+
+        var x1 = this.x;
+
+        if (x >= x1 && x <= x1 + this.width)
+        {
+            var y1 = this.y;
+
+            if (y >= y1 && y <= y1 + this.height)
+            {
+                return true;
+            }
+        }
+
+        return false;
+
+    }
+
+};
+
+Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle;
+
+//  Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
+PIXI.RoundedRectangle = Phaser.RoundedRectangle;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view.
+* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
+*
+* @class Phaser.Camera
+* @constructor
+* @param {Phaser.Game} game - Game reference to the currently running game.
+* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
+* @param {number} x - Position of the camera on the X axis
+* @param {number} y - Position of the camera on the Y axis
+* @param {number} width - The width of the view rectangle
+* @param {number} height - The height of the view rectangle
+*/
+Phaser.Camera = function (game, id, x, y, width, height) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.World} world - A reference to the game world.
+    */
+    this.world = game.world;
+
+    /**
+    * @property {number} id - Reserved for future multiple camera set-ups.
+    * @default
+    */
+    this.id = 0;
+
+    /**
+    * Camera view.
+    * The view into the world we wish to render (by default the game dimensions).
+    * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
+    * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered.
+    * @property {Phaser.Rectangle} view
+    */
+    this.view = new Phaser.Rectangle(x, y, width, height);
+
+    /**
+    * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World.
+    * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound
+    * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world.
+    * 
+    * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
+    */
+    this.bounds = new Phaser.Rectangle(x, y, width, height);
+
+    /**
+    * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move.
+    */
+    this.deadzone = null;
+
+    /**
+    * @property {boolean} visible - Whether this camera is visible or not.
+    * @default
+    */
+    this.visible = true;
+
+    /**
+    * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening.
+    * @default
+    */
+    this.roundPx = true;
+
+    /**
+    * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
+    */
+    this.atLimit = { x: false, y: false };
+
+    /**
+    * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
+    * @default
+    */
+    this.target = null;
+
+    /**
+    * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot
+    */
+    this.displayObject = null;
+
+    /**
+    * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot
+    */
+    this.scale = null;
+
+    /**
+    * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera.
+    * @readonly
+    */
+    this.totalInView = 0;
+
+    /**
+    * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position
+    * @private
+    */
+    this._targetPosition = new Phaser.Point();
+
+    /**
+    * @property {number} edge - Edge property.
+    * @private
+    * @default
+    */
+    this._edge = 0;
+
+    /**
+    * @property {Phaser.Point} position - Current position of the camera in world.
+    * @private
+    * @default
+    */
+    this._position = new Phaser.Point();
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Camera.FOLLOW_LOCKON = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Camera.FOLLOW_PLATFORMER = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Camera.FOLLOW_TOPDOWN = 2;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
+
+Phaser.Camera.prototype = {
+
+    /**
+    * Camera preUpdate. Sets the total view counter to zero.
+    *
+    * @method Phaser.Camera#preUpdate
+    */
+    preUpdate: function () {
+
+        this.totalInView = 0;
+
+    },
+
+    /**
+    * Tell the camera which sprite to follow.
+    * 
+    * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position.
+    * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering.
+    * 
+    * @method Phaser.Camera#follow
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
+    * @param {number} [style] - Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow().
+    */
+    follow: function (target, style) {
+
+        if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; }
+
+        this.target = target;
+
+        var helper;
+
+        switch (style) {
+
+            case Phaser.Camera.FOLLOW_PLATFORMER:
+                var w = this.width / 8;
+                var h = this.height / 3;
+                this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
+                break;
+
+            case Phaser.Camera.FOLLOW_TOPDOWN:
+                helper = Math.max(this.width, this.height) / 4;
+                this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
+                break;
+
+            case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
+                helper = Math.max(this.width, this.height) / 8;
+                this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
+                break;
+
+            case Phaser.Camera.FOLLOW_LOCKON:
+                this.deadzone = null;
+                break;
+
+            default:
+                this.deadzone = null;
+                break;
+        }
+
+    },
+
+    /**
+    * Sets the Camera follow target to null, stopping it from following an object if it's doing so.
+    *
+    * @method Phaser.Camera#unfollow
+    */
+    unfollow: function () {
+
+        this.target = null;
+
+    },
+
+    /**
+    * Move the camera focus on a display object instantly.
+    * @method Phaser.Camera#focusOn
+    * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
+    */
+    focusOn: function (displayObject) {
+
+        this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
+
+    },
+
+    /**
+    * Move the camera focus on a location instantly.
+    * @method Phaser.Camera#focusOnXY
+    * @param {number} x - X position.
+    * @param {number} y - Y position.
+    */
+    focusOnXY: function (x, y) {
+
+        this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
+
+    },
+
+    /**
+    * Update focusing and scrolling.
+    * @method Phaser.Camera#update
+    */
+    update: function () {
+
+        if (this.target)
+        {
+            this.updateTarget();
+        }
+
+        if (this.bounds)
+        {
+            this.checkBounds();
+        }
+
+        if (this.roundPx)
+        {
+            this.view.floor();
+        }
+
+        this.displayObject.position.x = -this.view.x;
+        this.displayObject.position.y = -this.view.y;
+
+    },
+
+    /**
+    * Internal method
+    * @method Phaser.Camera#updateTarget
+    * @private
+    */
+    updateTarget: function () {
+
+        this._targetPosition.copyFrom(this.target);
+
+        if (this.target.parent)
+        {
+            this._targetPosition.multiply(this.target.parent.worldTransform.a, this.target.parent.worldTransform.d);
+        }
+
+        if (this.deadzone)
+        {
+            this._edge = this._targetPosition.x - this.view.x;
+
+            if (this._edge < this.deadzone.left)
+            {
+                this.view.x = this._targetPosition.x - this.deadzone.left;
+            }
+            else if (this._edge > this.deadzone.right)
+            {
+                this.view.x = this._targetPosition.x - this.deadzone.right;
+            }
+
+            this._edge = this._targetPosition.y - this.view.y;
+
+            if (this._edge < this.deadzone.top)
+            {
+                this.view.y = this._targetPosition.y - this.deadzone.top;
+            }
+            else if (this._edge > this.deadzone.bottom)
+            {
+                this.view.y = this._targetPosition.y - this.deadzone.bottom;
+            }
+        }
+        else
+        {
+            this.view.x = this._targetPosition.x - this.view.halfWidth;
+            this.view.y = this._targetPosition.y - this.view.halfHeight;
+        }
+
+    },
+
+    /**
+    * Update the Camera bounds to match the game world.
+    * @method Phaser.Camera#setBoundsToWorld
+    */
+    setBoundsToWorld: function () {
+
+        this.bounds.copyFrom(this.game.world.bounds);
+
+    },
+
+    /**
+    * Method called to ensure the camera doesn't venture outside of the game world.
+    * @method Phaser.Camera#checkBounds
+    */
+    checkBounds: function () {
+
+        this.atLimit.x = false;
+        this.atLimit.y = false;
+
+        //  Make sure we didn't go outside the cameras bounds
+        if (this.view.x <= this.bounds.x)
+        {
+            this.atLimit.x = true;
+            this.view.x = this.bounds.x;
+        }
+
+        if (this.view.right >= this.bounds.right)
+        {
+            this.atLimit.x = true;
+            this.view.x = this.bounds.right - this.width;
+        }
+
+        if (this.view.y <= this.bounds.top)
+        {
+            this.atLimit.y = true;
+            this.view.y = this.bounds.top;
+        }
+
+        if (this.view.bottom >= this.bounds.bottom)
+        {
+            this.atLimit.y = true;
+            this.view.y = this.bounds.bottom - this.height;
+        }
+
+    },
+
+    /**
+    * A helper function to set both the X and Y properties of the camera at once
+    * without having to use game.camera.x and game.camera.y.
+    *
+    * @method Phaser.Camera#setPosition
+    * @param {number} x - X position.
+    * @param {number} y - Y position.
+    */
+    setPosition: function (x, y) {
+
+        this.view.x = x;
+        this.view.y = y;
+
+        if (this.bounds)
+        {
+            this.checkBounds();
+        }
+
+    },
+
+    /**
+    * Sets the size of the view rectangle given the width and height in parameters.
+    *
+    * @method Phaser.Camera#setSize
+    * @param {number} width - The desired width.
+    * @param {number} height - The desired height.
+    */
+    setSize: function (width, height) {
+
+        this.view.width = width;
+        this.view.height = height;
+
+    },
+
+    /**
+    * Resets the camera back to 0,0 and un-follows any object it may have been tracking.
+    *
+    * @method Phaser.Camera#reset
+    */
+    reset: function () {
+
+        this.target = null;
+        this.view.x = 0;
+        this.view.y = 0;
+
+    }
+
+};
+
+Phaser.Camera.prototype.constructor = Phaser.Camera;
+
+/**
+* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
+* @name Phaser.Camera#x
+* @property {number} x - Gets or sets the cameras x position.
+*/
+Object.defineProperty(Phaser.Camera.prototype, "x", {
+
+    get: function () {
+        return this.view.x;
+    },
+
+    set: function (value) {
+
+        this.view.x = value;
+
+        if (this.bounds)
+        {
+            this.checkBounds();
+        }
+    }
+
+});
+
+/**
+* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
+* @name Phaser.Camera#y
+* @property {number} y - Gets or sets the cameras y position.
+*/
+Object.defineProperty(Phaser.Camera.prototype, "y", {
+
+    get: function () {
+        return this.view.y;
+    },
+
+    set: function (value) {
+
+        this.view.y = value;
+
+        if (this.bounds)
+        {
+            this.checkBounds();
+        }
+    }
+
+});
+
+/**
+* The Cameras position. This value is automatically clamped if it falls outside of the World bounds.
+* @name Phaser.Camera#position
+* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object.
+*/
+Object.defineProperty(Phaser.Camera.prototype, "position", {
+
+    get: function () {
+        this._position.set(this.view.centerX, this.view.centerY);
+        return this._position;
+    },
+
+    set: function (value) {
+
+        if (typeof value.x !== "undefined") { this.view.x = value.x; }
+        if (typeof value.y !== "undefined") { this.view.y = value.y; }
+
+        if (this.bounds)
+        {
+            this.checkBounds();
+        }
+    }
+
+});
+
+/**
+* The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
+* @name Phaser.Camera#width
+* @property {number} width - Gets or sets the cameras width.
+*/
+Object.defineProperty(Phaser.Camera.prototype, "width", {
+
+    get: function () {
+        return this.view.width;
+    },
+
+    set: function (value) {
+        this.view.width = value;
+    }
+
+});
+
+/**
+* The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
+* @name Phaser.Camera#height
+* @property {number} height - Gets or sets the cameras height.
+*/
+Object.defineProperty(Phaser.Camera.prototype, "height", {
+
+    get: function () {
+        return this.view.height;
+    },
+
+    set: function (value) {
+        this.view.height = value;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content
+* quickly and easily, without the need for any external files. You can create textures for sprites and in
+* coming releases we'll add dynamic sound effect generation support as well (like sfxr).
+*
+* Access this via `State.create` (or `this.create` from within a State object)
+* 
+* @class Phaser.Create
+* @constructor
+* @param {Phaser.Game} game - Game reference to the currently running game.
+ */
+Phaser.Create = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from.
+    */
+    this.bmd = game.make.bitmapData();
+
+    /**
+    * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses.
+    */
+    this.canvas = this.bmd.canvas;
+
+    /**
+    * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
+    */
+    this.ctx = this.bmd.context;
+
+    /**
+    * @property {array} palettes - A range of 16 color palettes for use with sprite generation.
+    */
+    this.palettes = [
+        { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' },
+        { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' },
+        { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' },
+        { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' },
+        { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' }
+    ];
+
+};
+
+/**
+* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm)
+* @constant
+* @type {number}
+*/
+Phaser.Create.PALETTE_ARNE = 0;
+
+/**
+* A 16 color JMP inspired palette.
+* @constant
+* @type {number}
+*/
+Phaser.Create.PALETTE_JMP = 1;
+
+/**
+* A 16 color CGA inspired palette.
+* @constant
+* @type {number}
+*/
+Phaser.Create.PALETTE_CGA = 2;
+
+/**
+* A 16 color C64 inspired palette.
+* @constant
+* @type {number}
+*/
+Phaser.Create.PALETTE_C64 = 3;
+
+/**
+* A 16 color palette inspired by Japanese computers like the MSX.
+* @constant
+* @type {number}
+*/
+Phaser.Create.PALETTE_JAPANESE_MACHINE = 4;
+
+Phaser.Create.prototype = {
+
+    /**
+     * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite.
+     *
+     * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images
+     * rather than Phaser.Graphics objects, which are expensive to render and limited in scope.
+     *
+     * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts.
+     *
+     * For example:
+     *
+     * `var data = [
+     *   ' 333 ',
+     *   ' 777 ',
+     *   'E333E',
+     *   ' 333 ',
+     *   ' 3 3 '
+     * ];`
+     *
+     * `game.create.texture('bob', data);`
+     *
+     * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it
+     * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');`
+     *
+     * @method Phaser.Create#texture
+     * @param {string} key - The key used to store this texture in the Phaser Cache.
+     * @param {array} data - An array of pixel data.
+     * @param {integer} [pixelWidth=8] - The width of each pixel.
+     * @param {integer} [pixelHeight=8] - The height of each pixel.
+     * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts.
+     * @return {PIXI.Texture} The newly generated texture.
+     */
+    texture: function (key, data, pixelWidth, pixelHeight, palette) {
+
+        if (pixelWidth === undefined) { pixelWidth = 8; }
+        if (pixelHeight === undefined) { pixelHeight = pixelWidth; }
+        if (palette === undefined) { palette = 0; }
+
+        var w = data[0].length * pixelWidth;
+        var h = data.length * pixelHeight;
+
+        this.bmd.resize(w, h);
+        this.bmd.clear();
+
+        //  Draw it
+        for (var y = 0; y < data.length; y++)
+        {
+            var row = data[y];
+
+            for (var x = 0; x < row.length; x++)
+            {
+                var d = row[x];
+
+                if (d !== '.' && d !== ' ')
+                {
+                    this.ctx.fillStyle = this.palettes[palette][d];
+                    this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight);
+                }
+            }
+        }
+
+        return this.bmd.generateTexture(key);
+
+    },
+
+    /**
+     * Creates a grid texture based on the given dimensions.
+     *
+     * @method Phaser.Create#grid
+     * @param {string} key - The key used to store this texture in the Phaser Cache.
+     * @param {integer} width - The width of the grid in pixels.
+     * @param {integer} height - The height of the grid in pixels.
+     * @param {integer} cellWidth - The width of the grid cells in pixels.
+     * @param {integer} cellHeight - The height of the grid cells in pixels.
+     * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`.
+     * @return {PIXI.Texture} The newly generated texture.
+     */
+    grid: function (key, width, height, cellWidth, cellHeight, color) {
+
+        this.bmd.resize(width, height);
+
+        this.ctx.fillStyle = color;
+
+        for (var y = 0; y < height; y += cellHeight)
+        {
+            this.ctx.fillRect(0, y, width, 1);
+        }
+
+        for (var x = 0; x < width; x += cellWidth)
+        {
+            this.ctx.fillRect(x, 0, 1, height);
+        }
+
+        return this.bmd.generateTexture(key);
+
+    }
+
+};
+
+Phaser.Create.prototype.constructor = Phaser.Create;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* This is a base State class which can be extended if you are creating your own game.
+* It provides quick access to common functions such as the camera, cache, input, match, sound and more.
+*
+* @class Phaser.State
+* @constructor
+*/
+Phaser.State = function () {
+
+    /**
+    * @property {Phaser.Game} game - This is a reference to the currently running Game.
+    */
+    this.game = null;
+
+    /**
+    * @property {string} key - The string based identifier given to the State when added into the State Manager.
+    */
+    this.key = '';
+
+    /**
+    * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World.
+    */
+    this.add = null;
+
+    /**
+    * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects.
+    */
+    this.make = null;
+
+    /**
+    * @property {Phaser.Camera} camera - A handy reference to World.camera.
+    */
+    this.camera = null;
+
+    /**
+    * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more.
+    */
+    this.cache = null;
+
+    /**
+    * @property {Phaser.Input} input - A reference to the Input Manager.
+    */
+    this.input = null;
+
+    /**
+    * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets.
+    */
+    this.load = null;
+
+    /**
+    * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions.
+    */
+    this.math = null;
+
+    /**
+    * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume.
+    */
+    this.sound = null;
+
+    /**
+    * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays.
+    */
+    this.scale = null;
+
+    /**
+    * @property {Phaser.Stage} stage - A reference to the Stage.
+    */
+    this.stage = null;
+
+    /**
+    * @property {Phaser.Time} time - A reference to the game clock and timed events system.
+    */
+    this.time = null;
+
+    /**
+    * @property {Phaser.TweenManager} tweens - A reference to the tween manager.
+    */
+    this.tweens = null;
+
+    /**
+    * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution.
+    */
+    this.world = null;
+
+    /**
+    * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created.
+    */
+    this.particles = null;
+
+    /**
+    * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser.
+    */
+    this.physics = null;
+
+    /**
+    * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator.
+    */
+    this.rnd = null;
+
+};
+
+Phaser.State.prototype = {
+
+    /**
+    * init is the very first function called when your State starts up. It's called before preload, create or anything else.
+    * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables
+    * or objects before the preloading starts.
+    *
+    * @method Phaser.State#init
+    */
+    init: function () {
+    },
+
+    /**
+    * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State)
+    * You shouldn't create any objects in this method that require assets that you're also loading in this method, as
+    * they won't yet be available.
+    *
+    * @method Phaser.State#preload
+    */
+    preload: function () {
+    },
+
+    /**
+    * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
+    *
+    * @method Phaser.State#loadUpdate
+    */
+    loadUpdate: function () {
+    },
+
+    /**
+    * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
+    * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist.
+    *
+    * @method Phaser.State#loadRender
+    */
+    loadRender: function () {
+    },
+
+    /**
+    * create is called once preload has completed, this includes the loading of any assets from the Loader.
+    * If you don't have a preload method then create is the first method called in your State.
+    *
+    * @method Phaser.State#create
+    */
+    create: function () {
+    },
+
+    /**
+    * The update method is left empty for your own use.
+    * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called.
+    * If is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called.
+    *
+    * @method Phaser.State#update
+    */
+    update: function () {
+    },
+
+    /**
+    * The preRender method is called after all Game Objects have been updated, but before any rendering takes place.
+    *
+    * @method Phaser.State#preRender
+    */
+    preRender: function () {
+    },
+
+    /**
+    * Nearly all display objects in Phaser render automatically, you don't need to tell them to render.
+    * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any
+    * final post-processing style effects here. Note that this happens before plugins postRender takes place.
+    *
+    * @method Phaser.State#render
+    */
+    render: function () {
+    },
+
+    /**
+    * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height.
+    *
+    * @method Phaser.State#resize
+    */
+    resize: function () {
+    },
+
+    /**
+    * This method will be called if the core game loop is paused.
+    *
+    * @method Phaser.State#paused
+    */
+    paused: function () {
+    },
+
+    /**
+    * This method will be called when the core game loop resumes from a paused state.
+    *
+    * @method Phaser.State#resumed
+    */
+    resumed: function () {
+    },
+
+    /**
+    * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate.
+    *
+    * @method Phaser.State#pauseUpdate
+    */
+    pauseUpdate: function () {
+    },
+
+    /**
+    * This method will be called when the State is shutdown (i.e. you switch to another state from this one).
+    *
+    * @method Phaser.State#shutdown
+    */
+    shutdown: function () {
+    }
+
+};
+
+Phaser.State.prototype.constructor = Phaser.State;
+
+/* jshint newcap: false */
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The State Manager is responsible for loading, setting up and switching game states.
+*
+* @class Phaser.StateManager
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
+*/
+Phaser.StateManager = function (game, pendingState) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {object} states - The object containing Phaser.States.
+    */
+    this.states = {};
+
+    /**
+    * @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
+    * @private
+    */
+    this._pendingState = null;
+
+    if (typeof pendingState !== 'undefined' && pendingState !== null)
+    {
+        this._pendingState = pendingState;
+    }
+
+    /**
+    * @property {boolean} _clearWorld - Clear the world when we switch state?
+    * @private
+    */
+    this._clearWorld = false;
+
+    /**
+    * @property {boolean} _clearCache - Clear the cache when we switch state?
+    * @private
+    */
+    this._clearCache = false;
+
+    /**
+    * @property {boolean} _created - Flag that sets if the State has been created or not.
+    * @private
+    */
+    this._created = false;
+
+    /**
+    * @property {any[]} _args - Temporary container when you pass vars from one State to another.
+    * @private
+    */
+    this._args = [];
+
+    /**
+    * @property {string} current - The current active State object.
+    * @default
+    */
+    this.current = '';
+
+    /**
+    * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state.
+    * 
+    * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start
+    * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states
+    * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run.
+    *
+    * The callback you specify is sent two parameters: the string based key of the new state, 
+    * and the second parameter is the string based key of the old / previous state.
+    * 
+    * @property {Phaser.Signal} onStateChange
+    */
+    this.onStateChange = new Phaser.Signal();
+
+    /**
+    * @property {function} onInitCallback - This is called when the state is set as the active state.
+    * @default
+    */
+    this.onInitCallback = null;
+
+    /**
+    * @property {function} onPreloadCallback - This is called when the state starts to load assets.
+    * @default
+    */
+    this.onPreloadCallback = null;
+
+    /**
+    * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins.
+    * @default
+    */
+    this.onCreateCallback = null;
+
+    /**
+    * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback).
+    * @default
+    */
+    this.onUpdateCallback = null;
+
+    /**
+    * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback).
+    * @default
+    */
+    this.onRenderCallback = null;
+
+    /**
+    * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height.
+    * @default
+    */
+    this.onResizeCallback = null;
+
+    /**
+    * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted.
+    * @default
+    */
+    this.onPreRenderCallback = null;
+
+    /**
+    * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase.
+    * @default
+    */
+    this.onLoadUpdateCallback = null;
+
+    /**
+    * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase.
+    * @default
+    */
+    this.onLoadRenderCallback = null;
+
+    /**
+    * @property {function} onPausedCallback - This is called when the game is paused.
+    * @default
+    */
+    this.onPausedCallback = null;
+
+    /**
+    * @property {function} onResumedCallback - This is called when the game is resumed from a paused state.
+    * @default
+    */
+    this.onResumedCallback = null;
+
+    /**
+    * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused.
+    * @default
+    */
+    this.onPauseUpdateCallback = null;
+
+    /**
+    * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state).
+    * @default
+    */
+    this.onShutDownCallback = null;
+
+};
+
+Phaser.StateManager.prototype = {
+
+    /**
+    * The Boot handler is called by Phaser.Game when it first starts up.
+    * @method Phaser.StateManager#boot
+    * @private
+    */
+    boot: function () {
+
+        this.game.onPause.add(this.pause, this);
+        this.game.onResume.add(this.resume, this);
+
+        if (this._pendingState !== null && typeof this._pendingState !== 'string')
+        {
+            this.add('default', this._pendingState, true);
+        }
+
+    },
+
+    /**
+    * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
+    * The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
+    * If a function is given a new state object will be created by calling it.
+    *
+    * @method Phaser.StateManager#add
+    * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
+    * @param {Phaser.State|object|function} state  - The state you want to switch to.
+    * @param {boolean} [autoStart=false]  - If true the State will be started immediately after adding it.
+    */
+    add: function (key, state, autoStart) {
+
+        if (autoStart === undefined) { autoStart = false; }
+
+        var newState;
+
+        if (state instanceof Phaser.State)
+        {
+            newState = state;
+        }
+        else if (typeof state === 'object')
+        {
+            newState = state;
+            newState.game = this.game;
+        }
+        else if (typeof state === 'function')
+        {
+            newState = new state(this.game);
+        }
+
+        this.states[key] = newState;
+
+        if (autoStart)
+        {
+            if (this.game.isBooted)
+            {
+                this.start(key);
+            }
+            else
+            {
+                this._pendingState = key;
+            }
+        }
+
+        return newState;
+
+    },
+
+    /**
+    * Delete the given state.
+    * @method Phaser.StateManager#remove
+    * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
+    */
+    remove: function (key) {
+
+        if (this.current === key)
+        {
+            this.callbackContext = null;
+
+            this.onInitCallback = null;
+            this.onShutDownCallback = null;
+
+            this.onPreloadCallback = null;
+            this.onLoadRenderCallback = null;
+            this.onLoadUpdateCallback = null;
+            this.onCreateCallback = null;
+            this.onUpdateCallback = null;
+            this.onPreRenderCallback = null;
+            this.onRenderCallback = null;
+            this.onResizeCallback = null;
+            this.onPausedCallback = null;
+            this.onResumedCallback = null;
+            this.onPauseUpdateCallback = null;
+        }
+
+        delete this.states[key];
+
+    },
+
+    /**
+    * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State.
+    *
+    * @method Phaser.StateManager#start
+    * @param {string} key - The key of the state you want to start.
+    * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
+    * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
+    * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
+    */
+    start: function (key, clearWorld, clearCache) {
+
+        if (clearWorld === undefined) { clearWorld = true; }
+        if (clearCache === undefined) { clearCache = false; }
+
+        if (this.checkState(key))
+        {
+            //  Place the state in the queue. It will be started the next time the game loop begins.
+            this._pendingState = key;
+            this._clearWorld = clearWorld;
+            this._clearCache = clearCache;
+
+            if (arguments.length > 3)
+            {
+                this._args = Array.prototype.splice.call(arguments, 3);
+            }
+        }
+
+    },
+
+    /**
+    * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
+    *
+    * @method Phaser.StateManager#restart
+    * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
+    * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
+    * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one.
+    */
+    restart: function (clearWorld, clearCache) {
+
+        if (clearWorld === undefined) { clearWorld = true; }
+        if (clearCache === undefined) { clearCache = false; }
+
+        //  Place the state in the queue. It will be started the next time the game loop starts.
+        this._pendingState = this.current;
+        this._clearWorld = clearWorld;
+        this._clearCache = clearCache;
+
+        if (arguments.length > 2)
+        {
+            this._args = Array.prototype.splice.call(arguments, 2);
+        }
+
+    },
+
+    /**
+    * Used by onInit and onShutdown when those functions don't exist on the state
+    * @method Phaser.StateManager#dummy
+    * @private
+    */
+    dummy: function () {
+    },
+
+    /**
+    * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
+    *
+    * @method Phaser.StateManager#preUpdate
+    */
+    preUpdate: function () {
+
+        if (this._pendingState && this.game.isBooted)
+        {
+            var previousStateKey = this.current;
+
+            //  Already got a state running?
+            this.clearCurrentState();
+
+            this.setCurrentState(this._pendingState);
+
+            this.onStateChange.dispatch(this.current, previousStateKey);
+
+            if (this.current !== this._pendingState)
+            {
+                return;
+            }
+            else
+            {
+                this._pendingState = null;
+            }
+
+            //  If StateManager.start has been called from the init of a State that ALSO has a preload, then
+            //  onPreloadCallback will be set, but must be ignored
+            if (this.onPreloadCallback)
+            {
+                this.game.load.reset(true);
+                this.onPreloadCallback.call(this.callbackContext, this.game);
+
+                //  Is the loader empty?
+                if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0)
+                {
+                    this.loadComplete();
+                }
+                else
+                {
+                    //  Start the loader going as we have something in the queue
+                    this.game.load.start();
+                }
+            }
+            else
+            {
+                //  No init? Then there was nothing to load either
+                this.loadComplete();
+            }
+        }
+
+    },
+
+    /**
+    * This method clears the current State, calling its shutdown callback. The process also removes any active tweens,
+    * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too.
+    *
+    * @method Phaser.StateManager#clearCurrentState
+    */
+    clearCurrentState: function () {
+
+        if (this.current)
+        {
+            if (this.onShutDownCallback)
+            {
+                this.onShutDownCallback.call(this.callbackContext, this.game);
+            }
+
+            this.game.tweens.removeAll();
+
+            this.game.camera.reset();
+
+            this.game.input.reset(true);
+
+            this.game.physics.clear();
+
+            this.game.time.removeAll();
+
+            this.game.scale.reset(this._clearWorld);
+
+            if (this.game.debug)
+            {
+                this.game.debug.reset();
+            }
+
+            if (this._clearWorld)
+            {
+                this.game.world.shutdown();
+
+                if (this._clearCache === true)
+                {
+                    this.game.cache.destroy();
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render.
+    *
+    * @method Phaser.StateManager#checkState
+    * @param {string} key - The key of the state you want to check.
+    * @return {boolean} true if the State has the required functions, otherwise false.
+    */
+    checkState: function (key) {
+
+        if (this.states[key])
+        {
+            var valid = false;
+
+            if (this.states[key]['preload'] || this.states[key]['create'] || this.states[key]['update'] || this.states[key]['render'])
+            {
+                valid = true;
+            }
+
+            if (valid === false)
+            {
+                console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
+                return false;
+            }
+
+            return true;
+        }
+        else
+        {
+            console.warn("Phaser.StateManager - No state found with the key: " + key);
+            return false;
+        }
+
+    },
+
+    /**
+    * Links game properties to the State given by the key.
+    *
+    * @method Phaser.StateManager#link
+    * @param {string} key - State key.
+    * @protected
+    */
+    link: function (key) {
+
+        this.states[key].game = this.game;
+        this.states[key].add = this.game.add;
+        this.states[key].make = this.game.make;
+        this.states[key].camera = this.game.camera;
+        this.states[key].cache = this.game.cache;
+        this.states[key].input = this.game.input;
+        this.states[key].load = this.game.load;
+        this.states[key].math = this.game.math;
+        this.states[key].sound = this.game.sound;
+        this.states[key].scale = this.game.scale;
+        this.states[key].state = this;
+        this.states[key].stage = this.game.stage;
+        this.states[key].time = this.game.time;
+        this.states[key].tweens = this.game.tweens;
+        this.states[key].world = this.game.world;
+        this.states[key].particles = this.game.particles;
+        this.states[key].rnd = this.game.rnd;
+        this.states[key].physics = this.game.physics;
+        this.states[key].key = key;
+
+    },
+
+    /**
+    * Nulls all State level Phaser properties, including a reference to Game.
+    *
+    * @method Phaser.StateManager#unlink
+    * @param {string} key - State key.
+    * @protected
+    */
+    unlink: function (key) {
+
+        if (this.states[key])
+        {
+            this.states[key].game = null;
+            this.states[key].add = null;
+            this.states[key].make = null;
+            this.states[key].camera = null;
+            this.states[key].cache = null;
+            this.states[key].input = null;
+            this.states[key].load = null;
+            this.states[key].math = null;
+            this.states[key].sound = null;
+            this.states[key].scale = null;
+            this.states[key].state = null;
+            this.states[key].stage = null;
+            this.states[key].time = null;
+            this.states[key].tweens = null;
+            this.states[key].world = null;
+            this.states[key].particles = null;
+            this.states[key].rnd = null;
+            this.states[key].physics = null;
+        }
+
+    },
+
+    /**
+    * Sets the current State. Should not be called directly (use StateManager.start)
+    *
+    * @method Phaser.StateManager#setCurrentState
+    * @param {string} key - State key.
+    * @private
+    */
+    setCurrentState: function (key) {
+
+        this.callbackContext = this.states[key];
+
+        this.link(key);
+
+        //  Used when the state is set as being the current active state
+        this.onInitCallback = this.states[key]['init'] || this.dummy;
+
+        this.onPreloadCallback = this.states[key]['preload'] || null;
+        this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
+        this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
+        this.onCreateCallback = this.states[key]['create'] || null;
+        this.onUpdateCallback = this.states[key]['update'] || null;
+        this.onPreRenderCallback = this.states[key]['preRender'] || null;
+        this.onRenderCallback = this.states[key]['render'] || null;
+        this.onResizeCallback = this.states[key]['resize'] || null;
+        this.onPausedCallback = this.states[key]['paused'] || null;
+        this.onResumedCallback = this.states[key]['resumed'] || null;
+        this.onPauseUpdateCallback = this.states[key]['pauseUpdate'] || null;
+
+        //  Used when the state is no longer the current active state
+        this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
+
+        //  Reset the physics system, but not on the first state start
+        if (this.current !== '')
+        {
+            this.game.physics.reset();
+        }
+
+        this.current = key;
+        this._created = false;
+
+        //  At this point key and pendingState should equal each other
+        this.onInitCallback.apply(this.callbackContext, this._args);
+
+        //  If they no longer do then the init callback hit StateManager.start
+        if (key === this._pendingState)
+        {
+            this._args = [];
+        }
+
+        this.game._kickstart = true;
+
+    },
+
+    /**
+     * Gets the current State.
+     *
+     * @method Phaser.StateManager#getCurrentState
+     * @return Phaser.State
+     * @public
+     */
+    getCurrentState: function() {
+        return this.states[this.current];
+    },
+
+    /**
+    * @method Phaser.StateManager#loadComplete
+    * @protected
+    */
+    loadComplete: function () {
+
+        if (this._created === false && this.onCreateCallback)
+        {
+            this._created = true;
+            this.onCreateCallback.call(this.callbackContext, this.game);
+        }
+        else
+        {
+            this._created = true;
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#pause
+    * @protected
+    */
+    pause: function () {
+
+        if (this._created && this.onPausedCallback)
+        {
+            this.onPausedCallback.call(this.callbackContext, this.game);
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#resume
+    * @protected
+    */
+    resume: function () {
+
+        if (this._created && this.onResumedCallback)
+        {
+            this.onResumedCallback.call(this.callbackContext, this.game);
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#update
+    * @protected
+    */
+    update: function () {
+
+        if (this._created)
+        {
+            if (this.onUpdateCallback)
+            {
+                this.onUpdateCallback.call(this.callbackContext, this.game);
+            }
+        }
+        else
+        {
+            if (this.onLoadUpdateCallback)
+            {
+                this.onLoadUpdateCallback.call(this.callbackContext, this.game);
+            }
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#pauseUpdate
+    * @protected
+    */
+    pauseUpdate: function () {
+
+        if (this._created)
+        {
+            if (this.onPauseUpdateCallback)
+            {
+                this.onPauseUpdateCallback.call(this.callbackContext, this.game);
+            }
+        }
+        else
+        {
+            if (this.onLoadUpdateCallback)
+            {
+                this.onLoadUpdateCallback.call(this.callbackContext, this.game);
+            }
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#preRender
+    * @protected
+    * @param {number} elapsedTime - The time elapsed since the last update.
+    */
+    preRender: function (elapsedTime) {
+
+        if (this._created && this.onPreRenderCallback)
+        {
+            this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime);
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#resize
+    * @protected
+    */
+    resize: function (width, height) {
+
+        if (this.onResizeCallback)
+        {
+            this.onResizeCallback.call(this.callbackContext, width, height);
+        }
+
+    },
+
+    /**
+    * @method Phaser.StateManager#render
+    * @protected
+    */
+    render: function () {
+
+        if (this._created)
+        {
+            if (this.onRenderCallback)
+            {
+                if (this.game.renderType === Phaser.CANVAS)
+                {
+                    this.game.context.save();
+                    this.game.context.setTransform(1, 0, 0, 1, 0, 0);
+                    this.onRenderCallback.call(this.callbackContext, this.game);
+                    this.game.context.restore();
+                }
+                else
+                {
+                    this.onRenderCallback.call(this.callbackContext, this.game);
+                }
+            }
+        }
+        else
+        {
+            if (this.onLoadRenderCallback)
+            {
+                this.onLoadRenderCallback.call(this.callbackContext, this.game);
+            }
+        }
+
+    },
+
+    /**
+    * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
+    * You don't recover from this without rebuilding the Phaser instance again.
+    * @method Phaser.StateManager#destroy
+    */
+    destroy: function () {
+
+        this.clearCurrentState();
+
+        this.callbackContext = null;
+
+        this.onInitCallback = null;
+        this.onShutDownCallback = null;
+
+        this.onPreloadCallback = null;
+        this.onLoadRenderCallback = null;
+        this.onLoadUpdateCallback = null;
+        this.onCreateCallback = null;
+        this.onUpdateCallback = null;
+        this.onRenderCallback = null;
+        this.onPausedCallback = null;
+        this.onResumedCallback = null;
+        this.onPauseUpdateCallback = null;
+
+        this.game = null;
+        this.states = {};
+        this._pendingState = null;
+        this.current = '';
+
+    }
+
+};
+
+Phaser.StateManager.prototype.constructor = Phaser.StateManager;
+
+/**
+* @name Phaser.StateManager#created
+* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default).
+* @readOnly
+*/
+Object.defineProperty(Phaser.StateManager.prototype, "created", {
+
+    get: function () {
+
+        return this._created;
+
+    }
+
+});
+
+/**
+* @author       Miller Medeiros http://millermedeiros.github.com/js-signals/
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Signal is an event dispatch mechansim that supports broadcasting to multiple listeners.
+*
+* Event listeners are uniquely identified by the listener/callback function and the context.
+* 
+* @class Phaser.Signal
+* @constructor
+*/
+Phaser.Signal = function () {
+};
+
+Phaser.Signal.prototype = {
+
+    /**
+    * @property {?Array.<Phaser.SignalBinding>} _bindings - Internal variable.
+    * @private
+    */
+    _bindings: null,
+
+    /**
+    * @property {any} _prevParams - Internal variable.
+    * @private
+    */
+    _prevParams: null,
+
+    /**
+    * Memorize the previously dispatched event?
+    *
+    * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}.
+    * Use {@link #forget} to clear any currently memorized event.
+    *
+    * @property {boolean} memorize
+    */
+    memorize: false,
+
+    /**
+    * @property {boolean} _shouldPropagate
+    * @private
+    */
+    _shouldPropagate: true,
+
+    /**
+    * Is the Signal active? Only active signals will broadcast dispatched events.
+    *
+    * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}.
+    *
+    * @property {boolean} active
+    * @default
+    */
+    active: true,
+
+    /**
+    * @property {function} _boundDispatch - The bound dispatch function, if any.
+    * @private
+    */
+    _boundDispatch: true,
+
+    /**
+    * @method Phaser.Signal#validateListener
+    * @param {function} listener - Signal handler function.
+    * @param {string} fnName - Function name.
+    * @private
+    */
+    validateListener: function (listener, fnName) {
+
+        if (typeof listener !== 'function')
+        {
+            throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
+        }
+
+    },
+
+    /**
+    * @method Phaser.Signal#_registerListener
+    * @private
+    * @param {function} listener - Signal handler function.
+    * @param {boolean} isOnce - Should the listener only be called once?
+    * @param {object} [listenerContext] - The context under which the listener is invoked.
+    * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
+    * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
+    */
+    _registerListener: function (listener, isOnce, listenerContext, priority, args) {
+
+        var prevIndex = this._indexOfListener(listener, listenerContext);
+        var binding;
+
+        if (prevIndex !== -1)
+        {
+            binding = this._bindings[prevIndex];
+
+            if (binding.isOnce() !== isOnce)
+            {
+                throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
+            }
+        }
+        else
+        {
+            binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args);
+            this._addBinding(binding);
+        }
+
+        if (this.memorize && this._prevParams)
+        {
+            binding.execute(this._prevParams);
+        }
+
+        return binding;
+
+    },
+
+    /**
+    * @method Phaser.Signal#_addBinding
+    * @private
+    * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
+    */
+    _addBinding: function (binding) {
+
+        if (!this._bindings)
+        {
+            this._bindings = [];
+        }
+
+        //  Simplified insertion sort
+        var n = this._bindings.length;
+
+        do {
+            n--;
+        }
+        while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
+
+        this._bindings.splice(n + 1, 0, binding);
+
+    },
+
+    /**
+    * @method Phaser.Signal#_indexOfListener
+    * @private
+    * @param {function} listener - Signal handler function.
+    * @param {object} [context=null] - Signal handler function.
+    * @return {number} The index of the listener within the private bindings array.
+    */
+    _indexOfListener: function (listener, context) {
+
+        if (!this._bindings)
+        {
+            return -1;
+        }
+
+        if (context === undefined) { context = null; }
+
+        var n = this._bindings.length;
+        var cur;
+
+        while (n--)
+        {
+            cur = this._bindings[n];
+
+            if (cur._listener === listener && cur.context === context)
+            {
+                return n;
+            }
+        }
+
+        return -1;
+
+    },
+
+    /**
+    * Check if a specific listener is attached.
+    *
+    * @method Phaser.Signal#has
+    * @param {function} listener - Signal handler function.
+    * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
+    * @return {boolean} If Signal has the specified listener.
+    */
+    has: function (listener, context) {
+
+        return this._indexOfListener(listener, context) !== -1;
+
+    },
+
+    /**
+    * Add an event listener for this signal.
+    *
+    * An event listener is a callback with a related context and priority.
+    *
+    * You can optionally provide extra arguments which will be passed to the callback after any internal parameters.
+    *
+    * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter.
+    * Any arguments you've specified after `priority` will be sent as well:
+    *
+    * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);`
+    *
+    * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`.
+    *
+    * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', 
+    * and the value 100 were the custom arguments given in the call to 'add'.
+    *
+    * @method Phaser.Signal#add
+    * @param {function} listener - The function to call when this Signal is dispatched.
+    * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
+    * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0)
+    * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
+    * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
+    */
+    add: function (listener, listenerContext, priority) {
+
+        this.validateListener(listener, 'add');
+
+        var args = [];
+
+        if (arguments.length > 3)
+        {
+            for (var i = 3; i < arguments.length; i++)
+            {
+                args.push(arguments[i]);
+            }
+        }
+
+        return this._registerListener(listener, false, listenerContext, priority, args);
+
+    },
+
+    /**
+    * Add a one-time listener - the listener is automatically removed after the first execution.
+    *
+    * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and
+    * the listener will be removed immediately.
+    *
+    * @method Phaser.Signal#addOnce
+    * @param {function} listener - The function to call when this Signal is dispatched.
+    * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
+    * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0)
+    * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
+    * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
+    */
+    addOnce: function (listener, listenerContext, priority) {
+
+        this.validateListener(listener, 'addOnce');
+
+        var args = [];
+
+        if (arguments.length > 3)
+        {
+            for (var i = 3; i < arguments.length; i++)
+            {
+                args.push(arguments[i]);
+            }
+        }
+
+        return this._registerListener(listener, true, listenerContext, priority, args);
+
+    },
+
+    /**
+    * Remove a single event listener.
+    *
+    * @method Phaser.Signal#remove
+    * @param {function} listener - Handler function that should be removed.
+    * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context).
+    * @return {function} Listener handler function.
+    */
+    remove: function (listener, context) {
+
+        this.validateListener(listener, 'remove');
+
+        var i = this._indexOfListener(listener, context);
+
+        if (i !== -1)
+        {
+            this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
+            this._bindings.splice(i, 1);
+        }
+
+        return listener;
+
+    },
+
+    /**
+    * Remove all event listeners.
+    *
+    * @method Phaser.Signal#removeAll
+    * @param {object} [context=null] - If specified only listeners for the given context will be removed.
+    */
+    removeAll: function (context) {
+
+        if (context === undefined) { context = null; }
+
+        if (!this._bindings)
+        {
+            return;
+        }
+
+        var n = this._bindings.length;
+
+        while (n--)
+        {
+            if (context)
+            {
+                if (this._bindings[n].context === context)
+                {
+                    this._bindings[n]._destroy();
+                    this._bindings.splice(n, 1);
+                }
+            }
+            else
+            {
+                this._bindings[n]._destroy();
+            }
+        }
+
+        if (!context)
+        {
+            this._bindings.length = 0;
+        }
+
+    },
+
+    /**
+    * Gets the total number of listeners attached to this Signal.
+    *
+    * @method Phaser.Signal#getNumListeners
+    * @return {integer} Number of listeners attached to the Signal.
+    */
+    getNumListeners: function () {
+
+        return this._bindings ? this._bindings.length : 0;
+
+    },
+
+    /**
+    * Stop propagation of the event, blocking the dispatch to next listener on the queue.
+    *
+    * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast.
+    * See {@link #active} to enable/disable the signal entirely.
+    *
+    * @method Phaser.Signal#halt
+    */
+    halt: function () {
+
+        this._shouldPropagate = false;
+
+    },
+
+    /**
+    * Dispatch / broadcast the event to all listeners.
+    *
+    * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}.
+    *
+    * @method Phaser.Signal#dispatch
+    * @param {any} [params] - Parameters that should be passed to each handler.
+    */
+    dispatch: function () {
+
+        if (!this.active || !this._bindings)
+        {
+            return;
+        }
+
+        var paramsArr = Array.prototype.slice.call(arguments);
+        var n = this._bindings.length;
+        var bindings;
+
+        if (this.memorize)
+        {
+            this._prevParams = paramsArr;
+        }
+
+        if (!n)
+        {
+            //  Should come after memorize
+            return;
+        }
+
+        bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
+        this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
+
+        //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
+        //reverse loop since listeners with higher priority will be added at the end of the list
+        do {
+            n--;
+        }
+        while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
+
+    },
+
+    /**
+    * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any.
+    *
+    * @method Phaser.Signal#forget
+    */
+    forget: function() {
+
+        if (this._prevParams)
+        {
+            this._prevParams = null;
+        }
+
+    },
+
+    /**
+    * Dispose the signal - no more events can be dispatched.
+    *
+    * This removes all event listeners and clears references to external objects.
+    * Calling methods on a disposed objects results in undefined behavior.
+    *
+    * @method Phaser.Signal#dispose
+    */
+    dispose: function () {
+
+        this.removeAll();
+
+        this._bindings = null;
+        if (this._prevParams)
+        {
+            this._prevParams = null;
+        }
+
+    },
+
+    /**
+    * A string representation of the object.
+    *
+    * @method Phaser.Signal#toString
+    * @return {string} String representation of the object.
+    */
+    toString: function () {
+
+        return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
+
+    }
+
+};
+
+/**
+* Create a `dispatch` function that maintains a binding to the original Signal context.
+*
+* Use the resulting value if the dispatch function needs to be passed somewhere
+* or called independently of the Signal object.
+*
+* @memberof Phaser.Signal
+* @property {function} boundDispatch
+*/
+Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", {
+
+    get: function () {
+        var _this = this;
+        return this._boundDispatch || (this._boundDispatch = function () {
+            return _this.dispatch.apply(_this, arguments);
+        });
+    }
+
+});
+
+Phaser.Signal.prototype.constructor = Phaser.Signal;
+
+/**
+* @author       Miller Medeiros http://millermedeiros.github.com/js-signals/
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Object that represents a binding between a Signal and a listener function.
+* This is an internal constructor and shouldn't be created directly.
+* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
+* 
+* @class Phaser.SignalBinding
+* @constructor
+* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
+* @param {function} listener - Handler function bound to the signal.
+* @param {boolean} isOnce - If binding should be executed just once.
+* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
+* @param {number} [priority] - The priority level of the event listener. (default = 0).
+* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
+*/
+Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) {
+
+    /**
+    * @property {Phaser.Game} _listener - Handler function bound to the signal.
+    * @private
+    */
+    this._listener = listener;
+
+    if (isOnce)
+    {
+        this._isOnce = true;
+    }
+
+    if (listenerContext != null) /* not null/undefined */
+    {
+        this.context = listenerContext;
+    }
+
+    /**
+    * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
+    * @private
+    */
+    this._signal = signal;
+
+    if (priority)
+    {
+        this._priority = priority;
+    }
+
+    if (args && args.length)
+    {
+        this._args = args;
+    }
+
+};
+
+Phaser.SignalBinding.prototype = {
+
+    /**
+    * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
+    */
+    context: null,
+
+    /**
+    * @property {boolean} _isOnce - If binding should be executed just once.
+    * @private
+    */
+    _isOnce: false,
+
+    /**
+    * @property {number} _priority - Listener priority.
+    * @private
+    */
+    _priority: 0,
+
+    /**
+    * @property {array} _args - Listener arguments.
+    * @private
+    */
+    _args: null,
+
+    /**
+    * @property {number} callCount - The number of times the handler function has been called.
+    */
+    callCount: 0,
+
+    /**
+    * If binding is active and should be executed.
+    * @property {boolean} active
+    * @default
+    */
+    active: true,
+
+    /**
+    * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
+    * @property {array|null} params
+    * @default
+    */
+    params: null,
+
+    /**
+    * Call listener passing arbitrary parameters.
+    * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.
+    * @method Phaser.SignalBinding#execute
+    * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener.
+    * @return {any} Value returned by the listener.
+    */
+    execute: function(paramsArr) {
+
+        var handlerReturn, params;
+
+        if (this.active && !!this._listener)
+        {
+            params = this.params ? this.params.concat(paramsArr) : paramsArr;
+
+            if (this._args)
+            {
+                params = params.concat(this._args);
+            }
+
+            handlerReturn = this._listener.apply(this.context, params);
+
+            this.callCount++;
+
+            if (this._isOnce)
+            {
+                this.detach();
+            }
+        }
+
+        return handlerReturn;
+
+    },
+
+    /**
+    * Detach binding from signal.
+    * alias to: @see mySignal.remove(myBinding.getListener());
+    * @method Phaser.SignalBinding#detach
+    * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
+    */
+    detach: function () {
+        return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
+    },
+
+    /**
+    * @method Phaser.SignalBinding#isBound
+    * @return {boolean} True if binding is still bound to the signal and has a listener.
+    */
+    isBound: function () {
+        return (!!this._signal && !!this._listener);
+    },
+
+    /**
+    * @method Phaser.SignalBinding#isOnce
+    * @return {boolean} If SignalBinding will only be executed once.
+    */
+    isOnce: function () {
+        return this._isOnce;
+    },
+
+    /**
+    * @method Phaser.SignalBinding#getListener
+    * @return {function} Handler function bound to the signal.
+    */
+    getListener: function () {
+        return this._listener;
+    },
+
+    /**
+    * @method Phaser.SignalBinding#getSignal
+    * @return {Phaser.Signal} Signal that listener is currently bound to.
+    */
+    getSignal: function () {
+        return this._signal;
+    },
+
+    /**
+    * Delete instance properties
+    * @method Phaser.SignalBinding#_destroy
+    * @private
+    */
+    _destroy: function () {
+        delete this._signal;
+        delete this._listener;
+        delete this.context;
+    },
+
+    /**
+    * @method Phaser.SignalBinding#toString
+    * @return {string} String representation of the object.
+    */
+    toString: function () {
+        return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
+    }
+
+};
+
+Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* This is a base Filter class to use for any Phaser filter development.
+*
+* @class Phaser.Filter
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {object} uniforms - Uniform mappings object
+* @param {Array|string} fragmentSrc - The fragment shader code. Either an array, one element per line of code, or a string.
+*/
+Phaser.Filter = function (game, uniforms, fragmentSrc) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
+    * @default
+    */
+    this.type = Phaser.WEBGL_FILTER;
+
+    /**
+    * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
+    * For example the blur filter has two passes blurX and blurY.
+    * @property {array} passes - An array of filter objects.
+    * @private
+    */
+    this.passes = [this];
+
+    /**
+    * @property {array} shaders - Array an array of shaders.
+    * @private
+    */
+    this.shaders = [];
+
+    /**
+    * @property {boolean} dirty - Internal PIXI var.
+    * @default
+    */
+    this.dirty = true;
+
+    /**
+    * @property {number} padding - Internal PIXI var.
+    * @default
+    */
+    this.padding = 0;
+
+    /**
+    * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same)
+    */
+    this.prevPoint = new Phaser.Point();
+
+    /*
+    * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D.
+    */
+
+    var d = new Date();
+
+    /**
+    * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox.
+    */
+    this.uniforms = {
+
+        resolution: { type: '2f', value: { x: 256, y: 256 }},
+        time: { type: '1f', value: 0 },
+        mouse: { type: '2f', value: { x: 0.0, y: 0.0 } },
+        date: { type: '4fv', value: [ d.getFullYear(),  d.getMonth(),  d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] },
+        sampleRate: { type: '1f', value: 44100.0 },
+        iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } },
+        iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } },
+        iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } },
+        iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } }
+
+    };
+
+    //  Copy over/replace any passed in the constructor
+    if (uniforms)
+    {
+        for (var key in uniforms)
+        {
+            this.uniforms[key] = uniforms[key];
+        }
+    }
+
+    /**
+    * @property {array|string} fragmentSrc - The fragment shader code.
+    */
+    this.fragmentSrc = fragmentSrc || '';
+
+};
+
+Phaser.Filter.prototype = {
+
+    /**
+    * Should be over-ridden.
+    * @method Phaser.Filter#init
+    */
+    init: function () {
+        //  This should be over-ridden. Will receive a variable number of arguments.
+    },
+
+    /**
+    * Set the resolution uniforms on the filter.
+    * @method Phaser.Filter#setResolution
+    * @param {number} width - The width of the display.
+    * @param {number} height - The height of the display.
+    */
+    setResolution: function (width, height) {
+
+        this.uniforms.resolution.value.x = width;
+        this.uniforms.resolution.value.y = height;
+
+    },
+
+    /**
+    * Updates the filter.
+    * @method Phaser.Filter#update
+    * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
+    */
+    update: function (pointer) {
+
+        if (typeof pointer !== 'undefined')
+        {
+            var x = pointer.x / this.game.width;
+            var y = 1 - pointer.y / this.game.height;
+
+            if (x !== this.prevPoint.x || y !== this.prevPoint.y)
+            {
+                this.uniforms.mouse.value.x = x.toFixed(2);
+                this.uniforms.mouse.value.y = y.toFixed(2);
+                this.prevPoint.set(x, y);
+            }
+        }
+
+        this.uniforms.time.value = this.game.time.totalElapsedSeconds();
+
+    },
+
+    /**
+    * Clear down this Filter and null out references
+    * @method Phaser.Filter#destroy
+    */
+    destroy: function () {
+
+        this.game = null;
+
+    }
+
+};
+
+Phaser.Filter.prototype.constructor = Phaser.Filter;
+
+/**
+* @name Phaser.Filter#width
+* @property {number} width - The width (resolution uniform)
+*/
+Object.defineProperty(Phaser.Filter.prototype, 'width', {
+
+    get: function() {
+        return this.uniforms.resolution.value.x;
+    },
+
+    set: function(value) {
+        this.uniforms.resolution.value.x = value;
+    }
+
+});
+
+/**
+* @name Phaser.Filter#height
+* @property {number} height - The height (resolution uniform)
+*/
+Object.defineProperty(Phaser.Filter.prototype, 'height', {
+
+    get: function() {
+        return this.uniforms.resolution.value.y;
+    },
+
+    set: function(value) {
+        this.uniforms.resolution.value.y = value;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* This is a base Plugin template to use for any Phaser plugin development.
+*
+* @class Phaser.Plugin
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager.
+*/
+Phaser.Plugin = function (game, parent) {
+
+    if (parent === undefined) { parent = null; }
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null.
+    */
+    this.parent = parent;
+
+    /**
+    * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
+    * @default
+    */
+    this.active = false;
+
+    /**
+    * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
+    * @default
+    */
+    this.visible = false;
+
+    /**
+    * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
+    * @default
+    */
+    this.hasPreUpdate = false;
+
+    /**
+    * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
+    * @default
+    */
+    this.hasUpdate = false;
+
+    /**
+    * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
+    * @default
+    */
+    this.hasPostUpdate = false;
+
+    /**
+    * @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
+    * @default
+    */
+    this.hasRender = false;
+
+    /**
+    * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
+    * @default
+    */
+    this.hasPostRender = false;
+
+};
+
+Phaser.Plugin.prototype = {
+
+    /**
+    * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
+    * It is only called if active is set to true.
+    * @method Phaser.Plugin#preUpdate
+    */
+    preUpdate: function () {
+    },
+
+    /**
+    * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
+    * It is only called if active is set to true.
+    * @method Phaser.Plugin#update
+    */
+    update: function () {
+    },
+
+    /**
+    * Render is called right after the Game Renderer completes, but before the State.render.
+    * It is only called if visible is set to true.
+    * @method Phaser.Plugin#render
+    */
+    render: function () {
+    },
+
+    /**
+    * Post-render is called after the Game Renderer and State.render have run.
+    * It is only called if visible is set to true.
+    * @method Phaser.Plugin#postRender
+    */
+    postRender: function () {
+    },
+
+    /**
+    * Clear down this Plugin and null out references
+    * @method Phaser.Plugin#destroy
+    */
+    destroy: function () {
+
+        this.game = null;
+        this.parent = null;
+        this.active = false;
+        this.visible = false;
+
+    }
+
+};
+
+Phaser.Plugin.prototype.constructor = Phaser.Plugin;
+
+/* jshint newcap: false */
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
+*
+* @class Phaser.PluginManager
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.PluginManager = function(game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager.
+    */
+    this.plugins = [];
+
+    /**
+    * @property {number} _len - Internal cache var.
+    * @private
+    */
+    this._len = 0;
+
+    /**
+    * @property {number} _i - Internal cache var.
+    * @private
+    */
+    this._i = 0;
+
+};
+
+Phaser.PluginManager.prototype = {
+
+    /**
+    * Add a new Plugin into the PluginManager.
+    * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager.
+    *
+    * @method Phaser.PluginManager#add
+    * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
+    * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method.
+    * @return {Phaser.Plugin} The Plugin that was added to the manager.
+    */
+    add: function (plugin) {
+
+        var args = Array.prototype.splice.call(arguments, 1);
+        var result = false;
+
+        //  Prototype?
+        if (typeof plugin === 'function')
+        {
+            plugin = new plugin(this.game, this);
+        }
+        else
+        {
+            plugin.game = this.game;
+            plugin.parent = this;
+        }
+
+        //  Check for methods now to avoid having to do this every loop
+        if (typeof plugin['preUpdate'] === 'function')
+        {
+            plugin.hasPreUpdate = true;
+            result = true;
+        }
+
+        if (typeof plugin['update'] === 'function')
+        {
+            plugin.hasUpdate = true;
+            result = true;
+        }
+
+        if (typeof plugin['postUpdate'] === 'function')
+        {
+            plugin.hasPostUpdate = true;
+            result = true;
+        }
+
+        if (typeof plugin['render'] === 'function')
+        {
+            plugin.hasRender = true;
+            result = true;
+        }
+
+        if (typeof plugin['postRender'] === 'function')
+        {
+            plugin.hasPostRender = true;
+            result = true;
+        }
+
+        //  The plugin must have at least one of the above functions to be added to the PluginManager.
+        if (result)
+        {
+            if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
+            {
+                plugin.active = true;
+            }
+
+            if (plugin.hasRender || plugin.hasPostRender)
+            {
+                plugin.visible = true;
+            }
+
+            this._len = this.plugins.push(plugin);
+
+            // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
+            if (typeof plugin['init'] === 'function')
+            {
+                plugin.init.apply(plugin, args);
+            }
+
+            return plugin;
+        }
+        else
+        {
+            return null;
+        }
+    },
+
+    /**
+    * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager.
+    *
+    * @method Phaser.PluginManager#remove
+    * @param {Phaser.Plugin} plugin - The plugin to be removed.
+    */
+    remove: function (plugin) {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            if (this.plugins[this._i] === plugin)
+            {
+                plugin.destroy();
+                this.plugins.splice(this._i, 1);
+                this._len--;
+                return;
+            }
+        }
+
+    },
+
+    /**
+    * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
+    *
+    * @method Phaser.PluginManager#removeAll
+    */
+    removeAll: function() {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            this.plugins[this._i].destroy();
+        }
+
+        this.plugins.length = 0;
+        this._len = 0;
+
+    },
+
+    /**
+    * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
+    * It only calls plugins who have active=true.
+    *
+    * @method Phaser.PluginManager#preUpdate
+    */
+    preUpdate: function () {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
+            {
+                this.plugins[this._i].preUpdate();
+            }
+        }
+
+    },
+
+    /**
+    * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
+    * It only calls plugins who have active=true.
+    *
+    * @method Phaser.PluginManager#update
+    */
+    update: function () {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
+            {
+                this.plugins[this._i].update();
+            }
+        }
+
+    },
+
+    /**
+    * PostUpdate is the last thing to be called before the world render.
+    * In particular, it is called after the world postUpdate, which means the camera has been adjusted.
+    * It only calls plugins who have active=true.
+    *
+    * @method Phaser.PluginManager#postUpdate
+    */
+    postUpdate: function () {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
+            {
+                this.plugins[this._i].postUpdate();
+            }
+        }
+
+    },
+
+    /**
+    * Render is called right after the Game Renderer completes, but before the State.render.
+    * It only calls plugins who have visible=true.
+    *
+    * @method Phaser.PluginManager#render
+    */
+    render: function () {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
+            {
+                this.plugins[this._i].render();
+            }
+        }
+
+    },
+
+    /**
+    * Post-render is called after the Game Renderer and State.render have run.
+    * It only calls plugins who have visible=true.
+    *
+    * @method Phaser.PluginManager#postRender
+    */
+    postRender: function () {
+
+        this._i = this._len;
+
+        while (this._i--)
+        {
+            if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
+            {
+                this.plugins[this._i].postRender();
+            }
+        }
+
+    },
+
+    /**
+    * Clear down this PluginManager, calls destroy on every plugin and nulls out references.
+    *
+    * @method Phaser.PluginManager#destroy
+    */
+    destroy: function () {
+
+        this.removeAll();
+
+        this.game = null;
+
+    }
+
+};
+
+Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Stage controls root level display objects upon which everything is displayed.
+* It also handles browser visibility handling and the pausing due to loss of focus.
+*
+* @class Phaser.Stage
+* @extends PIXI.Stage
+* @constructor
+* @param {Phaser.Game} game - Game reference to the currently running game.
+ */
+Phaser.Stage = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    PIXI.Stage.call(this, 0x000000);
+
+    /**
+    * @property {string} name - The name of this object.
+    * @default
+    */
+    this.name = '_stage_root';
+
+    /**
+    * @property {boolean} disableVisibilityChange - By default if the browser tab loses focus the game will pause. You can stop that behaviour by setting this property to true.
+    * @default
+    */
+    this.disableVisibilityChange = false;
+
+    /**
+    * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
+    * @default
+    */
+    this.exists = true;
+
+    /**
+    * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
+    */
+    this.currentRenderOrderID = 0;
+
+    /**
+    * @property {string} hiddenVar - The page visibility API event name.
+    * @private
+    */
+    this._hiddenVar = 'hidden';
+
+    /**
+    * @property {function} _onChange - The blur/focus event handler.
+    * @private
+    */
+    this._onChange = null;
+
+    /**
+    * @property {number} _backgroundColor - Stage background color.
+    * @private
+    */
+    this._backgroundColor = 0x000000;
+
+    if (game.config)
+    {
+        this.parseConfig(game.config);
+    }
+
+};
+
+Phaser.Stage.prototype = Object.create(PIXI.Stage.prototype);
+Phaser.Stage.prototype.constructor = Phaser.Stage;
+
+/**
+* Parses a Game configuration object.
+*
+* @method Phaser.Stage#parseConfig
+* @protected
+* @param {object} config -The configuration object to parse.
+*/
+Phaser.Stage.prototype.parseConfig = function (config) {
+
+    if (config['disableVisibilityChange'])
+    {
+        this.disableVisibilityChange = config['disableVisibilityChange'];
+    }
+
+    if (config['backgroundColor'])
+    {
+        this.backgroundColor = config['backgroundColor'];
+    }
+
+};
+
+/**
+* Initialises the stage and adds the event listeners.
+* @method Phaser.Stage#boot
+* @private
+*/
+Phaser.Stage.prototype.boot = function () {
+
+    Phaser.DOM.getOffset(this.game.canvas, this.offset);
+
+    Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
+    Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
+
+    this.checkVisibility();
+
+};
+
+/**
+* This is called automatically after the plugins preUpdate and before the State.update.
+* Most objects have preUpdate methods and it's where initial movement and positioning is done.
+*
+* @method Phaser.Stage#preUpdate
+*/
+Phaser.Stage.prototype.preUpdate = function () {
+
+    this.currentRenderOrderID = 0;
+
+    //  This can't loop in reverse, we need the orderID to be in sequence
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i].preUpdate();
+    }
+
+};
+
+/**
+* This is called automatically after the State.update, but before particles or plugins update.
+*
+* @method Phaser.Stage#update
+*/
+Phaser.Stage.prototype.update = function () {
+
+    var i = this.children.length;
+
+    while (i--)
+    {
+        this.children[i].update();
+    }
+
+};
+
+/**
+* This is called automatically before the renderer runs and after the plugins have updated.
+* In postUpdate this is where all the final physics calculatations and object positioning happens.
+* The objects are processed in the order of the display list.
+* The only exception to this is if the camera is following an object, in which case that is updated first.
+*
+* @method Phaser.Stage#postUpdate
+*/
+Phaser.Stage.prototype.postUpdate = function () {
+
+    if (this.game.world.camera.target)
+    {
+        this.game.world.camera.target.postUpdate();
+
+        this.game.world.camera.update();
+
+        var i = this.children.length;
+
+        while (i--)
+        {
+            if (this.children[i] !== this.game.world.camera.target)
+            {
+                this.children[i].postUpdate();
+            }
+        }
+    }
+    else
+    {
+        this.game.world.camera.update();
+
+        var i = this.children.length;
+
+        while (i--)
+        {
+            this.children[i].postUpdate();
+        }
+    }
+
+};
+
+/**
+* Updates the transforms for all objects on the display list.
+* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check.
+* 
+* @method Phaser.Stage#updateTransform
+*/
+Phaser.Stage.prototype.updateTransform = function () {
+
+    this.worldAlpha = 1;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i].updateTransform();
+    }
+
+};
+
+/**
+* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser.
+* Also listens for window.onblur and window.onfocus.
+* 
+* @method Phaser.Stage#checkVisibility
+*/
+Phaser.Stage.prototype.checkVisibility = function () {
+
+    if (document.webkitHidden !== undefined)
+    {
+        this._hiddenVar = 'webkitvisibilitychange';
+    }
+    else if (document.mozHidden !== undefined)
+    {
+        this._hiddenVar = 'mozvisibilitychange';
+    }
+    else if (document.msHidden !== undefined)
+    {
+        this._hiddenVar = 'msvisibilitychange';
+    }
+    else if (document.hidden !== undefined)
+    {
+        this._hiddenVar = 'visibilitychange';
+    }
+    else
+    {
+        this._hiddenVar = null;
+    }
+
+    var _this = this;
+
+    this._onChange = function (event) {
+        return _this.visibilityChange(event);
+    };
+
+    //  Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
+    if (this._hiddenVar)
+    {
+        document.addEventListener(this._hiddenVar, this._onChange, false);
+    }
+
+    window.onblur = this._onChange;
+    window.onfocus = this._onChange;
+
+    window.onpagehide = this._onChange;
+    window.onpageshow = this._onChange;
+    
+    if (this.game.device.cocoonJSApp)
+    {
+        CocoonJS.App.onSuspended.addEventListener(function () {
+            Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" });
+        });
+
+        CocoonJS.App.onActivated.addEventListener(function () {
+            Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" });
+        });
+    }
+
+};
+
+/**
+* This method is called when the document visibility is changed.
+* 
+* @method Phaser.Stage#visibilityChange
+* @param {Event} event - Its type will be used to decide whether the game should be paused or not.
+*/
+Phaser.Stage.prototype.visibilityChange = function (event) {
+
+    if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
+    {
+        if (event.type === 'pagehide' || event.type === 'blur')
+        {
+            this.game.focusLoss(event);
+        }
+        else if (event.type === 'pageshow' || event.type === 'focus')
+        {
+            this.game.focusGain(event);
+        }
+
+        return;
+    }
+
+    if (this.disableVisibilityChange)
+    {
+        return;
+    }
+
+    if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause")
+    {
+        this.game.gamePaused(event);
+    }
+    else
+    {
+        this.game.gameResumed(event);
+    }
+
+};
+
+/**
+* Sets the background color for the Stage.
+*
+* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`).
+*
+* An alpha channel is _not_ supported and will be ignored.
+*
+* @method Phaser.Stage#setBackgroundColor
+* @param {number|string} backgroundColor - The color of the background.
+*/
+Phaser.Stage.prototype.setBackgroundColor = function(backgroundColor)
+{
+    var rgb = Phaser.Color.valueToColor(backgroundColor);
+    this._backgroundColor = Phaser.Color.getColor(rgb.r, rgb.g, rgb.b);
+
+    this.backgroundColorSplit = [ rgb.r / 255, rgb.g / 255, rgb.b / 255 ];
+    this.backgroundColorString = Phaser.Color.RGBtoString(rgb.r, rgb.g, rgb.b, 255, '#');
+
+};
+
+/**
+* Destroys the Stage and removes event listeners.
+*
+* @method Phaser.Stage#destroy
+*/
+Phaser.Stage.prototype.destroy  = function () {
+
+    if (this._hiddenVar)
+    {
+        document.removeEventListener(this._hiddenVar, this._onChange, false);
+    }
+
+    window.onpagehide = null;
+    window.onpageshow = null;
+
+    window.onblur = null;
+    window.onfocus = null;
+
+};
+
+/**
+* @name Phaser.Stage#backgroundColor
+* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000'
+*/
+Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
+
+    get: function () {
+
+        return this._backgroundColor;
+
+    },
+
+    set: function (color) {
+
+        if (!this.game.transparent)
+        {
+            this.setBackgroundColor(color);
+        }
+
+    }
+
+});
+
+/**
+* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
+*
+* @name Phaser.Stage#smoothed
+* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
+*/
+Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
+
+    get: function () {
+
+        return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR;
+
+    },
+
+    set: function (value) {
+
+        if (value)
+        {
+            PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR;
+        }
+        else
+        {
+            PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
+        }
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}.
+*
+* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children.
+* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled.
+*
+* In addition, Groups provides support for fast pooling and object recycling.
+*
+* Groups are also display objects and can be nested as children within other Groups.
+* 
+* @class Phaser.Group
+* @extends PIXI.DisplayObjectContainer
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to.
+*     If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent.
+* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging.
+* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World.
+* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}.
+* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values.
+*/
+Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) {
+
+    if (addToStage === undefined) { addToStage = false; }
+    if (enableBody === undefined) { enableBody = false; }
+    if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; }
+
+    /**
+    * A reference to the currently running Game.
+    * @property {Phaser.Game} game
+    * @protected
+    */
+    this.game = game;
+
+    if (parent === undefined)
+    {
+        parent = game.world;
+    }
+
+    /**
+    * A name for this group. Not used internally but useful for debugging.
+    * @property {string} name
+    */
+    this.name = name || 'group';
+
+    /**
+    * The z-depth value of this object within its parent container/Group - the World is a Group as well.
+    * This value must be unique for each child in a Group.
+    * @property {integer} z
+    */
+    this.z = 0;
+
+    PIXI.DisplayObjectContainer.call(this);
+
+    if (addToStage)
+    {
+        this.game.stage.addChild(this);
+        this.z = this.game.stage.children.length;
+    }
+    else
+    {
+        if (parent)
+        {
+            parent.addChild(this);
+            this.z = parent.children.length;
+        }
+    }
+
+    /**
+    * Internal Phaser Type value.
+    * @property {integer} type
+    * @protected
+    */
+    this.type = Phaser.GROUP;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.GROUP;
+
+    /**
+    * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive.
+    * @property {boolean} alive
+    * @default
+    */
+    this.alive = true;
+
+    /**
+    * If exists is true the group is updated, otherwise it is skipped.
+    * @property {boolean} exists
+    * @default
+    */
+    this.exists = true;
+
+    /**
+    * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method.
+    * @property {boolean} ignoreDestroy
+    * @default
+    */
+    this.ignoreDestroy = false;
+
+    /**
+    * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method 
+    * called on the next logic update.
+    * You can set it directly to flag the Group to be destroyed on its next update.
+    * 
+    * This is extremely useful if you wish to destroy a Group from within one of its own callbacks 
+    * or a callback of one of its children.
+    * 
+    * @property {boolean} pendingDestroy
+    */
+    this.pendingDestroy = false;
+
+    /**
+    * The type of objects that will be created when using {@link #create} or {@link #createMultiple}.
+    *
+    * Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments:
+    * when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`.
+    *
+    * @property {object} classType
+    * @default {@link Phaser.Sprite}
+    */
+    this.classType = Phaser.Sprite;
+
+    /**
+    * The current display object that the group cursor is pointing to, if any. (Can be set manually.)
+    *
+    * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}.
+    * @property {?DisplayObject} cursor
+    */
+    this.cursor = null;
+
+    /**
+    * If true all Sprites created by, or added to this group, will have a physics body enabled on them.
+    *
+    * The default body type is controlled with {@link #physicsBodyType}.
+    * @property {boolean} enableBody
+    */
+    this.enableBody = enableBody;
+
+    /**
+    * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well.
+    *
+    * This only works for P2 bodies.
+    * @property {boolean} enableBodyDebug
+    * @default
+    */
+    this.enableBodyDebug = false;
+
+    /**
+    * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites.
+    *
+    * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2}, {@link Phaser.Physics.NINJA}, etc.
+    * @property {integer} physicsBodyType
+    */
+    this.physicsBodyType = physicsBodyType;
+
+    /**
+    * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property.
+    * 
+    * It should be set to one of the Phaser.Physics.Arcade sort direction constants: 
+    * 
+    * Phaser.Physics.Arcade.SORT_NONE
+    * Phaser.Physics.Arcade.LEFT_RIGHT
+    * Phaser.Physics.Arcade.RIGHT_LEFT
+    * Phaser.Physics.Arcade.TOP_BOTTOM
+    * Phaser.Physics.Arcade.BOTTOM_TOP
+    *
+    * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior.
+    * 
+    * @property {integer} physicsSortDirection
+    * @default
+    */
+    this.physicsSortDirection = null;
+
+    /**
+    * This signal is dispatched when the group is destroyed.
+    * @property {Phaser.Signal} onDestroy
+    */
+    this.onDestroy = new Phaser.Signal();
+
+    /**
+    * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next.
+    * @readOnly
+    */
+    this.cursorIndex = 0;
+
+    /**
+    * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset.
+    * 
+    * Note that the cameraOffset values are in addition to any parent in the display list.
+    * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x
+    * 
+    * @property {boolean} fixedToCamera
+    */
+    this.fixedToCamera = false;
+
+    /**
+    * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view.
+    * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled.
+    * @property {Phaser.Point} cameraOffset
+    */
+    this.cameraOffset = new Phaser.Point();
+
+    /**
+    * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash.
+    * 
+    * Only children of this Group can be added to and removed from the hash.
+    * 
+    * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting.
+    * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own
+    * sorting and filtering of Group children without touching their z-index (and therefore display draw order)
+    * 
+    * @property {array} hash
+    */
+    this.hash = [];
+
+    /**
+    * The property on which children are sorted.
+    * @property {string} _sortProperty
+    * @private
+    */
+    this._sortProperty = 'z';
+
+};
+
+Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
+Phaser.Group.prototype.constructor = Phaser.Group;
+
+/**
+* A returnType value, as specified in {@link #iterate} eg.
+* @constant
+* @type {integer}
+*/
+Phaser.Group.RETURN_NONE = 0;
+
+/**
+* A returnType value, as specified in {@link #iterate} eg.
+* @constant
+* @type {integer}
+*/
+Phaser.Group.RETURN_TOTAL = 1;
+
+/**
+* A returnType value, as specified in {@link #iterate} eg.
+* @constant
+* @type {integer}
+*/
+Phaser.Group.RETURN_CHILD = 2;
+
+/**
+* A sort ordering value, as specified in {@link #sort} eg.
+* @constant
+* @type {integer}
+*/
+Phaser.Group.SORT_ASCENDING = -1;
+
+/**
+* A sort ordering value, as specified in {@link #sort} eg.
+* @constant
+* @type {integer}
+*/
+Phaser.Group.SORT_DESCENDING = 1;
+
+/**
+* Adds an existing object as the top child in this group.
+*
+* The child is automatically added to the top of the group and is displayed on top of every previous child.
+*
+* If Group.enableBody is set then a physics body will be created on the object, so long as one does not already exist.
+*
+* Use {@link #addAt} to control where a child is added. Use {@link #create} to create and add a new child.
+*
+* @method Phaser.Group#add
+* @param {DisplayObject} child - The display object to add as a child.
+* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event.
+* @return {DisplayObject} The child that was added to the group.
+*/
+Phaser.Group.prototype.add = function (child, silent) {
+
+    if (silent === undefined) { silent = false; }
+
+    if (child.parent !== this)
+    {
+        this.addChild(child);
+
+        child.z = this.children.length;
+
+        if (this.enableBody && child.body === null)
+        {
+            this.game.physics.enable(child, this.physicsBodyType);
+        }
+        else if (child.body)
+        {
+            this.addToHash(child);
+        }
+
+        if (!silent && child.events)
+        {
+            child.events.onAddedToGroup$dispatch(child, this);
+        }
+
+        if (this.cursor === null)
+        {
+            this.cursor = child;
+        }
+    }
+
+    return child;
+
+};
+
+/**
+* Adds a child of this Group into the hash array.
+* This call will return false if the child is not a child of this Group, or is already in the hash.
+*
+* @method Phaser.Group#addToHash
+* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash.
+* @return {boolean} True if the child was successfully added to the hash, otherwise false.
+*/
+Phaser.Group.prototype.addToHash = function (child) {
+
+    if (child.parent === this)
+    {
+        var index = this.hash.indexOf(child);
+
+        if (index === -1)
+        {
+            this.hash.push(child);
+            return true;
+        }
+    }
+
+    return false;
+
+};
+
+/**
+* Removes a child of this Group from the hash array.
+* This call will return false if the child is not in the hash.
+*
+* @method Phaser.Group#removeFromHash
+* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash.
+* @return {boolean} True if the child was successfully removed from the hash, otherwise false.
+*/
+Phaser.Group.prototype.removeFromHash = function (child) {
+
+    if (child)
+    {
+        var index = this.hash.indexOf(child);
+
+        if (index !== -1)
+        {
+            this.hash.splice(index, 1);
+            return true;
+        }
+    }
+
+    return false;
+
+};
+
+/**
+* Adds an array of existing Display Objects to this Group.
+*
+* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group.
+*
+* As well as an array you can also pass another Group as the first argument. In this case all of the children from that
+* Group will be removed from it and added into this Group.
+*
+* @method Phaser.Group#addMultiple
+* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it.
+* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event.
+* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group.
+*/
+Phaser.Group.prototype.addMultiple = function (children, silent) {
+
+    if (children instanceof Phaser.Group)
+    {
+        children.moveAll(this, silent);
+    }
+    else if (Array.isArray(children))
+    {
+        for (var i = 0; i < children.length; i++)
+        {
+            this.add(children[i], silent);
+        }
+    }
+
+    return children;
+
+};
+
+/**
+* Adds an existing object to this group.
+*
+* The child is added to the group at the location specified by the index value, this allows you to control child ordering.
+*
+* @method Phaser.Group#addAt
+* @param {DisplayObject} child - The display object to add as a child.
+* @param {integer} [index=0] - The index within the group to insert the child to.
+* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event.
+* @return {DisplayObject} The child that was added to the group.
+*/
+Phaser.Group.prototype.addAt = function (child, index, silent) {
+
+    if (silent === undefined) { silent = false; }
+
+    if (child.parent !== this)
+    {
+        this.addChildAt(child, index);
+
+        this.updateZ();
+
+        if (this.enableBody && child.body === null)
+        {
+            this.game.physics.enable(child, this.physicsBodyType);
+        }
+        else if (child.body)
+        {
+            this.addToHash(child);
+        }
+
+        if (!silent && child.events)
+        {
+            child.events.onAddedToGroup$dispatch(child, this);
+        }
+
+        if (this.cursor === null)
+        {
+            this.cursor = child;
+        }
+    }
+
+    return child;
+
+};
+
+/**
+* Returns the child found at the given index within this group.
+*
+* @method Phaser.Group#getAt
+* @param {integer} index - The index to return the child from.
+* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index.
+*/
+Phaser.Group.prototype.getAt = function (index) {
+
+    if (index < 0 || index >= this.children.length)
+    {
+        return -1;
+    }
+    else
+    {
+        return this.getChildAt(index);
+    }
+
+};
+
+/**
+* Creates a new Phaser.Sprite object and adds it to the top of this group.
+*
+* Use {@link #classType} to change the type of object creaded.
+*
+* @method Phaser.Group#create
+* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point.
+* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point.
+* @param {string} key - The Game.cache key of the image that this Sprite will use.
+* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
+* @param {boolean} [exists=true] - The default exists state of the Sprite.
+* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed.
+*/
+Phaser.Group.prototype.create = function (x, y, key, frame, exists) {
+
+    if (exists === undefined) { exists = true; }
+
+    var child = new this.classType(this.game, x, y, key, frame);
+
+    child.exists = exists;
+    child.visible = exists;
+    child.alive = exists;
+
+    this.addChild(child);
+
+    child.z = this.children.length;
+
+    if (this.enableBody)
+    {
+        this.game.physics.enable(child, this.physicsBodyType, this.enableBodyDebug);
+    }
+
+    if (child.events)
+    {
+        child.events.onAddedToGroup$dispatch(child, this);
+    }
+
+    if (this.cursor === null)
+    {
+        this.cursor = child;
+    }
+
+    return child;
+
+};
+
+/**
+* Creates multiple Phaser.Sprite objects and adds them to the top of this group.
+*
+* Useful if you need to quickly generate a pool of identical sprites, such as bullets.
+*
+* By default the sprites will be set to not exist and will be positioned at 0, 0 (relative to the group.x/y).
+* Use {@link #classType} to change the type of object created.
+*
+* @method Phaser.Group#createMultiple
+* @param {integer} quantity - The number of Sprites to create.
+* @param {string} key - The Game.cache key of the image that this Sprite will use.
+* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
+* @param {boolean} [exists=false] - The default exists state of the Sprite.
+*/
+Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists) {
+
+    if (exists === undefined) { exists = false; }
+
+    for (var i = 0; i < quantity; i++)
+    {
+        this.create(0, 0, key, frame, exists);
+    }
+
+};
+
+/**
+* Internal method that re-applies all of the children's Z values.
+*
+* This must be called whenever children ordering is altered so that their `z` indices are correctly updated.
+*
+* @method Phaser.Group#updateZ
+* @protected
+*/
+Phaser.Group.prototype.updateZ = function () {
+
+    var i = this.children.length;
+
+    while (i--)
+    {
+        this.children[i].z = i;
+    }
+
+};
+
+/**
+* Sets the group cursor to the first child in the group.
+*
+* If the optional index parameter is given it sets the cursor to the object at that index instead.
+*
+* @method Phaser.Group#resetCursor
+* @param {integer} [index=0] - Set the cursor to point to a specific index.
+* @return {any} The child the cursor now points to.
+*/
+Phaser.Group.prototype.resetCursor = function (index) {
+
+    if (index === undefined) { index = 0; }
+
+    if (index > this.children.length - 1)
+    {
+        index = 0;
+    }
+
+    if (this.cursor)
+    {
+        this.cursorIndex = index;
+        this.cursor = this.children[this.cursorIndex];
+        return this.cursor;
+    }
+
+};
+
+/**
+* Advances the group cursor to the next (higher) object in the group.
+*
+* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child).
+*
+* @method Phaser.Group#next
+* @return {any} The child the cursor now points to.
+*/
+Phaser.Group.prototype.next = function () {
+
+    if (this.cursor)
+    {
+        //  Wrap the cursor?
+        if (this.cursorIndex >= this.children.length - 1)
+        {
+            this.cursorIndex = 0;
+        }
+        else
+        {
+            this.cursorIndex++;
+        }
+
+        this.cursor = this.children[this.cursorIndex];
+
+        return this.cursor;
+    }
+
+};
+
+/**
+* Moves the group cursor to the previous (lower) child in the group.
+*
+* If the cursor is at the start of the group (bottom child) it is moved to the end (top child).
+*
+* @method Phaser.Group#previous
+* @return {any} The child the cursor now points to.
+*/
+Phaser.Group.prototype.previous = function () {
+
+    if (this.cursor)
+    {
+        //  Wrap the cursor?
+        if (this.cursorIndex === 0)
+        {
+            this.cursorIndex = this.children.length - 1;
+        }
+        else
+        {
+            this.cursorIndex--;
+        }
+
+        this.cursor = this.children[this.cursorIndex];
+
+        return this.cursor;
+    }
+
+};
+
+/**
+* Swaps the position of two children in this group.
+*
+* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped.
+*
+* @method Phaser.Group#swap
+* @param {any} child1 - The first child to swap.
+* @param {any} child2 - The second child to swap.
+*/
+Phaser.Group.prototype.swap = function (child1, child2) {
+
+    this.swapChildren(child1, child2);
+    this.updateZ();
+
+};
+
+/**
+* Brings the given child to the top of this group so it renders above all other children.
+*
+* @method Phaser.Group#bringToTop
+* @param {any} child - The child to bring to the top of this group.
+* @return {any} The child that was moved.
+*/
+Phaser.Group.prototype.bringToTop = function (child) {
+
+    if (child.parent === this && this.getIndex(child) < this.children.length)
+    {
+        this.remove(child, false, true);
+        this.add(child, true);
+    }
+
+    return child;
+
+};
+
+/**
+* Sends the given child to the bottom of this group so it renders below all other children.
+*
+* @method Phaser.Group#sendToBack
+* @param {any} child - The child to send to the bottom of this group.
+* @return {any} The child that was moved.
+*/
+Phaser.Group.prototype.sendToBack = function (child) {
+
+    if (child.parent === this && this.getIndex(child) > 0)
+    {
+        this.remove(child, false, true);
+        this.addAt(child, 0, true);
+    }
+
+    return child;
+
+};
+
+/**
+* Moves the given child up one place in this group unless it's already at the top.
+*
+* @method Phaser.Group#moveUp
+* @param {any} child - The child to move up in the group.
+* @return {any} The child that was moved.
+*/
+Phaser.Group.prototype.moveUp = function (child) {
+
+    if (child.parent === this && this.getIndex(child) < this.children.length - 1)
+    {
+        var a = this.getIndex(child);
+        var b = this.getAt(a + 1);
+
+        if (b)
+        {
+            this.swap(child, b);
+        }
+    }
+
+    return child;
+
+};
+
+/**
+* Moves the given child down one place in this group unless it's already at the bottom.
+*
+* @method Phaser.Group#moveDown
+* @param {any} child - The child to move down in the group.
+* @return {any} The child that was moved.
+*/
+Phaser.Group.prototype.moveDown = function (child) {
+
+    if (child.parent === this && this.getIndex(child) > 0)
+    {
+        var a = this.getIndex(child);
+        var b = this.getAt(a - 1);
+
+        if (b)
+        {
+            this.swap(child, b);
+        }
+    }
+
+    return child;
+
+};
+
+/**
+* Positions the child found at the given index within this group to the given x and y coordinates.
+*
+* @method Phaser.Group#xy
+* @param {integer} index - The index of the child in the group to set the position of.
+* @param {number} x - The new x position of the child.
+* @param {number} y - The new y position of the child.
+*/
+Phaser.Group.prototype.xy = function (index, x, y) {
+
+    if (index < 0 || index > this.children.length)
+    {
+        return -1;
+    }
+    else
+    {
+        this.getChildAt(index).x = x;
+        this.getChildAt(index).y = y;
+    }
+
+};
+
+/**
+* Reverses all children in this group.
+*
+* This operaation applies only to immediate children and does not propagate to subgroups.
+*
+* @method Phaser.Group#reverse
+*/
+Phaser.Group.prototype.reverse = function () {
+
+    this.children.reverse();
+    this.updateZ();
+
+};
+
+/**
+* Get the index position of the given child in this group, which should match the child's `z` property.
+*
+* @method Phaser.Group#getIndex
+* @param {any} child - The child to get the index for.
+* @return {integer} The index of the child or -1 if it's not a member of this group.
+*/
+Phaser.Group.prototype.getIndex = function (child) {
+
+    return this.children.indexOf(child);
+
+};
+
+/**
+* Replaces a child of this group with the given newChild. The newChild cannot be a member of this group.
+*
+* @method Phaser.Group#replace
+* @param {any} oldChild - The child in this group that will be replaced.
+* @param {any} newChild - The child to be inserted into this group.
+* @return {any} Returns the oldChild that was replaced within this group.
+*/
+Phaser.Group.prototype.replace = function (oldChild, newChild) {
+
+    var index = this.getIndex(oldChild);
+
+    if (index !== -1)
+    {
+        if (newChild.parent)
+        {
+            if (newChild.parent instanceof Phaser.Group)
+            {
+                newChild.parent.remove(newChild);
+            }
+            else
+            {
+                newChild.parent.removeChild(newChild);
+            }
+        }
+
+        this.remove(oldChild);
+
+        this.addAt(newChild, index);
+
+        return oldChild;
+    }
+
+};
+
+/**
+* Checks if the child has the given property.
+*
+* Will scan up to 4 levels deep only.
+*
+* @method Phaser.Group#hasProperty
+* @param {any} child - The child to check for the existance of the property on.
+* @param {string[]} key - An array of strings that make up the property.
+* @return {boolean} True if the child has the property, otherwise false.
+*/
+Phaser.Group.prototype.hasProperty = function (child, key) {
+
+    var len = key.length;
+
+    if (len === 1 && key[0] in child)
+    {
+        return true;
+    }
+    else if (len === 2 && key[0] in child && key[1] in child[key[0]])
+    {
+        return true;
+    }
+    else if (len === 3 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]])
+    {
+        return true;
+    }
+    else if (len === 4 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]] && key[3] in child[key[0]][key[1]][key[2]])
+    {
+        return true;
+    }
+
+    return false;
+
+};
+
+/**
+* Sets a property to the given value on the child. The operation parameter controls how the value is set.
+*
+* The operations are:
+* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed
+* - 1: will add the given value to the value already present.
+* - 2: will subtract the given value from the value already present.
+* - 3: will multiply the value already present by the given value.
+* - 4: will divide the value already present by the given value.
+*
+* @method Phaser.Group#setProperty
+* @param {any} child - The child to set the property value on.
+* @param {array} key - An array of strings that make up the property that will be set.
+* @param {any} value - The value that will be set.
+* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
+* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
+* @return {boolean} True if the property was set, false if not.
+*/
+Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) {
+
+    if (force === undefined) { force = false; }
+
+    operation = operation || 0;
+
+    //  As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration.
+
+    //  0 = Equals
+    //  1 = Add
+    //  2 = Subtract
+    //  3 = Multiply
+    //  4 = Divide
+
+    //  We can't force a property in and the child doesn't have it, so abort.
+    //  Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too.
+    if (!this.hasProperty(child, key) && (!force || operation > 0))
+    {
+        return false;
+    }
+
+    var len = key.length;
+
+    if (len === 1)
+    {
+        if (operation === 0) { child[key[0]] = value; }
+        else if (operation == 1) { child[key[0]] += value; }
+        else if (operation == 2) { child[key[0]] -= value; }
+        else if (operation == 3) { child[key[0]] *= value; }
+        else if (operation == 4) { child[key[0]] /= value; }
+    }
+    else if (len === 2)
+    {
+        if (operation === 0) { child[key[0]][key[1]] = value; }
+        else if (operation == 1) { child[key[0]][key[1]] += value; }
+        else if (operation == 2) { child[key[0]][key[1]] -= value; }
+        else if (operation == 3) { child[key[0]][key[1]] *= value; }
+        else if (operation == 4) { child[key[0]][key[1]] /= value; }
+    }
+    else if (len === 3)
+    {
+        if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
+        else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; }
+        else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; }
+        else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; }
+        else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; }
+    }
+    else if (len === 4)
+    {
+        if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
+        else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
+        else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
+        else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
+        else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
+    }
+
+    return true;
+
+};
+
+/**
+* Checks a property for the given value on the child.
+*
+* @method Phaser.Group#checkProperty
+* @param {any} child - The child to check the property value on.
+* @param {array} key - An array of strings that make up the property that will be set.
+* @param {any} value - The value that will be checked.
+* @param {boolean} [force=false] - If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned.
+* @return {boolean} True if the property was was equal to value, false if not.
+*/
+Phaser.Group.prototype.checkProperty = function (child, key, value, force) {
+
+    if (force === undefined) { force = false; }
+
+    //  We can't force a property in and the child doesn't have it, so abort.
+    if (!Phaser.Utils.getProperty(child, key) && force)
+    {
+        return false;
+    }
+
+    if (Phaser.Utils.getProperty(child, key) !== value)
+    {
+        return false;
+    }
+
+    return true;
+
+};
+
+/**
+* Quickly set a property on a single child of this group to a new value.
+*
+* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
+*
+* @method Phaser.Group#set
+* @param {Phaser.Sprite} child - The child to set the property on.
+* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
+* @param {any} value - The value that will be set.
+* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true.
+* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true.
+* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
+* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
+* @return {boolean} True if the property was set, false if not.
+*/
+Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) {
+
+    if (force === undefined) { force = false; }
+
+    key = key.split('.');
+
+    if (checkAlive === undefined) { checkAlive = false; }
+    if (checkVisible === undefined) { checkVisible = false; }
+
+    if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible)))
+    {
+        return this.setProperty(child, key, value, operation, force);
+    }
+
+};
+
+/**
+* Quickly set the same property across all children of this group to a new value.
+*
+* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children.
+* If you need that ability please see `Group.setAllChildren`.
+*
+* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
+*
+* @method Phaser.Group#setAll
+* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
+* @param {any} value - The value that will be set.
+* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
+* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
+* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
+* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
+*/
+Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) {
+
+    if (checkAlive === undefined) { checkAlive = false; }
+    if (checkVisible === undefined) { checkVisible = false; }
+    if (force === undefined) { force = false; }
+
+    key = key.split('.');
+    operation = operation || 0;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
+        {
+            this.setProperty(this.children[i], key, value, operation, force);
+        }
+    }
+
+};
+
+/**
+* Quickly set the same property across all children of this group, and any child Groups, to a new value.
+*
+* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom.
+* Unlike with `setAll` the property is NOT set on child Groups itself.
+*
+* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
+*
+* @method Phaser.Group#setAllChildren
+* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
+* @param {any} value - The value that will be set.
+* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
+* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
+* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
+* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
+*/
+Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) {
+
+    if (checkAlive === undefined) { checkAlive = false; }
+    if (checkVisible === undefined) { checkVisible = false; }
+    if (force === undefined) { force = false; }
+
+    operation = operation || 0;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
+        {
+            if (this.children[i] instanceof Phaser.Group)
+            {
+                this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force);
+            }
+            else
+            {
+                this.setProperty(this.children[i], key.split('.'), value, operation, force);
+            }
+        }
+    }
+
+};
+
+/**
+* Quickly check that the same property across all children of this group is equal to the given value.
+*
+* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children.
+*
+* @method Phaser.Group#checkAll
+* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
+* @param {any} value - The value that will be checked.
+* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children.
+* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children.
+* @param {boolean} [force=false] - If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned.
+*/
+Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) {
+
+    if (checkAlive === undefined) { checkAlive = false; }
+    if (checkVisible === undefined) { checkVisible = false; }
+    if (force === undefined) { force = false; }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
+        {
+            if (!this.checkProperty(this.children[i], key, value, force))
+            {
+                return false;
+            }
+        }
+    }
+
+    return true;
+
+};
+
+/**
+* Adds the amount to the given property on all children in this group.
+*
+* `Group.addAll('x', 10)` will add 10 to the child.x value for each child.
+*
+* @method Phaser.Group#addAll
+* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
+* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
+* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
+* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
+*/
+Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {
+
+    this.setAll(property, amount, checkAlive, checkVisible, 1);
+
+};
+
+/**
+* Subtracts the amount from the given property on all children in this group.
+*
+* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child.
+*
+* @method Phaser.Group#subAll
+* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
+* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
+* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
+* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
+*/
+Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) {
+
+    this.setAll(property, amount, checkAlive, checkVisible, 2);
+
+};
+
+/**
+* Multiplies the given property by the amount on all children in this group.
+*
+* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child.
+*
+* @method Phaser.Group#multiplyAll
+* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
+* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
+* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
+* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
+*/
+Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) {
+
+    this.setAll(property, amount, checkAlive, checkVisible, 3);
+
+};
+
+/**
+* Divides the given property by the amount on all children in this group.
+*
+* `Group.divideAll('x', 2)` will half the child.x value for each child.
+*
+* @method Phaser.Group#divideAll
+* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
+* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
+* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
+* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
+*/
+Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) {
+
+    this.setAll(property, amount, checkAlive, checkVisible, 4);
+
+};
+
+/**
+* Calls a function, specified by name, on all children in the group who exist (or do not exist).
+*
+* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
+*
+* @method Phaser.Group#callAllExists
+* @param {string} callback - Name of the function on the children to call.
+* @param {boolean} existsValue - Only children with exists=existsValue will be called.
+* @param {...any} parameter - Additional parameters that will be passed to the callback.
+*/
+Phaser.Group.prototype.callAllExists = function (callback, existsValue) {
+
+    var args;
+
+    if (arguments.length > 2)
+    {
+        args = [];
+
+        for (var i = 2; i < arguments.length; i++)
+        {
+            args.push(arguments[i]);
+        }
+    }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        if (this.children[i].exists === existsValue && this.children[i][callback])
+        {
+            this.children[i][callback].apply(this.children[i], args);
+        }
+    }
+
+};
+
+/**
+* Returns a reference to a function that exists on a child of the group based on the given callback array.
+*
+* @method Phaser.Group#callbackFromArray
+* @param {object} child - The object to inspect.
+* @param {array} callback - The array of function names.
+* @param {integer} length - The size of the array (pre-calculated in callAll).
+* @protected
+*/
+Phaser.Group.prototype.callbackFromArray = function (child, callback, length) {
+
+    //  Kinda looks like a Christmas tree
+
+    if (length == 1)
+    {
+        if (child[callback[0]])
+        {
+            return child[callback[0]];
+        }
+    }
+    else if (length == 2)
+    {
+        if (child[callback[0]][callback[1]])
+        {
+            return child[callback[0]][callback[1]];
+        }
+    }
+    else if (length == 3)
+    {
+        if (child[callback[0]][callback[1]][callback[2]])
+        {
+            return child[callback[0]][callback[1]][callback[2]];
+        }
+    }
+    else if (length == 4)
+    {
+        if (child[callback[0]][callback[1]][callback[2]][callback[3]])
+        {
+            return child[callback[0]][callback[1]][callback[2]][callback[3]];
+        }
+    }
+    else
+    {
+        if (child[callback])
+        {
+            return child[callback];
+        }
+    }
+
+    return false;
+
+};
+
+/**
+* Calls a function, specified by name, on all on children.
+*
+* The function is called for all children regardless if they are dead or alive (see callAllExists for different options).
+* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
+*
+* @method Phaser.Group#callAll
+* @param {string} method - Name of the function on the child to call. Deep property lookup is supported.
+* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child.
+* @param {...any} args - Additional parameters that will be passed to the method.
+*/
+Phaser.Group.prototype.callAll = function (method, context) {
+
+    if (method === undefined)
+    {
+        return;
+    }
+
+    //  Extract the method into an array
+    method = method.split('.');
+
+    var methodLength = method.length;
+
+    if (context === undefined || context === null || context === '')
+    {
+        context = null;
+    }
+    else
+    {
+        //  Extract the context into an array
+        if (typeof context === 'string')
+        {
+            context = context.split('.');
+            var contextLength = context.length;
+        }
+    }
+
+    var args;
+
+    if (arguments.length > 2)
+    {
+        args = [];
+
+        for (var i = 2; i < arguments.length; i++)
+        {
+            args.push(arguments[i]);
+        }
+    }
+
+    var callback = null;
+    var callbackContext = null;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        callback = this.callbackFromArray(this.children[i], method, methodLength);
+
+        if (context && callback)
+        {
+            callbackContext = this.callbackFromArray(this.children[i], context, contextLength);
+
+            if (callback)
+            {
+                callback.apply(callbackContext, args);
+            }
+        }
+        else if (callback)
+        {
+            callback.apply(this.children[i], args);
+        }
+    }
+
+};
+
+/**
+* The core preUpdate - as called by World.
+* @method Phaser.Group#preUpdate
+* @protected
+*/
+Phaser.Group.prototype.preUpdate = function () {
+
+    if (this.pendingDestroy)
+    {
+        this.destroy();
+        return false;
+    }
+
+    if (!this.exists || !this.parent.exists)
+    {
+        this.renderOrderID = -1;
+        return false;
+    }
+
+    var i = this.children.length;
+
+    while (i--)
+    {
+        this.children[i].preUpdate();
+    }
+
+    return true;
+
+};
+
+/**
+* The core update - as called by World.
+* @method Phaser.Group#update
+* @protected
+*/
+Phaser.Group.prototype.update = function () {
+
+    var i = this.children.length;
+
+    while (i--)
+    {
+        this.children[i].update();
+    }
+
+};
+
+/**
+* The core postUpdate - as called by World.
+* @method Phaser.Group#postUpdate
+* @protected
+*/
+Phaser.Group.prototype.postUpdate = function () {
+
+    //  Fixed to Camera?
+    if (this.fixedToCamera)
+    {
+        this.x = this.game.camera.view.x + this.cameraOffset.x;
+        this.y = this.game.camera.view.y + this.cameraOffset.y;
+    }
+
+    var i = this.children.length;
+
+    while (i--)
+    {
+        this.children[i].postUpdate();
+    }
+
+};
+
+
+/**
+* Find children matching a certain predicate.
+*
+* For example:
+*
+*     var healthyList = Group.filter(function(child, index, children) {
+*         return child.health > 10 ? true : false;
+*     }, true);
+*     healthyList.callAll('attack');
+*
+* Note: Currently this will skip any children which are Groups themselves.
+*
+* @method Phaser.Group#filter
+* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third
+* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate.
+* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for
+*/
+Phaser.Group.prototype.filter = function (predicate, checkExists) {
+
+    var index = -1;
+    var length = this.children.length;
+    var results = [];
+
+    while (++index < length)
+    {
+        var child = this.children[index];
+
+        if (!checkExists || (checkExists && child.exists))
+        {
+            if (predicate(child, index, this.children))
+            {
+                results.push(child);
+            }
+        }
+    }
+
+    return new Phaser.ArraySet(results);
+
+};
+
+/**
+* Call a function on each child in this group.
+*
+* Additional arguments for the callback can be specified after the `checkExists` parameter. For example,
+*
+*     Group.forEach(awardBonusGold, this, true, 100, 500)
+*
+* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`.
+*
+* Note: This check will skip any children which are Groups themselves.
+*
+* @method Phaser.Group#forEach
+* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
+* @param {object} callbackContext - The context in which the function should be called (usually 'this').
+* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed.
+* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
+*/
+Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) {
+
+    if (checkExists === undefined) { checkExists = false; }
+
+    if (arguments.length <= 3)
+    {
+        for (var i = 0; i < this.children.length; i++)
+        {
+            if (!checkExists || (checkExists && this.children[i].exists))
+            {
+                callback.call(callbackContext, this.children[i]);
+            }
+        }
+    }
+    else
+    {
+        // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE.
+        // Using an array and pushing each element (not a slice!) is _significantly_ faster.
+        var args = [null];
+
+        for (var i = 3; i < arguments.length; i++)
+        {
+            args.push(arguments[i]);
+        }
+
+        for (var i = 0; i < this.children.length; i++)
+        {
+            if (!checkExists || (checkExists && this.children[i].exists))
+            {
+                args[0] = this.children[i];
+                callback.apply(callbackContext, args);
+            }
+        }
+    }
+
+};
+
+/**
+* Call a function on each existing child in this group.
+*
+* See {@link Phaser.Group#forEach forEach} for details.
+*
+* @method Phaser.Group#forEachExists
+* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
+* @param {object} callbackContext - The context in which the function should be called (usually 'this').
+* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
+*/
+Phaser.Group.prototype.forEachExists = function (callback, callbackContext) {
+
+    var args;
+
+    if (arguments.length > 2)
+    {
+        args = [null];
+
+        for (var i = 2; i < arguments.length; i++)
+        {
+            args.push(arguments[i]);
+        }
+    }
+
+    this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
+
+};
+
+/**
+* Call a function on each alive child in this group.
+*
+* See {@link Phaser.Group#forEach forEach} for details.
+*
+* @method Phaser.Group#forEachAlive
+* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
+* @param {object} callbackContext - The context in which the function should be called (usually 'this').
+* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
+*/
+Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) {
+
+    var args;
+
+    if (arguments.length > 2)
+    {
+        args = [null];
+
+        for (var i = 2; i < arguments.length; i++)
+        {
+            args.push(arguments[i]);
+        }
+    }
+
+    this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
+
+};
+
+/**
+* Call a function on each dead child in this group.
+*
+* See {@link Phaser.Group#forEach forEach} for details.
+*
+* @method Phaser.Group#forEachDead
+* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
+* @param {object} callbackContext - The context in which the function should be called (usually 'this').
+* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
+*/
+Phaser.Group.prototype.forEachDead = function (callback, callbackContext) {
+
+    var args;
+
+    if (arguments.length > 2)
+    {
+        args = [null];
+
+        for (var i = 2; i < arguments.length; i++)
+        {
+            args.push(arguments[i]);
+        }
+    }
+
+    this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
+
+};
+
+/**
+* Sort the children in the group according to a particular key and ordering.
+*
+* Call this function to sort the group according to a particular key value and order.
+* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`.
+*
+* @method Phaser.Group#sort
+* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value.
+* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}).
+*/
+Phaser.Group.prototype.sort = function (key, order) {
+
+    if (this.children.length < 2)
+    {
+        //  Nothing to swap
+        return;
+    }
+
+    if (key === undefined) { key = 'z'; }
+    if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; }
+
+    this._sortProperty = key;
+
+    if (order === Phaser.Group.SORT_ASCENDING)
+    {
+        this.children.sort(this.ascendingSortHandler.bind(this));
+    }
+    else
+    {
+        this.children.sort(this.descendingSortHandler.bind(this));
+    }
+
+    this.updateZ();
+
+};
+
+/**
+* Sort the children in the group according to custom sort function.
+*
+* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b).
+* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`.
+*
+* @method Phaser.Group#customSort
+* @param {function} sortHandler - The custom sort function.
+* @param {object} [context=undefined] - The context in which the sortHandler is called.
+*/
+Phaser.Group.prototype.customSort = function (sortHandler, context) {
+
+    if (this.children.length < 2)
+    {
+        //  Nothing to swap
+        return;
+    }
+
+    this.children.sort(sortHandler.bind(context));
+
+    this.updateZ();
+
+};
+
+/**
+* An internal helper function for the sort process.
+*
+* @method Phaser.Group#ascendingSortHandler
+* @protected
+* @param {object} a - The first object being sorted.
+* @param {object} b - The second object being sorted.
+*/
+Phaser.Group.prototype.ascendingSortHandler = function (a, b) {
+
+    if (a[this._sortProperty] < b[this._sortProperty])
+    {
+        return -1;
+    }
+    else if (a[this._sortProperty] > b[this._sortProperty])
+    {
+        return 1;
+    }
+    else
+    {
+        if (a.z < b.z)
+        {
+            return -1;
+        }
+        else
+        {
+            return 1;
+        }
+    }
+
+};
+
+/**
+* An internal helper function for the sort process.
+*
+* @method Phaser.Group#descendingSortHandler
+* @protected
+* @param {object} a - The first object being sorted.
+* @param {object} b - The second object being sorted.
+*/
+Phaser.Group.prototype.descendingSortHandler = function (a, b) {
+
+    if (a[this._sortProperty] < b[this._sortProperty])
+    {
+        return 1;
+    }
+    else if (a[this._sortProperty] > b[this._sortProperty])
+    {
+        return -1;
+    }
+    else
+    {
+        return 0;
+    }
+
+};
+
+/**
+* Iterates over the children of the group performing one of several actions for matched children.
+*
+* A child is considered a match when it has a property, named `key`, whose value is equal to `value`
+* according to a strict equality comparison.
+*
+* The result depends on the `returnType`:
+*
+* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}:
+*     The callback, if any, is applied to all matching children. The number of matched children is returned.
+* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}:
+*     The callback, if any, is applied to all matching children. No value is returned.
+* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}:
+*     The callback, if any, is applied to the *first* matching child and the *first* matched child is returned.
+*     If there is no matching child then null is returned.
+*
+* If `args` is specified it must be an array. The matched child will be assigned to the first
+* element and the entire array will be applied to the callback function.
+*
+* @method Phaser.Group#iterate
+* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
+* @param {any} value - A child matches if `child[key] === value` is true.
+* @param {integer} returnType - How to iterate the children and what to return.
+* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument.
+* @param {object} [callbackContext] - The context in which the function should be called (usually 'this').
+* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child.
+* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null.
+*/
+Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) {
+
+    if (returnType === Phaser.Group.RETURN_TOTAL && this.children.length === 0)
+    {
+        return 0;
+    }
+
+    var total = 0;
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        if (this.children[i][key] === value)
+        {
+            total++;
+
+            if (callback)
+            {
+                if (args)
+                {
+                    args[0] = this.children[i];
+                    callback.apply(callbackContext, args);
+                }
+                else
+                {
+                    callback.call(callbackContext, this.children[i]);
+                }
+            }
+
+            if (returnType === Phaser.Group.RETURN_CHILD)
+            {
+                return this.children[i];
+            }
+        }
+    }
+
+    if (returnType === Phaser.Group.RETURN_TOTAL)
+    {
+        return total;
+    }
+
+    // RETURN_CHILD or RETURN_NONE
+    return null;
+
+};
+
+/**
+* Get the first display object that exists, or doesn't exist.
+*
+* @method Phaser.Group#getFirstExists
+* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child.
+* @return {any} The first child, or null if none found.
+*/
+Phaser.Group.prototype.getFirstExists = function (exists) {
+
+    if (typeof exists !== 'boolean')
+    {
+        exists = true;
+    }
+
+    return this.iterate('exists', exists, Phaser.Group.RETURN_CHILD);
+
+};
+
+/**
+* Get the first child that is alive (`child.alive === true`).
+*
+* This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
+*
+* @method Phaser.Group#getFirstAlive
+* @return {any} The first alive child, or null if none found.
+*/
+Phaser.Group.prototype.getFirstAlive = function () {
+
+    return this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
+
+};
+
+/**
+* Get the first child that is dead (`child.alive === false`).
+*
+* This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
+*
+* @method Phaser.Group#getFirstDead
+* @return {any} The first dead child, or null if none found.
+*/
+Phaser.Group.prototype.getFirstDead = function () {
+
+    return this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
+
+};
+
+/**
+* Return the child at the top of this group.
+*
+* The top child is the child displayed (rendered) above every other child.
+*
+* @method Phaser.Group#getTop
+* @return {any} The child at the top of the Group.
+*/
+Phaser.Group.prototype.getTop = function () {
+
+    if (this.children.length > 0)
+    {
+        return this.children[this.children.length - 1];
+    }
+
+};
+
+/**
+* Returns the child at the bottom of this group.
+*
+* The bottom child the child being displayed (rendered) below every other child.
+*
+* @method Phaser.Group#getBottom
+* @return {any} The child at the bottom of the Group.
+*/
+Phaser.Group.prototype.getBottom = function () {
+
+    if (this.children.length > 0)
+    {
+        return this.children[0];
+    }
+
+};
+
+/**
+* Get the number of living children in this group.
+*
+* @method Phaser.Group#countLiving
+* @return {integer} The number of children flagged as alive.
+*/
+Phaser.Group.prototype.countLiving = function () {
+
+    return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
+
+};
+
+/**
+* Get the number of dead children in this group.
+*
+* @method Phaser.Group#countDead
+* @return {integer} The number of children flagged as dead.
+*/
+Phaser.Group.prototype.countDead = function () {
+
+    return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
+
+};
+
+/**
+* Returns a random child from the group.
+*
+* @method Phaser.Group#getRandom
+* @param {integer} [startIndex=0] - Offset from the front of the front of the group (lowest child).
+* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from.
+* @return {any} A random child of this Group.
+*/
+Phaser.Group.prototype.getRandom = function (startIndex, length) {
+
+    if (this.children.length === 0)
+    {
+        return null;
+    }
+
+    startIndex = startIndex || 0;
+    length = length || this.children.length;
+
+    return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length);
+
+};
+
+/**
+* Removes the given child from this group.
+*
+* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child.
+*
+* If the group cursor was referring to the removed child it is updated to refer to the next child.
+*
+* @method Phaser.Group#remove
+* @param {any} child - The child to remove.
+* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child.
+* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event.
+* @return {boolean} true if the child was removed from this group, otherwise false.
+*/
+Phaser.Group.prototype.remove = function (child, destroy, silent) {
+
+    if (destroy === undefined) { destroy = false; }
+    if (silent === undefined) { silent = false; }
+
+    if (this.children.length === 0 || this.children.indexOf(child) === -1)
+    {
+        return false;
+    }
+
+    if (!silent && child.events && !child.destroyPhase)
+    {
+        child.events.onRemovedFromGroup$dispatch(child, this);
+    }
+
+    var removed = this.removeChild(child);
+
+    this.removeFromHash(child);
+
+    this.updateZ();
+
+    if (this.cursor === child)
+    {
+        this.next();
+    }
+
+    if (destroy && removed)
+    {
+        removed.destroy(true);
+    }
+
+    return true;
+
+};
+
+/**
+* Moves all children from this Group to the Group given.
+*
+* @method Phaser.Group#moveAll
+* @param {Phaser.Group} group - The new Group to which the children will be moved to.
+* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group.
+* @return {Phaser.Group} The Group to which all the children were moved.
+*/
+Phaser.Group.prototype.moveAll = function (group, silent) {
+
+    if (silent === undefined) { silent = false; }
+
+    if (this.children.length > 0 && group instanceof Phaser.Group)
+    {
+        do
+        {
+            group.add(this.children[0], silent);
+        }
+        while (this.children.length > 0);
+
+        this.hash = [];
+
+        this.cursor = null;
+    }
+
+    return group;
+
+};
+
+/**
+* Removes all children from this group, but does not remove the group from its parent.
+*
+* @method Phaser.Group#removeAll
+* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child.
+* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events.
+*/
+Phaser.Group.prototype.removeAll = function (destroy, silent) {
+
+    if (destroy === undefined) { destroy = false; }
+    if (silent === undefined) { silent = false; }
+
+    if (this.children.length === 0)
+    {
+        return;
+    }
+
+    do
+    {
+        if (!silent && this.children[0].events)
+        {
+            this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this);
+        }
+
+        var removed = this.removeChild(this.children[0]);
+
+        this.removeFromHash(removed);
+
+        if (destroy && removed)
+        {
+            removed.destroy(true);
+        }
+    }
+    while (this.children.length > 0);
+
+    this.hash = [];
+
+    this.cursor = null;
+
+};
+
+/**
+* Removes all children from this group whose index falls beteen the given startIndex and endIndex values.
+*
+* @method Phaser.Group#removeBetween
+* @param {integer} startIndex - The index to start removing children from.
+* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group.
+* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child.
+* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events.
+*/
+Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) {
+
+    if (endIndex === undefined) { endIndex = this.children.length - 1; }
+    if (destroy === undefined) { destroy = false; }
+    if (silent === undefined) { silent = false; }
+
+    if (this.children.length === 0)
+    {
+        return;
+    }
+
+    if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
+    {
+        return false;
+    }
+
+    var i = endIndex;
+
+    while (i >= startIndex)
+    {
+        if (!silent && this.children[i].events)
+        {
+            this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this);
+        }
+
+        var removed = this.removeChild(this.children[i]);
+
+        this.removeFromHash(removed);
+
+        if (destroy && removed)
+        {
+            removed.destroy(true);
+        }
+
+        if (this.cursor === this.children[i])
+        {
+            this.cursor = null;
+        }
+
+        i--;
+    }
+
+    this.updateZ();
+
+};
+
+/**
+* Destroys this group.
+*
+* Removes all children, then removes this group from its parent and nulls references.
+*
+* @method Phaser.Group#destroy
+* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child.
+* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does.
+*/
+Phaser.Group.prototype.destroy = function (destroyChildren, soft) {
+
+    if (this.game === null || this.ignoreDestroy) { return; }
+
+    if (destroyChildren === undefined) { destroyChildren = true; }
+    if (soft === undefined) { soft = false; }
+
+    this.onDestroy.dispatch(this, destroyChildren, soft);
+
+    this.removeAll(destroyChildren);
+
+    this.cursor = null;
+    this.filters = null;
+    this.pendingDestroy = false;
+
+    if (!soft)
+    {
+        if (this.parent)
+        {
+            this.parent.removeChild(this);
+        }
+
+        this.game = null;
+        this.exists = false;
+    }
+
+};
+
+/**
+* Total number of existing children in the group.
+*
+* @name Phaser.Group#total
+* @property {integer} total
+* @readonly
+*/
+Object.defineProperty(Phaser.Group.prototype, "total", {
+
+    get: function () {
+
+        return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
+
+    }
+
+});
+
+/**
+* Total number of children in this group, regardless of exists/alive status.
+*
+* @name Phaser.Group#length
+* @property {integer} length 
+* @readonly
+*/
+Object.defineProperty(Phaser.Group.prototype, "length", {
+
+    get: function () {
+
+        return this.children.length;
+
+    }
+
+});
+
+/**
+* The angle of rotation of the group container, in degrees.
+*
+* This adjusts the group itself by modifying its local rotation transform.
+*
+* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform
+* and on-screen orientation and position.
+*
+* @name Phaser.Group#angle
+* @property {number} angle
+*/
+Object.defineProperty(Phaser.Group.prototype, "angle", {
+
+    get: function() {
+        return Phaser.Math.radToDeg(this.rotation);
+    },
+
+    set: function(value) {
+        this.rotation = Phaser.Math.degToRad(value);
+    }
+
+});
+
+/**
+* A display object is any object that can be rendered in the Phaser/pixi.js scene graph.
+*
+* This includes {@link Phaser.Group} (groups are display objects!),
+* {@link Phaser.Sprite}, {@link Phaser.Button}, {@link Phaser.Text}
+* as well as {@link PIXI.DisplayObject} and all derived types.
+*
+* @typedef {object} DisplayObject
+*/
+// Documentation stub for linking.
+
+/**
+* The x coordinate of the group container.
+*
+* You can adjust the group container itself by modifying its coordinates.
+* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
+* @name Phaser.Group#x
+* @property {number} x
+*/
+
+/**
+* The y coordinate of the group container.
+*
+* You can adjust the group container itself by modifying its coordinates.
+* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
+* @name Phaser.Group#y
+* @property {number} y
+*/
+
+/**
+* The angle of rotation of the group container, in radians.
+*
+* This will adjust the group container itself by modifying its rotation.
+* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
+* @name Phaser.Group#rotation
+* @property {number} rotation
+*/
+
+/**
+* The visible state of the group. Non-visible Groups and all of their children are not rendered.
+*
+* @name Phaser.Group#visible
+* @property {boolean} visible
+*/
+
+/**
+* The alpha value of the group container.
+*
+* @name Phaser.Group#alpha
+* @property {number} alpha
+*/
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* "This world is but a canvas to our imagination." - Henry David Thoreau
+*
+* A game has only one world. The world is an abstract place in which all game objects live. It is not bound
+* by stage limits and can be any size. You look into the world via cameras. All game objects live within
+* the world at world-based coordinates. By default a world is created the same size as your Stage.
+*
+* @class Phaser.World
+* @extends Phaser.Group
+* @constructor
+* @param {Phaser.Game} game - Reference to the current game instance.
+*/
+Phaser.World = function (game) {
+
+    Phaser.Group.call(this, game, null, '__world', false);
+
+    /**
+    * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects.
+    * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display.
+    * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0.
+    * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0.
+    * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
+    */
+    this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
+
+    /**
+    * @property {Phaser.Camera} camera - Camera instance.
+    */
+    this.camera = null;
+
+    /**
+    * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions.
+    * @readonly
+    */
+    this._definedSize = false;
+
+    /**
+    * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension.
+    */
+    this._width = game.width;
+
+    /**
+    * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension.
+    */
+    this._height = game.height;
+
+    this.game.state.onStateChange.add(this.stateChange, this);
+
+};
+
+Phaser.World.prototype = Object.create(Phaser.Group.prototype);
+Phaser.World.prototype.constructor = Phaser.World;
+
+/**
+* Initialises the game world.
+*
+* @method Phaser.World#boot
+* @protected
+*/
+Phaser.World.prototype.boot = function () {
+
+    this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
+
+    this.camera.displayObject = this;
+
+    this.camera.scale = this.scale;
+
+    this.game.camera = this.camera;
+
+    this.game.stage.addChild(this);
+
+};
+
+/**
+* Called whenever the State changes or resets.
+* 
+* It resets the world.x and world.y coordinates back to zero,
+* then resets the Camera.
+*
+* @method Phaser.World#stateChange
+* @protected
+*/
+Phaser.World.prototype.stateChange = function () {
+
+    this.x = 0;
+    this.y = 0;
+
+    this.camera.reset();
+
+};
+
+/**
+* Updates the size of this world and sets World.x/y to the given values
+* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds.
+*
+* @method Phaser.World#setBounds
+* @param {number} x - Top left most corner of the world.
+* @param {number} y - Top left most corner of the world.
+* @param {number} width - New width of the game world in pixels.
+* @param {number} height - New height of the game world in pixels.
+*/
+Phaser.World.prototype.setBounds = function (x, y, width, height) {
+
+    this._definedSize = true;
+    this._width = width;
+    this._height = height;
+
+    this.bounds.setTo(x, y, width, height);
+
+    this.x = x;
+    this.y = y;
+
+    if (this.camera.bounds)
+    {
+        //  The Camera can never be smaller than the game size
+        this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height));
+    }
+
+    this.game.physics.setBoundsToWorld();
+
+};
+
+/**
+* Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
+*
+* @method Phaser.World#resize
+* @param {number} width - New width of the game world in pixels.
+* @param {number} height - New height of the game world in pixels.
+*/
+Phaser.World.prototype.resize = function (width, height) {
+
+    //  Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size
+
+    if (this._definedSize)
+    {
+        if (width < this._width)
+        {
+            width = this._width;
+        }
+
+        if (height < this._height)
+        {
+            height = this._height;
+        }
+    }
+
+    this.bounds.width = width;
+    this.bounds.height = height;
+
+    this.game.camera.setBoundsToWorld();
+
+    this.game.physics.setBoundsToWorld();
+
+};
+
+/**
+* Destroyer of worlds.
+*
+* @method Phaser.World#shutdown
+*/
+Phaser.World.prototype.shutdown = function () {
+
+    //  World is a Group, so run a soft destruction on this and all children.
+    this.destroy(true, true);
+
+};
+
+/**
+* This will take the given game object and check if its x/y coordinates fall outside of the world bounds.
+* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect.
+* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function.
+*
+* @method Phaser.World#wrap
+* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds.
+* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true.
+* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive.
+* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally.
+* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically.
+*/
+Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) {
+
+    if (padding === undefined) { padding = 0; }
+    if (useBounds === undefined) { useBounds = false; }
+    if (horizontal === undefined) { horizontal = true; }
+    if (vertical === undefined) { vertical = true; }
+
+    if (!useBounds)
+    {
+        if (horizontal && sprite.x + padding < this.bounds.x)
+        {
+            sprite.x = this.bounds.right + padding;
+        }
+        else if (horizontal && sprite.x - padding > this.bounds.right)
+        {
+            sprite.x = this.bounds.left - padding;
+        }
+
+        if (vertical && sprite.y + padding < this.bounds.top)
+        {
+            sprite.y = this.bounds.bottom + padding;
+        }
+        else if (vertical && sprite.y - padding > this.bounds.bottom)
+        {
+            sprite.y = this.bounds.top - padding;
+        }
+    }
+    else
+    {
+        sprite.getBounds();
+
+        if (horizontal)
+        {
+            if ((sprite.x + sprite._currentBounds.width) < this.bounds.x)
+            {
+                sprite.x = this.bounds.right;
+            }
+            else if (sprite.x > this.bounds.right)
+            {
+                sprite.x = this.bounds.left;
+            }
+        }
+
+        if (vertical)
+        {
+            if ((sprite.y + sprite._currentBounds.height) < this.bounds.top)
+            {
+                sprite.y = this.bounds.bottom;
+            }
+            else if (sprite.y > this.bounds.bottom)
+            {
+                sprite.y = this.bounds.top;
+            }
+        }
+    }
+
+};
+
+/**
+* @name Phaser.World#width
+* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions.
+*/
+Object.defineProperty(Phaser.World.prototype, "width", {
+
+    get: function () {
+        return this.bounds.width;
+    },
+
+    set: function (value) {
+
+        if (value < this.game.width)
+        {
+            value = this.game.width;
+        }
+
+        this.bounds.width = value;
+        this._width = value;
+        this._definedSize = true;
+
+    }
+
+});
+
+/**
+* @name Phaser.World#height
+* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions.
+*/
+Object.defineProperty(Phaser.World.prototype, "height", {
+
+    get: function () {
+        return this.bounds.height;
+    },
+
+    set: function (value) {
+
+        if (value < this.game.height)
+        {
+            value = this.game.height;
+        }
+
+        this.bounds.height = value;
+        this._height = value;
+        this._definedSize = true;
+
+    }
+
+});
+
+/**
+* @name Phaser.World#centerX
+* @property {number} centerX - Gets the X position corresponding to the center point of the world.
+* @readonly
+*/
+Object.defineProperty(Phaser.World.prototype, "centerX", {
+
+    get: function () {
+        return this.bounds.halfWidth;
+    }
+
+});
+
+/**
+* @name Phaser.World#centerY
+* @property {number} centerY - Gets the Y position corresponding to the center point of the world.
+* @readonly
+*/
+Object.defineProperty(Phaser.World.prototype, "centerY", {
+
+    get: function () {
+        return this.bounds.halfHeight;
+    }
+
+});
+
+/**
+* @name Phaser.World#randomX
+* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
+* @readonly
+*/
+Object.defineProperty(Phaser.World.prototype, "randomX", {
+
+    get: function () {
+
+        if (this.bounds.x < 0)
+        {
+            return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
+        }
+        else
+        {
+            return this.game.rnd.between(this.bounds.x, this.bounds.width);
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.World#randomY
+* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
+* @readonly
+*/
+Object.defineProperty(Phaser.World.prototype, "randomY", {
+
+    get: function () {
+
+        if (this.bounds.y < 0)
+        {
+            return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
+        }
+        else
+        {
+            return this.game.rnd.between(this.bounds.y, this.bounds.height);
+        }
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete.
+* Please try to avoid using in production games with a long time to build.
+* This is also why the documentation is incomplete.
+* 
+* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers
+* to provide for game object positioning in a responsive manner.
+*
+* @class Phaser.FlexGrid
+* @constructor
+* @param {Phaser.ScaleManager} manager - The ScaleManager.
+* @param {number} width - The width of the game.
+* @param {number} height - The height of the game.
+*/
+Phaser.FlexGrid = function (manager, width, height) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = manager.game;
+
+    /**
+    * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager.
+    */
+    this.manager = manager;
+
+    //  The perfect dimensions on which everything else is based
+    this.width = width;
+    this.height = height;
+
+    this.boundsCustom = new Phaser.Rectangle(0, 0, width, height);
+    this.boundsFluid = new Phaser.Rectangle(0, 0, width, height);
+    this.boundsFull = new Phaser.Rectangle(0, 0, width, height);
+    this.boundsNone = new Phaser.Rectangle(0, 0, width, height);
+
+    /**
+    * @property {Phaser.Point} position - 
+    * @readonly
+    */
+    this.positionCustom = new Phaser.Point(0, 0);
+    this.positionFluid = new Phaser.Point(0, 0);
+    this.positionFull = new Phaser.Point(0, 0);
+    this.positionNone = new Phaser.Point(0, 0);
+
+    /**
+    * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
+    * @readonly
+    */
+    this.scaleCustom = new Phaser.Point(1, 1);
+    this.scaleFluid = new Phaser.Point(1, 1);
+    this.scaleFluidInversed = new Phaser.Point(1, 1);
+    this.scaleFull = new Phaser.Point(1, 1);
+    this.scaleNone = new Phaser.Point(1, 1);
+
+    this.customWidth = 0;
+    this.customHeight = 0;
+    this.customOffsetX = 0;
+    this.customOffsetY = 0;
+
+    this.ratioH = width / height;
+    this.ratioV = height / width;
+
+    this.multiplier = 0;
+
+    this.layers = [];
+
+};
+
+Phaser.FlexGrid.prototype = {
+
+    /**
+     * Sets the core game size. This resets the w/h parameters and bounds.
+     *
+     * @method Phaser.FlexGrid#setSize
+     * @param {number} width - The new dimensions.
+     * @param {number} height - The new dimensions.
+     */
+    setSize: function (width, height) {
+
+        //  These are locked and don't change until setSize is called again
+        this.width = width;
+        this.height = height;
+
+        this.ratioH = width / height;
+        this.ratioV = height / width;
+
+        this.scaleNone = new Phaser.Point(1, 1);
+
+        this.boundsNone.width = this.width;
+        this.boundsNone.height = this.height;
+
+        this.refresh();
+
+    },
+
+    //  Need ability to create your own layers with custom scaling, etc.
+
+    /**
+     * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down.
+     *
+     * @method Phaser.FlexGrid#createCustomLayer
+     * @param {number} width - Width of this layer in pixels.
+     * @param {number} height - Height of this layer in pixels.
+     * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer.
+     * @return {Phaser.FlexLayer} The Layer object.
+     */
+    createCustomLayer: function (width, height, children, addToWorld) {
+
+        if (addToWorld === undefined) { addToWorld = true; }
+
+        this.customWidth = width;
+        this.customHeight = height;
+
+        this.boundsCustom.width = width;
+        this.boundsCustom.height = height;
+
+        var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom);
+
+        if (addToWorld)
+        {
+            this.game.world.add(layer);
+        }
+
+        this.layers.push(layer);
+
+        if (typeof children !== 'undefined' && typeof children !== null)
+        {
+            layer.addMultiple(children);
+        }
+
+        return layer;
+
+    },
+
+    /**
+     * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down.
+     *
+     * @method Phaser.FlexGrid#createFluidLayer
+     * @param {array} [children] - An array of children that are used to populate the FlexLayer.
+     * @return {Phaser.FlexLayer} The Layer object.
+     */
+    createFluidLayer: function (children, addToWorld) {
+
+        if (addToWorld === undefined) { addToWorld = true; }
+
+        var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid);
+
+        if (addToWorld)
+        {
+            this.game.world.add(layer);
+        }
+
+        this.layers.push(layer);
+
+        if (typeof children !== 'undefined' && typeof children !== null)
+        {
+            layer.addMultiple(children);
+        }
+
+        return layer;
+
+    },
+
+    /**
+     * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios.
+     *
+     * @method Phaser.FlexGrid#createFullLayer
+     * @param {array} [children] - An array of children that are used to populate the FlexLayer.
+     * @return {Phaser.FlexLayer} The Layer object.
+     */
+    createFullLayer: function (children) {
+
+        var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid);
+
+        this.game.world.add(layer);
+
+        this.layers.push(layer);
+
+        if (typeof children !== 'undefined')
+        {
+            layer.addMultiple(children);
+        }
+
+        return layer;
+
+    },
+
+    /**
+     * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled.
+     *
+     * @method Phaser.FlexGrid#createFixedLayer
+     * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer.
+     * @return {Phaser.FlexLayer} The Layer object.
+     */
+    createFixedLayer: function (children) {
+
+        var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone);
+
+        this.game.world.add(layer);
+
+        this.layers.push(layer);
+
+        if (typeof children !== 'undefined')
+        {
+            layer.addMultiple(children);
+        }
+
+        return layer;
+
+    },
+
+    /**
+     * Resets the layer children references
+     *
+     * @method Phaser.FlexGrid#reset
+     */
+    reset: function () {
+
+        var i = this.layers.length;
+
+        while (i--)
+        {
+            if (!this.layers[i].persist)
+            {
+                //  Remove references to this class
+                this.layers[i].position = null;
+                this.layers[i].scale = null;
+                this.layers.slice(i, 1);
+            }
+        }
+
+    },
+
+    /**
+     * Called when the game container changes dimensions.
+     *
+     * @method Phaser.FlexGrid#onResize
+     * @param {number} width - The new width of the game container.
+     * @param {number} height - The new height of the game container.
+     */
+    onResize: function (width, height) {
+
+        this.ratioH = width / height;
+        this.ratioV = height / width;
+
+        this.refresh(width, height);
+
+    },
+
+    /**
+     * Updates all internal vars such as the bounds and scale values.
+     *
+     * @method Phaser.FlexGrid#refresh
+     */
+    refresh: function () {
+
+        this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width));
+
+        this.boundsFluid.width = Math.round(this.width * this.multiplier);
+        this.boundsFluid.height = Math.round(this.height * this.multiplier);
+
+        this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height);
+        this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height);
+
+        this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height);
+
+        this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x);
+        this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y);
+
+        this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY);
+        this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY);
+
+        this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y);
+        this.positionNone.set(this.boundsNone.x, this.boundsNone.y);
+
+    },
+
+    /**
+     * Fits a sprites width to the bounds.
+     *
+     * @method Phaser.FlexGrid#fitSprite
+     * @param {Phaser.Sprite} sprite - The Sprite to fit.
+     */
+    fitSprite: function (sprite) {
+
+        this.manager.scaleSprite(sprite);
+
+        sprite.x = this.manager.bounds.centerX;
+        sprite.y = this.manager.bounds.centerY;
+
+    },
+
+    /**
+     * Call in the render function to output the bounds rects.
+     *
+     * @method Phaser.FlexGrid#debug
+     */
+    debug: function () {
+
+        // for (var i = 0; i < this.layers.length; i++)
+        // {
+        //     this.layers[i].debug();
+        // }
+
+        // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16);
+        // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false);
+
+        this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16);
+        this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false);
+
+        // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16);
+        // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false);
+
+        // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16);
+        // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false);
+
+    }
+
+};
+
+Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete.
+* Please try to avoid using in production games with a long time to build.
+* This is also why the documentation is incomplete.
+* 
+* A responsive grid layer.
+*
+* @class Phaser.FlexLayer
+* @extends Phaser.Group
+* @constructor
+* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer.
+* @param {Phaser.Point} position - A reference to the Point object used for positioning.
+* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds.
+* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling.
+*/
+Phaser.FlexLayer = function (manager, position, bounds, scale) {
+
+    Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false);
+
+    /**
+    * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager.
+    */
+    this.manager = manager.manager;
+
+    /**
+    * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer.
+    */
+    this.grid = manager;
+
+    /**
+     * Should the FlexLayer remain through a State swap?
+     *
+     * @type {boolean}
+     */
+    this.persist = false;
+
+    /**
+    * @property {Phaser.Point} position
+    */
+    this.position = position;
+
+    /**
+    * @property {Phaser.Rectangle} bounds
+    */
+    this.bounds = bounds;
+
+    /**
+    * @property {Phaser.Point} scale
+    */
+    this.scale = scale;
+
+    /**
+    * @property {Phaser.Point} topLeft
+    */
+    this.topLeft = bounds.topLeft;
+
+    /**
+    * @property {Phaser.Point} topMiddle
+    */
+    this.topMiddle = new Phaser.Point(bounds.halfWidth, 0);
+
+    /**
+    * @property {Phaser.Point} topRight
+    */
+    this.topRight = bounds.topRight;
+
+    /**
+    * @property {Phaser.Point} bottomLeft
+    */
+    this.bottomLeft = bounds.bottomLeft;
+
+    /**
+    * @property {Phaser.Point} bottomMiddle
+    */
+    this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom);
+
+    /**
+    * @property {Phaser.Point} bottomRight
+    */
+    this.bottomRight = bounds.bottomRight;
+
+};
+
+Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype);
+Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer;
+
+/**
+ * Resize.
+ *
+ * @method Phaser.FlexLayer#resize
+ */
+Phaser.FlexLayer.prototype.resize = function () {
+};
+
+/**
+ * Debug.
+ *
+ * @method Phaser.FlexLayer#debug
+ */
+Phaser.FlexLayer.prototype.debug = function () {
+
+    this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16);
+    this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false);
+
+    this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9');
+    this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9');
+    this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9');
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* @classdesc
+* The ScaleManager object handles the the scaling, resizing, and alignment of the
+* Game size and the game Display canvas.
+*
+* The Game size is the logical size of the game; the Display canvas has size as an HTML element.
+*
+* The calculations of these are heavily influenced by the bounding Parent size which is the computed
+* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the
+* canvas's Parent element play an important role_ in the operation of the ScaleManager. 
+*
+* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size.
+* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}).
+*
+* Parent and Display canvas containment guidelines:
+*
+* - Style the Parent element (of the game canvas) to control the Parent size and
+*   thus the Display canvas's size and layout.
+*
+* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior.
+*
+* - The Parent element should _not_ apply a padding as this is not accounted for.
+*   If a padding is required apply it to the Parent's parent or apply a margin to the Parent.
+*   If you need to add a border, margin or any other CSS around your game container, then use a parent element and
+*   apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container.
+*
+* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as
+*   they may be updated by the ScaleManager.
+*
+* @description
+* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game}
+*
+* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%.
+*
+* @class
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number|string} width - The width of the game. See above.
+* @param {number|string} height - The height of the game. See above.
+*/
+Phaser.ScaleManager = function (game, width, height) {
+
+    /**
+    * A reference to the currently running game.
+    * @property {Phaser.Game} game
+    * @protected
+    * @readonly
+    */
+    this.game = game;
+
+    /**
+    * Provides access to some cross-device DOM functions.
+    * @property {Phaser.DOM} dom
+    * @protected
+    * @readonly
+    */
+    this.dom = Phaser.DOM;
+
+    /**
+    * _EXPERIMENTAL:_ A responsive grid on which you can align game objects.
+    * @property {Phaser.FlexGrid} grid
+    * @public
+    */
+    this.grid = null;
+
+    /**
+    * Target width (in pixels) of the Display canvas.
+    * @property {number} width
+    * @readonly
+    */
+    this.width = 0;
+
+    /**
+    * Target height (in pixels) of the Display canvas.
+    * @property {number} height
+    * @readonly
+    */
+    this.height = 0;
+
+    /**
+    * Minimum width the canvas should be scaled to (in pixels).
+    * Change with {@link #setMinMax}.
+    * @property {?number} minWidth
+    * @readonly
+    * @protected
+    */
+    this.minWidth = null;
+
+    /**
+    * Maximum width the canvas should be scaled to (in pixels).
+    * If null it will scale to whatever width the browser can handle.
+    * Change with {@link #setMinMax}.
+    * @property {?number} maxWidth
+    * @readonly
+    * @protected
+    */
+    this.maxWidth = null;
+
+    /**
+    * Minimum height the canvas should be scaled to (in pixels).
+    * Change with {@link #setMinMax}.
+    * @property {?number} minHeight
+    * @readonly
+    * @protected
+    */
+    this.minHeight = null;
+
+    /**
+    * Maximum height the canvas should be scaled to (in pixels).
+    * If null it will scale to whatever height the browser can handle.
+    * Change with {@link #setMinMax}.
+    * @property {?number} maxHeight
+    * @readonly
+    * @protected
+    */
+    this.maxHeight = null;
+
+    /**
+    * The offset coordinates of the Display canvas from the top-left of the browser window.
+    * The is used internally by Phaser.Pointer (for Input) and possibly other types.
+    * @property {Phaser.Point} offset
+    * @readonly
+    * @protected
+    */
+    this.offset = new Phaser.Point();
+
+    /**
+    * If true, the game should only run in a landscape orientation.
+    * Change with {@link #forceOrientation}.
+    * @property {boolean} forceLandscape
+    * @readonly
+    * @default
+    * @protected
+    */
+    this.forceLandscape = false;
+
+    /**
+    * If true, the game should only run in a portrait 
+    * Change with {@link #forceOrientation}.
+    * @property {boolean} forcePortrait
+    * @readonly
+    * @default
+    * @protected
+    */
+    this.forcePortrait = false;
+
+    /**
+    * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation.
+    *
+    * This value is not updated immediately.
+    *
+    * @property {boolean} incorrectOrientation    
+    * @readonly
+    * @protected
+    */
+    this.incorrectOrientation = false;
+
+    /**
+    * See {@link #pageAlignHorizontally}.
+    * @property {boolean} _pageAlignHorizontally
+    * @private
+    */
+    this._pageAlignHorizontally = false;
+
+    /**
+    * See {@link #pageAlignVertically}.
+    * @property {boolean} _pageAlignVertically
+    * @private
+    */
+    this._pageAlignVertically = false;
+
+    /**
+    * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes.
+    * 
+    * The signal is supplied with the following arguments:
+    * - `scale` - the ScaleManager object
+    * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}.
+    * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect.
+    *
+    * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`.
+    * Thus the following tests can be done:
+    *
+    *     // The orientation itself changed:
+    *     scale.screenOrientation !== prevOrientation
+    *     // The orientation just became incorrect:
+    *     scale.incorrectOrientation && !wasIncorrect
+    *
+    * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation
+    * correctness changes even if the orientation itself does not change.
+    *
+    * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
+    *
+    * @property {Phaser.Signal} onOrientationChange
+    * @public
+    */
+    this.onOrientationChange = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}.
+    *
+    * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
+    *
+    * @property {Phaser.Signal} enterIncorrectOrientation
+    * @public
+    */
+    this.enterIncorrectOrientation = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}.
+    *
+    * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
+    *
+    * @property {Phaser.Signal} leaveIncorrectOrientation
+    * @public
+    */
+    this.leaveIncorrectOrientation = new Phaser.Signal();
+
+    /**
+    * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked.
+    * The target element must have the correct CSS styling and contain the Display canvas.
+    *
+    * The elements style will be modified (ie. the width and height might be set to 100%)
+    * but it will not be added to, removed from, or repositioned within the DOM.
+    * An attempt is made to restore relevant style changes when fullscreen mode is left.
+    *
+    * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`.
+    *
+    * @property {?DOMElement} fullScreenTarget
+    * @default
+    */
+    this.fullScreenTarget = null;
+
+    /**
+    * The fullscreen target, as created by {@link #createFullScreenTarget}.
+    * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends.
+    * @property {?DOMElement} _createdFullScreenTarget
+    * @private
+    */
+    this._createdFullScreenTarget = null;
+
+    /**
+    * This signal is dispatched when fullscreen mode is ready to be initialized but
+    * before the fullscreen request.
+    *
+    * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`.
+    *
+    * The `targetElement` is the {@link #fullScreenTarget} element,
+    * if such is assigned, or a new element created by {@link #createFullScreenTarget}.
+    *
+    * Custom CSS styling or resets can be applied to `targetElement` as required.
+    *
+    * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}:
+    * - After initialization the Display canvas is moved onto the `targetElement` for
+    *   the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited.
+    * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated.
+    *
+    * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}.
+    *
+    * @property {Phaser.Signal} onFullScreenInit
+    * @public
+    */
+    this.onFullScreenInit = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported.
+    *
+    * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine
+    * if currently running in Fullscreen mode.
+    *
+    * @property {Phaser.Signal} onFullScreenChange
+    * @public    
+    */
+    this.onFullScreenChange = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when the browser fails to enter fullscreen mode;
+    * or if the device does not support fullscreen mode and `startFullScreen` is invoked.
+    *
+    * The signal is supplied with a single argument: `scale` (the ScaleManager).
+    *
+    * @property {Phaser.Signal} onFullScreenError
+    * @public
+    */
+    this.onFullScreenError = new Phaser.Signal();
+
+    /**
+    * The _last known_ orientation of the screen, as defined in the Window Screen Web API.
+    * See {@link Phaser.DOM.getScreenOrientation} for possible values.
+    *
+    * @property {string} screenOrientation
+    * @readonly
+    * @public
+    */
+    this.screenOrientation = this.dom.getScreenOrientation();
+
+    /**
+    * The _current_ scale factor based on the game dimensions vs. the scaled dimensions.
+    * @property {Phaser.Point} scaleFactor
+    * @readonly
+    */
+    this.scaleFactor = new Phaser.Point(1, 1);
+
+    /**
+    * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions.
+    * @property {Phaser.Point} scaleFactorInversed
+    * @readonly
+    * @protected
+    */
+    this.scaleFactorInversed = new Phaser.Point(1, 1);
+
+    /**
+    * The Display canvas is aligned by adjusting the margins; the last margins are stored here.
+    *
+    * @property {Bounds-like} margin
+    * @readonly
+    * @protected
+    */
+    this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0};
+
+    /**
+    * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height.
+    * @property {Phaser.Rectangle} bounds
+    * @readonly
+    */
+    this.bounds = new Phaser.Rectangle();
+
+    /**
+    * The aspect ratio of the scaled Display canvas.
+    * @property {number} aspectRatio
+    * @readonly
+    */
+    this.aspectRatio = 0;
+
+    /**
+    * The aspect ratio of the original game dimensions.
+    * @property {number} sourceAspectRatio
+    * @readonly
+    */
+    this.sourceAspectRatio = 0;
+
+    /**
+    * The native browser events from Fullscreen API changes.
+    * @property {any} event
+    * @readonly
+    * @private
+    */
+    this.event = null;
+
+    /**
+    * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container.
+    *
+    * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'.
+    * - If 'visual', the edge will be constrained to the Window / displayed screen area
+    * - If 'layout', the edge will be constrained to the CSS Layout bounds
+    * - An invalid value is treated as 'visual'
+    *
+    * @member
+    * @property {string} bottom
+    * @property {string} right
+    * @default
+    */
+    this.windowConstraints = {
+        right: 'layout',
+        bottom: ''
+    };
+
+    /**
+    * Various compatibility settings.
+    * A value of "(auto)" indicates the setting is configured based on device and runtime information.
+    *
+    * A {@link #refresh} may need to be performed after making changes.
+    *
+    * @protected
+    * 
+    * @property {boolean} [supportsFullscreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.)
+    *
+    * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}.
+    *
+    * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen.
+    *
+    * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh.
+    *
+    * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates.
+    *    The height set varies by device and may either be the height of the window or the viewport.
+    *
+    * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions.
+    *
+    * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events.
+    *     A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used.
+    *     Any other string value (including the empty string) prevents using click trampolines.
+    *     For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}.
+    */
+    this.compatibility = {
+        supportsFullScreen: false,
+        orientationFallback: null,
+        noMargins: false,
+        scrollTo: null,
+        forceMinimumDocumentHeight: false,
+        canExpandParent: true,
+        clickTrampoline: ''
+    };
+
+    /**
+    * Scale mode to be used when not in fullscreen.
+    * @property {number} _scaleMode
+    * @private
+    */
+    this._scaleMode = Phaser.ScaleManager.NO_SCALE;
+
+    /*
+    * Scale mode to be used in fullscreen.
+    * @property {number} _fullScreenScaleMode
+    * @private
+    */
+    this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
+
+    /**
+    * If the parent container of the Game canvas is the browser window itself (i.e. document.body),
+    * rather than another div, this should set to `true`.
+    *
+    * The {@link #parentNode} property is generally ignored while this is in effect.
+    *
+    * @property {boolean} parentIsWindow
+    */
+    this.parentIsWindow = false;
+
+    /**
+    * The _original_ DOM element for the parent of the Display canvas.
+    * This may be different in fullscreen - see {@link #createFullScreenTarget}.
+    *
+    * This should only be changed after moving the Game canvas to a different DOM parent.
+    *
+    * @property {?DOMElement} parentNode
+    */
+    this.parentNode = null;
+
+    /**
+    * The scale of the game in relation to its parent container.
+    * @property {Phaser.Point} parentScaleFactor
+    * @readonly
+    */
+    this.parentScaleFactor = new Phaser.Point(1, 1);
+
+    /**
+    * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window).
+    * Update checks normally happen quicker in response to other events.
+    *
+    * @property {integer} trackParentInterval
+    * @default
+    * @protected
+    * @see {@link Phaser.ScaleManager#refresh refresh}
+    */
+    this.trackParentInterval = 2000;
+
+    /**
+    * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. 
+    * When invoked this is done _after_ the Canvas size/position have been updated.
+    *
+    * This signal is _only_ called when a change occurs and a reflow may be required.
+    * For example, if the canvas does not change sizes because of CSS settings (such as min-width)
+    * then this signal will _not_ be triggered.
+    *
+    * Use this to handle responsive game layout options.
+    *
+    * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
+    *
+    * @property {Phaser.Signal} onSizeChange
+    * @todo Formalize the arguments, if any, supplied to this signal.
+    */
+    this.onSizeChange = new Phaser.Signal();
+
+    /**
+    * The callback that will be called each the parent container resizes.
+    * @property {function} onResize
+    * @private
+    */
+    this.onResize = null;
+
+    /**
+    * The context in which the {@link #onResize} callback will be called.
+    * @property {object} onResizeContext
+    * @private
+    */
+    this.onResizeContext = null;
+
+    /**
+    * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot.
+    * @private
+    */
+    this._pendingScaleMode = null;
+
+    /**
+    * Information saved when fullscreen mode is started.
+    * @property {?object} _fullScreenRestore
+    * @private
+    */
+    this._fullScreenRestore = null;
+
+    /**
+    * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}.
+    * @property {Phaser.Rectangle} _gameSize
+    * @private
+    */
+    this._gameSize = new Phaser.Rectangle();
+
+    /**
+    * The user-supplied scale factor, used with the USER_SCALE scaling mode.
+    * @property {Phaser.Point} _userScaleFactor
+    * @private
+    */
+    this._userScaleFactor = new Phaser.Point(1, 1);
+
+    /**
+    * The user-supplied scale trim, used with the USER_SCALE scaling mode.
+    * @property {Phaser.Point} _userScaleTrim
+    * @private
+    */
+    this._userScaleTrim = new Phaser.Point(0, 0);
+
+    /**
+    * The last time the bounds were checked in `preUpdate`.
+    * @property {number} _lastUpdate
+    * @private
+    */
+    this._lastUpdate = 0;
+
+    /**
+    * Size checks updates are delayed according to the throttle.
+    * The throttle increases to `trackParentInterval` over time and is used to more
+    * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety.
+    * @property {integer} _updateThrottle
+    * @private
+    */
+    this._updateThrottle = 0;
+
+    /**
+    * The minimum throttle allowed until it has slowed down sufficiently.
+    * @property {integer} _updateThrottleReset   
+    * @private
+    */
+    this._updateThrottleReset = 100;
+
+    /**
+    * The cached result of the parent (possibly window) bounds; used to invalidate sizing.
+    * @property {Phaser.Rectangle} _parentBounds
+    * @private
+    */
+    this._parentBounds = new Phaser.Rectangle();
+
+    /**
+    * Temporary bounds used for internal work to cut down on new objects created.
+    * @property {Phaser.Rectangle} _parentBounds
+    * @private
+    */
+    this._tempBounds = new Phaser.Rectangle();
+
+    /**
+    * The Canvas size at which the last onSizeChange signal was triggered.
+    * @property {Phaser.Rectangle} _lastReportedCanvasSize
+    * @private
+    */
+    this._lastReportedCanvasSize = new Phaser.Rectangle();
+
+    /**
+    * The Game size at which the last onSizeChange signal was triggered.
+    * @property {Phaser.Rectangle} _lastReportedGameSize
+    * @private
+    */
+    this._lastReportedGameSize = new Phaser.Rectangle();
+
+    /**
+    * @property {boolean} _booted - ScaleManager booted state.
+    * @private
+    */
+    this._booted = false;
+
+    if (game.config)
+    {
+        this.parseConfig(game.config);
+    }
+
+    this.setupScale(width, height);
+
+};
+
+/**
+* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
+*
+* @constant
+* @type {integer}
+*/
+Phaser.ScaleManager.EXACT_FIT = 0;
+
+/**
+* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
+*
+* @constant
+* @type {integer}
+*/
+Phaser.ScaleManager.NO_SCALE = 1;
+
+/**
+* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
+*
+* @constant
+* @type {integer}
+*/
+Phaser.ScaleManager.SHOW_ALL = 2;
+
+/**
+* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
+*
+* @constant
+* @type {integer}
+*/
+Phaser.ScaleManager.RESIZE = 3;
+
+/**
+* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
+*
+* @constant
+* @type {integer}
+*/
+Phaser.ScaleManager.USER_SCALE = 4;
+
+Phaser.ScaleManager.prototype = {
+
+    /**
+    * Start the ScaleManager.
+    * 
+    * @method Phaser.ScaleManager#boot
+    * @protected
+    */
+    boot: function () {
+
+        // Configure device-dependent compatibility
+
+        var compat = this.compatibility;
+        
+        compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS;
+
+        //  We can't do anything about the status bars in iPads, web apps or desktops
+        if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
+        {
+            if (this.game.device.android && !this.game.device.chrome)
+            {
+                compat.scrollTo = new Phaser.Point(0, 1);
+            }
+            else
+            {
+                compat.scrollTo = new Phaser.Point(0, 0);
+            }
+        }
+
+        if (this.game.device.desktop)
+        {
+            compat.orientationFallback = 'screen';
+            compat.clickTrampoline = 'when-not-mouse';
+        }
+        else
+        {
+            compat.orientationFallback = '';
+            compat.clickTrampoline = '';
+        }
+
+        // Configure event listeners
+
+        var _this = this;
+
+        this._orientationChange = function(event) {
+            return _this.orientationChange(event);
+        };
+
+        this._windowResize = function(event) {
+            return _this.windowResize(event);
+        };
+
+        // This does not appear to be on the standards track
+        window.addEventListener('orientationchange', this._orientationChange, false);
+        window.addEventListener('resize', this._windowResize, false);
+
+        if (this.compatibility.supportsFullScreen)
+        {
+            this._fullScreenChange = function(event) {
+                return _this.fullScreenChange(event);
+            };
+
+            this._fullScreenError = function(event) {
+                return _this.fullScreenError(event);
+            };
+
+            document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false);
+            document.addEventListener('mozfullscreenchange', this._fullScreenChange, false);
+            document.addEventListener('MSFullscreenChange', this._fullScreenChange, false);
+            document.addEventListener('fullscreenchange', this._fullScreenChange, false);
+
+            document.addEventListener('webkitfullscreenerror', this._fullScreenError, false);
+            document.addEventListener('mozfullscreenerror', this._fullScreenError, false);
+            document.addEventListener('MSFullscreenError', this._fullScreenError, false);
+            document.addEventListener('fullscreenerror', this._fullScreenError, false);
+        }
+
+        this.game.onResume.add(this._gameResumed, this);
+
+        // Initialize core bounds
+
+        this.dom.getOffset(this.game.canvas, this.offset);
+
+        this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
+
+        this.setGameSize(this.game.width, this.game.height);
+
+        // Don't use updateOrientationState so events are not fired
+        this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
+
+        this.grid = new Phaser.FlexGrid(this, this.width, this.height);
+
+        this._booted = true;
+
+        if (this._pendingScaleMode)
+        {
+            this.scaleMode = this._pendingScaleMode;
+            this._pendingScaleMode = null;
+        }
+
+    },
+
+    /**
+    * Load configuration settings.
+    * 
+    * @method Phaser.ScaleManager#parseConfig
+    * @protected
+    * @param {object} config - The game configuration object.
+    */
+    parseConfig: function (config) {
+
+        if (config['scaleMode'])
+        {
+            if (this._booted)
+            {
+                this.scaleMode = config['scaleMode'];
+            }
+            else
+            {
+                this._pendingScaleMode = config['scaleMode'];
+            }
+        }
+
+        if (config['fullScreenScaleMode'])
+        {
+            this.fullScreenScaleMode = config['fullScreenScaleMode'];
+        }
+
+        if (config['fullScreenTarget'])
+        {
+            this.fullScreenTarget = config['fullScreenTarget'];
+        }
+
+    },
+
+    /**
+    * Calculates and sets the game dimensions based on the given width and height.
+    *
+    * This should _not_ be called when in fullscreen mode.
+    * 
+    * @method Phaser.ScaleManager#setupScale
+    * @protected
+    * @param {number|string} width - The width of the game.
+    * @param {number|string} height - The height of the game.
+    */
+    setupScale: function (width, height) {
+
+        var target;
+        var rect = new Phaser.Rectangle();
+
+        if (this.game.parent !== '')
+        {
+            if (typeof this.game.parent === 'string')
+            {
+                // hopefully an element ID
+                target = document.getElementById(this.game.parent);
+            }
+            else if (this.game.parent && this.game.parent.nodeType === 1)
+            {
+                // quick test for a HTMLelement
+                target = this.game.parent;
+            }
+        }
+
+        // Fallback, covers an invalid ID and a non HTMLelement object
+        if (!target)
+        {
+            //  Use the full window
+            this.parentNode = null;
+            this.parentIsWindow = true;
+
+            rect.width = this.dom.visualBounds.width;
+            rect.height = this.dom.visualBounds.height;
+
+            this.offset.set(0, 0);
+        }
+        else
+        {
+            this.parentNode = target;
+            this.parentIsWindow = false;
+
+            this.getParentBounds(this._parentBounds);
+
+            rect.width = this._parentBounds.width;
+            rect.height = this._parentBounds.height;
+
+            this.offset.set(this._parentBounds.x, this._parentBounds.y);
+        }
+
+        var newWidth = 0;
+        var newHeight = 0;
+
+        if (typeof width === 'number')
+        {
+            newWidth = width;
+        }
+        else
+        {
+            //  Percentage based
+            this.parentScaleFactor.x = parseInt(width, 10) / 100;
+            newWidth = rect.width * this.parentScaleFactor.x;
+        }
+
+        if (typeof height === 'number')
+        {
+            newHeight = height;
+        }
+        else
+        {
+            //  Percentage based
+            this.parentScaleFactor.y = parseInt(height, 10) / 100;
+            newHeight = rect.height * this.parentScaleFactor.y;
+        }
+
+        this._gameSize.setTo(0, 0, newWidth, newHeight);
+
+        this.updateDimensions(newWidth, newHeight, false);
+
+    },
+
+    /**
+    * Invoked when the game is resumed.
+    * 
+    * @method Phaser.ScaleManager#_gameResumed
+    * @private
+    */
+    _gameResumed: function () {
+
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * Set the actual Game size.
+    * Use this instead of directly changing `game.width` or `game.height`.
+    *
+    * The actual physical display (Canvas element size) depends on various settings including
+    * - Scale mode
+    * - Scaling factor
+    * - Size of Canvas's parent element or CSS rules such as min-height/max-height;
+    * - The size of the Window
+    *
+    * @method Phaser.ScaleManager#setGameSize
+    * @public
+    * @param {integer} width - _Game width_, in pixels.
+    * @param {integer} height - _Game height_, in pixels.
+    */
+    setGameSize: function (width, height) {
+
+        this._gameSize.setTo(0, 0, width, height);
+        
+        if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE)
+        {
+            this.updateDimensions(width, height, true);
+        }
+
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * Set a User scaling factor used in the USER_SCALE scaling mode.
+    *
+    * The target canvas size is computed by:
+    *
+    *     canvas.width = (game.width * hScale) - hTrim
+    *     canvas.height = (game.height * vScale) - vTrim
+    *
+    * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}.
+    *
+    * @method Phaser.ScaleManager#setUserScale
+    * @param {number} hScale - Horizontal scaling factor.
+    * @param {numer} vScale - Vertical scaling factor.
+    * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling.
+    * @param {integer} [vTrim=0] - Vertical trim, applied after scaling.
+    */
+    setUserScale: function (hScale, vScale, hTrim, vTrim) {
+
+        this._userScaleFactor.setTo(hScale, vScale);
+        this._userScaleTrim.setTo(hTrim | 0, vTrim | 0);
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * Sets the callback that will be invoked before sizing calculations.
+    *
+    * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling.
+    *
+    * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager
+    * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element.
+    *
+    * This callback
+    * - May be invoked even though the parent container or canvas sizes have not changed
+    * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated
+    * - Will be invoked from `preUpdate`, _even when_ the game is paused    
+    *
+    * See {@link #onSizeChange} for a better way of reacting to layout updates.
+    * 
+    * @method Phaser.ScaleManager#setResizeCallback
+    * @public
+    * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes.
+    * @param {object} context - The context in which the callback will be called.
+    */
+    setResizeCallback: function (callback, context) {
+
+        this.onResize = callback;
+        this.onResizeContext = context;
+
+    },
+
+    /**
+    * Signals a resize - IF the canvas or Game size differs from the last signal.
+    *
+    * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager).
+    *
+    * @method Phaser.ScaleManager#signalSizeChange
+    * @private
+    */
+    signalSizeChange: function () {
+
+        if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) ||
+            !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize))
+        {
+            var width = this.width;
+            var height = this.height;
+
+            this._lastReportedCanvasSize.setTo(0, 0, width, height);
+            this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height);
+
+            this.grid.onResize(width, height);
+
+            this.onSizeChange.dispatch(this, width, height);
+
+            // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode.
+            if (this.currentScaleMode === Phaser.ScaleManager.RESIZE)
+            {
+                this.game.state.resize(width, height);
+                this.game.load.resize(width, height);
+            }
+        }
+
+    },
+
+    /**
+    * Set the min and max dimensions for the Display canvas.
+    * 
+    * _Note:_ The min/max dimensions are only applied in some cases
+    * - When the device is not in an incorrect orientation; or
+    * - The scale mode is EXACT_FIT when not in fullscreen
+    *
+    * @method Phaser.ScaleManager#setMinMax
+    * @public
+    * @param {number} minWidth - The minimum width the game is allowed to scale down to.
+    * @param {number} minHeight - The minimum height the game is allowed to scale down to.
+    * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified.
+    * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified.
+    * @todo These values are only sometimes honored.
+    */
+    setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) {
+
+        this.minWidth = minWidth;
+        this.minHeight = minHeight;
+
+        if (typeof maxWidth !== 'undefined')
+        {
+            this.maxWidth = maxWidth;
+        }
+
+        if (typeof maxHeight !== 'undefined')
+        {
+            this.maxHeight = maxHeight;
+        }
+
+    },
+
+    /**
+    * The ScaleManager.preUpdate is called automatically by the core Game loop.
+    * 
+    * @method Phaser.ScaleManager#preUpdate
+    * @protected
+    */
+    preUpdate: function () {
+
+        if (this.game.time.time < (this._lastUpdate + this._updateThrottle))
+        {
+            return;
+        }
+
+        var prevThrottle = this._updateThrottle;
+        this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100;
+
+        this.dom.getOffset(this.game.canvas, this.offset);
+
+        var prevWidth = this._parentBounds.width;
+        var prevHeight = this._parentBounds.height;
+        var bounds = this.getParentBounds(this._parentBounds);
+
+        var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight;
+
+        // Always invalidate on a newly detected orientation change
+        var orientationChanged = this.updateOrientationState();
+
+        if (boundsChanged || orientationChanged)
+        {
+            if (this.onResize)
+            {
+                this.onResize.call(this.onResizeContext, this, bounds);
+            }
+
+            this.updateLayout();
+
+            this.signalSizeChange();
+        }
+
+        // Next throttle, eg. 25, 50, 100, 200..
+        var throttle = this._updateThrottle * 2;
+
+        // Don't let an update be too eager about resetting the throttle.
+        if (this._updateThrottle < prevThrottle)
+        {
+            throttle = Math.min(prevThrottle, this._updateThrottleReset);
+        }
+
+        this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval);
+        this._lastUpdate = this.game.time.time;
+
+    },
+
+    /**
+    * Update method while paused.
+    *
+    * @method Phaser.ScaleManager#pauseUpdate
+    * @private
+    */
+    pauseUpdate: function () {
+
+        this.preUpdate();
+
+        // Updates at slowest.
+        this._updateThrottle = this.trackParentInterval;
+        
+    },
+
+    /**
+    * Update the dimensions taking the parent scaling factor into account.
+    *
+    * @method Phaser.ScaleManager#updateDimensions
+    * @private
+    * @param {number} width - The new width of the parent container.
+    * @param {number} height - The new height of the parent container.
+    * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars.
+    */
+    updateDimensions: function (width, height, resize) {
+
+        this.width = width * this.parentScaleFactor.x;
+        this.height = height * this.parentScaleFactor.y;
+
+        this.game.width = this.width;
+        this.game.height = this.height;
+
+        this.sourceAspectRatio = this.width / this.height;
+        this.updateScalingAndBounds();
+
+        if (resize)
+        {
+            //  Resize the renderer (which in turn resizes the Display canvas!)
+            this.game.renderer.resize(this.width, this.height);
+
+            //  The Camera can never be smaller than the Game size
+            this.game.camera.setSize(this.width, this.height);
+
+            //  This should only happen if the world is smaller than the new canvas size
+            this.game.world.resize(this.width, this.height);
+        }
+
+    },
+
+    /**
+    * Update relevant scaling values based on the ScaleManager dimension and game dimensions,
+    * which should already be set. This does not change {@link #sourceAspectRatio}.
+    * 
+    * @method Phaser.ScaleManager#updateScalingAndBounds
+    * @private
+    */
+    updateScalingAndBounds: function () {
+
+        this.scaleFactor.x = this.game.width / this.width;
+        this.scaleFactor.y = this.game.height / this.height;
+
+        this.scaleFactorInversed.x = this.width / this.game.width;
+        this.scaleFactorInversed.y = this.height / this.game.height;
+
+        this.aspectRatio = this.width / this.height;
+
+        // This can be invoked in boot pre-canvas
+        if (this.game.canvas)
+        {
+            this.dom.getOffset(this.game.canvas, this.offset);
+        }
+
+        this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
+
+        // Can be invoked in boot pre-input
+        if (this.game.input && this.game.input.scale)
+        {
+            this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y);
+        }
+
+    },
+
+    /**
+    * Force the game to run in only one orientation.
+    *
+    * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation.
+    *
+    * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor
+    * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the 
+    * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'`
+    * 
+    * @method Phaser.ScaleManager#forceOrientation
+    * @public
+    * @param {boolean} forceLandscape - true if the game should run in landscape mode only.
+    * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
+    */
+    forceOrientation: function (forceLandscape, forcePortrait) {
+
+        if (forcePortrait === undefined) { forcePortrait = false; }
+
+        this.forceLandscape = forceLandscape;
+        this.forcePortrait = forcePortrait;
+
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * Classify the orientation, per `getScreenOrientation`.
+    * 
+    * @method Phaser.ScaleManager#classifyOrientation
+    * @private
+    * @param {string} orientation - The orientation string, e.g. 'portrait-primary'.
+    * @return {?string} The classified orientation: 'portrait', 'landscape`, or null.
+    */
+    classifyOrientation: function (orientation) {
+
+        if (orientation === 'portrait-primary' || orientation === 'portrait-secondary')
+        {
+            return 'portrait';
+        }
+        else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary')
+        {
+            return 'landscape';
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Updates the current orientation and dispatches orientation change events.
+    * 
+    * @method Phaser.ScaleManager#updateOrientationState
+    * @private
+    * @return {boolean} True if the orientation state changed which means a forced update is likely required.
+    */
+    updateOrientationState: function () {
+
+        var previousOrientation = this.screenOrientation;
+        var previouslyIncorrect = this.incorrectOrientation;
+        
+        this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
+
+        this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) ||
+            (this.forcePortrait && !this.isPortrait);
+
+        var changed = previousOrientation !== this.screenOrientation;
+        var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation;
+
+        if (correctnessChanged)
+        {
+            if (this.incorrectOrientation)
+            {
+                this.enterIncorrectOrientation.dispatch();
+            }
+            else
+            {
+                this.leaveIncorrectOrientation.dispatch();
+            }
+        }
+
+        if (changed || correctnessChanged)
+        {
+            this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect);
+        }
+
+        return changed || correctnessChanged;
+
+    },
+
+    /**
+    * window.orientationchange event handler.
+    * 
+    * @method Phaser.ScaleManager#orientationChange
+    * @private
+    * @param {Event} event - The orientationchange event data.
+    */
+    orientationChange: function (event) {
+
+        this.event = event;
+
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * window.resize event handler.
+    * 
+    * @method Phaser.ScaleManager#windowResize
+    * @private
+    * @param {Event} event - The resize event data.
+    */
+    windowResize: function (event) {
+
+        this.event = event;
+
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * Scroll to the top - in some environments. See `compatibility.scrollTo`.
+    * 
+    * @method Phaser.ScaleManager#scrollTop
+    * @private
+    */
+    scrollTop: function () {
+
+        var scrollTo = this.compatibility.scrollTo;
+
+        if (scrollTo)
+        {
+            window.scrollTo(scrollTo.x, scrollTo.y);
+        }
+
+    },
+
+    /**
+    * The "refresh" methods informs the ScaleManager that a layout refresh is required.
+    *
+    * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout)
+    * when the browser is resized, the orientation changes, or when there is a detected change
+    * of the Parent size. Refreshing is also done automatically when public properties,
+    * such as {@link #scaleMode}, are updated or state-changing methods are invoked.
+    *
+    * The "refresh" method _may_ need to be used in a few (rare) situtations when
+    *
+    * - a device change event is not correctly detected; or
+    * - the Parent size changes (and an immediate reflow is desired); or
+    * - the ScaleManager state is updated by non-standard means; or
+    * - certain {@link #compatibility} properties are manually changed.
+    *
+    * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`.
+    * 
+    * @method Phaser.ScaleManager#refresh
+    * @public
+    */
+    refresh: function () {
+
+        this.scrollTop();
+        this.queueUpdate(true);
+
+    },
+
+    /**
+    * Updates the game / canvas position and size.
+    *
+    * @method Phaser.ScaleManager#updateLayout
+    * @private
+    */
+    updateLayout: function () {
+
+        var scaleMode = this.currentScaleMode;
+
+        if (scaleMode === Phaser.ScaleManager.RESIZE)
+        {
+            this.reflowGame();
+            return;
+        }
+
+        this.scrollTop();
+
+        if (this.compatibility.forceMinimumDocumentHeight)
+        {
+            // (This came from older code, by why is it here?)
+            // Set minimum height of content to new window height
+            document.documentElement.style.minHeight = window.innerHeight + 'px';
+        }
+        
+        if (this.incorrectOrientation)
+        {
+            this.setMaximum();
+        }
+        else
+        {
+            if (scaleMode === Phaser.ScaleManager.EXACT_FIT)
+            {
+                this.setExactFit();
+            }
+            else if (scaleMode === Phaser.ScaleManager.SHOW_ALL)
+            {
+                if (!this.isFullScreen && this.boundingParent &&
+                    this.compatibility.canExpandParent)
+                {
+                    // Try to expand parent out, but choosing maximizing dimensions.                    
+                    // Then select minimize dimensions which should then honor parent
+                    // maximum bound applications.
+                    this.setShowAll(true);
+                    this.resetCanvas();
+                    this.setShowAll();
+                }
+                else
+                {
+                    this.setShowAll();
+                }
+            }
+            else if (scaleMode === Phaser.ScaleManager.NO_SCALE)
+            {
+                this.width = this.game.width;
+                this.height = this.game.height;
+            }
+            else if (scaleMode === Phaser.ScaleManager.USER_SCALE)
+            {
+                this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x;
+                this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y;
+            }
+        }
+
+        if (!this.compatibility.canExpandParent &&
+            (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE))
+        {
+            var bounds = this.getParentBounds(this._tempBounds);
+            this.width = Math.min(this.width, bounds.width);
+            this.height = Math.min(this.height, bounds.height);
+        }
+
+        // Always truncate / force to integer
+        this.width = this.width | 0;
+        this.height = this.height | 0;
+
+        this.reflowCanvas();
+
+    },
+
+    /**
+    * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill.
+    *
+    * If in fullscreen mode or without parent (see {@link #parentIsWindow}),
+    * this will be the bounds of the visual viewport itself.
+    *
+    * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside
+    * the viewport then this function may return a smaller than expected size.
+    *
+    * Values are rounded to the nearest pixel.
+    *
+    * @method Phaser.ScaleManager#getParentBounds
+    * @protected
+    * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed.
+    * @return {Phaser.Rectangle} The established parent bounds.
+    */
+    getParentBounds: function (target) {
+
+        var bounds = target || new Phaser.Rectangle();
+        var parentNode = this.boundingParent;
+        var visualBounds = this.dom.visualBounds;
+        var layoutBounds = this.dom.layoutBounds;
+
+        if (!parentNode)
+        {
+            bounds.setTo(0, 0, visualBounds.width, visualBounds.height);
+        }
+        else
+        {
+            // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect
+            var clientRect = parentNode.getBoundingClientRect();
+
+            bounds.setTo(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
+
+            var wc = this.windowConstraints;
+
+            if (wc.right)
+            {
+                var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds;
+                bounds.right = Math.min(bounds.right, windowBounds.width);
+            }
+
+            if (wc.bottom)
+            {
+                var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds;
+                bounds.bottom = Math.min(bounds.bottom, windowBounds.height);
+            }
+        }
+
+        bounds.setTo(
+            Math.round(bounds.x), Math.round(bounds.y),
+            Math.round(bounds.width), Math.round(bounds.height));
+
+        return bounds;
+
+    },
+
+    /**
+    * Update the canvas position/margins - for alignment within the parent container.
+    *
+    * The canvas margins _must_ be reset/cleared prior to invoking this.
+    *
+    * @method Phaser.ScaleManager#alignCanvas
+    * @private
+    * @param {boolean} horizontal - Align horizontally?
+    * @param {boolean} vertical - Align vertically?
+    */
+    alignCanvas: function (horizontal, vertical) {
+
+        var parentBounds = this.getParentBounds(this._tempBounds);
+        var canvas = this.game.canvas;
+        var margin = this.margin;
+
+        if (horizontal)
+        {
+            margin.left = margin.right = 0;
+
+            var canvasBounds = canvas.getBoundingClientRect();
+
+            if (this.width < parentBounds.width && !this.incorrectOrientation)
+            {
+                var currentEdge = canvasBounds.left - parentBounds.x;
+                var targetEdge = (parentBounds.width / 2) - (this.width / 2);
+
+                targetEdge = Math.max(targetEdge, 0);
+
+                var offset = targetEdge - currentEdge;
+
+                margin.left = Math.round(offset);
+            }
+
+            canvas.style.marginLeft = margin.left + 'px';
+
+            if (margin.left !== 0)
+            {
+                margin.right = -(parentBounds.width - canvasBounds.width - margin.left);
+                canvas.style.marginRight = margin.right + 'px';
+            }
+        }
+
+        if (vertical)
+        {
+            margin.top = margin.bottom = 0;
+
+            var canvasBounds = canvas.getBoundingClientRect();
+            
+            if (this.height < parentBounds.height && !this.incorrectOrientation)
+            {
+                var currentEdge = canvasBounds.top - parentBounds.y;
+                var targetEdge = (parentBounds.height / 2) - (this.height / 2);
+
+                targetEdge = Math.max(targetEdge, 0);
+                
+                var offset = targetEdge - currentEdge;
+                margin.top = Math.round(offset);
+            }
+
+            canvas.style.marginTop = margin.top + 'px';
+
+            if (margin.top !== 0)
+            {
+                margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top);
+                canvas.style.marginBottom = margin.bottom + 'px';
+            }
+        }
+
+        // Silly backwards compatibility..
+        margin.x = margin.left;
+        margin.y = margin.top;
+
+    },
+
+    /**
+    * Updates the Game state / size.
+    *
+    * The canvas margins may always be adjusted, even if alignment is not in effect.
+    * 
+    * @method Phaser.ScaleManager#reflowGame
+    * @private
+    */
+    reflowGame: function () {
+
+        this.resetCanvas('', '');
+
+        var bounds = this.getParentBounds(this._tempBounds);
+        this.updateDimensions(bounds.width, bounds.height, true);
+
+    },
+
+    /**
+    * Updates the Display canvas size.
+    *
+    * The canvas margins may always be adjusted, even alignment is not in effect.
+    * 
+    * @method Phaser.ScaleManager#reflowCanvas
+    * @private
+    */
+    reflowCanvas: function () {
+
+        if (!this.incorrectOrientation)
+        {
+            this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width);
+            this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height);
+        }
+
+        this.resetCanvas();
+
+        if (!this.compatibility.noMargins)
+        {
+            if (this.isFullScreen && this._createdFullScreenTarget)
+            {
+                this.alignCanvas(true, true);
+            }
+            else
+            {
+                this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically);
+            }
+        }
+
+        this.updateScalingAndBounds();
+
+    },
+
+    /**
+    * "Reset" the Display canvas and set the specified width/height.
+    *
+    * @method Phaser.ScaleManager#resetCanvas
+    * @private
+    * @param {string} [cssWidth=(current width)] - The css width to set.
+    * @param {string} [cssHeight=(current height)] - The css height to set.
+    */
+    resetCanvas: function (cssWidth, cssHeight) {
+
+        if (cssWidth === undefined) { cssWidth = this.width + 'px'; }
+        if (cssHeight === undefined) { cssHeight = this.height + 'px'; }
+
+        var canvas = this.game.canvas;
+
+        if (!this.compatibility.noMargins)
+        {
+            canvas.style.marginLeft = '';
+            canvas.style.marginTop = '';
+            canvas.style.marginRight = '';
+            canvas.style.marginBottom = '';
+        }
+
+        canvas.style.width = cssWidth;
+        canvas.style.height = cssHeight;
+
+    },
+
+    /**
+    * Queues/marks a size/bounds check as needing to occur (from `preUpdate`).
+    *
+    * @method Phaser.ScaleManager#queueUpdate
+    * @private
+    * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty.
+    */
+    queueUpdate: function (force) {
+
+        if (force)
+        {
+            this._parentBounds.width = 0;
+            this._parentBounds.height = 0;
+        }
+
+        this._updateThrottle = this._updateThrottleReset;
+
+    },
+
+    /**
+    * Reset internal data/state.
+    *
+    * @method Phaser.ScaleManager#reset
+    * @private
+    */
+    reset: function (clearWorld) {
+
+        if (clearWorld)
+        {
+            this.grid.reset();
+        }
+
+    },
+
+    /**
+    * Updates the width/height to that of the window.
+    * 
+    * @method Phaser.ScaleManager#setMaximum
+    * @private
+    */
+    setMaximum: function () {
+
+        this.width = this.dom.visualBounds.width;
+        this.height = this.dom.visualBounds.height;
+
+    },
+
+    /**
+    * Updates the width/height such that the game is scaled proportionally.
+    * 
+    * @method Phaser.ScaleManager#setShowAll
+    * @private
+    * @param {boolean} expanding - If true then the maximizing dimension is chosen.
+    */
+    setShowAll: function (expanding) {
+
+        var bounds = this.getParentBounds(this._tempBounds);
+        var width = bounds.width;
+        var height = bounds.height;
+
+        var multiplier;
+
+        if (expanding)
+        {
+            multiplier = Math.max((height / this.game.height), (width / this.game.width));
+        }
+        else
+        {
+            multiplier = Math.min((height / this.game.height), (width / this.game.width));
+        }
+
+        this.width = Math.round(this.game.width * multiplier);
+        this.height = Math.round(this.game.height * multiplier);
+
+    },
+
+    /**
+    * Updates the width/height such that the game is stretched to the available size.
+    * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen.
+    *
+    * @method Phaser.ScaleManager#setExactFit
+    * @private
+    */
+    setExactFit: function () {
+
+        var bounds = this.getParentBounds(this._tempBounds);
+
+        this.width = bounds.width;
+        this.height = bounds.height;
+
+        if (this.isFullScreen)
+        {
+            // Max/min not honored fullscreen
+            return;
+        }
+
+        if (this.maxWidth)
+        {
+            this.width = Math.min(this.width, this.maxWidth);
+        }
+
+        if (this.maxHeight)
+        {
+            this.height = Math.min(this.height, this.maxHeight);
+        }
+
+    },
+
+    /**
+    * Creates a fullscreen target. This is called automatically as as needed when entering
+    * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}.
+    *
+    * Use {@link #onFullScreenInit} to customize the created object.
+    *
+    * @method Phaser.ScaleManager#createFullScreenTarget
+    * @protected
+    */
+    createFullScreenTarget: function () {
+
+        var fsTarget = document.createElement('div');
+
+        fsTarget.style.margin = '0';
+        fsTarget.style.padding = '0';
+        fsTarget.style.background = '#000';
+
+        return fsTarget;
+
+    },
+
+    /**
+    * Start the browsers fullscreen mode - this _must_ be called from a user input Pointer or Mouse event.
+    *
+    * The Fullscreen API must be supported by the browser for this to work - it is not the same as setting
+    * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current
+    * device is reported to support fullscreen mode.
+    *
+    * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API.
+    *
+    * @method Phaser.ScaleManager#startFullScreen
+    * @public
+    * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode.
+    * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed.
+    * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.)
+    */
+    startFullScreen: function (antialias, allowTrampoline) {
+
+        if (this.isFullScreen)
+        {
+            return false;
+        }
+
+        if (!this.compatibility.supportsFullScreen)
+        {
+            // Error is called in timeout to emulate the real fullscreenerror event better
+            var _this = this;
+            setTimeout(function () {
+                _this.fullScreenError();
+            }, 10);
+            return;
+        }
+
+        if (this.compatibility.clickTrampoline === 'when-not-mouse')
+        {
+            var input = this.game.input;
+
+            if (input.activePointer &&
+                input.activePointer !== input.mousePointer &&
+                (allowTrampoline || allowTrampoline !== false))
+            {
+                input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]);
+                return;
+            }
+        }
+
+        if (typeof antialias !== 'undefined' && this.game.renderType === Phaser.CANVAS)
+        {
+            this.game.stage.smoothed = antialias;
+        }
+
+        var fsTarget = this.fullScreenTarget;
+        
+        if (!fsTarget)
+        {
+            this.cleanupCreatedTarget();
+
+            this._createdFullScreenTarget = this.createFullScreenTarget();
+            fsTarget = this._createdFullScreenTarget;
+        }
+
+        var initData = {
+            targetElement: fsTarget
+        };
+
+        this.onFullScreenInit.dispatch(this, initData);
+
+        if (this._createdFullScreenTarget)
+        {
+            // Move the Display canvas inside of the target and add the target to the DOM
+            // (The target has to be added for the Fullscreen API to work.)
+            var canvas = this.game.canvas;
+            var parent = canvas.parentNode;
+            parent.insertBefore(fsTarget, canvas);
+            fsTarget.appendChild(canvas);
+        }
+
+        if (this.game.device.fullscreenKeyboard)
+        {
+            fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
+        }
+        else
+        {
+            fsTarget[this.game.device.requestFullscreen]();
+        }
+
+        return true;
+
+    },
+
+    /**
+    * Stops / exits fullscreen mode, if active.
+    *
+    * @method Phaser.ScaleManager#stopFullScreen
+    * @public
+    * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited.
+    */
+    stopFullScreen: function () {
+
+        if (!this.isFullScreen || !this.compatibility.supportsFullScreen)
+        {
+            return false;
+        }
+
+        document[this.game.device.cancelFullscreen]();
+
+        return true;
+
+    },
+
+    /**
+    * Cleans up the previous fullscreen target, if such was automatically created.
+    * This ensures the canvas is restored to its former parent, assuming the target didn't move.
+    *
+    * @method Phaser.ScaleManager#cleanupCreatedTarget
+    * @private
+    */
+    cleanupCreatedTarget: function () {
+
+        var fsTarget = this._createdFullScreenTarget;
+
+        if (fsTarget && fsTarget.parentNode)
+        {
+            // Make sure to cleanup synthetic target for sure;
+            // swap the canvas back to the parent.
+            var parent = fsTarget.parentNode;
+            parent.insertBefore(this.game.canvas, fsTarget);
+            parent.removeChild(fsTarget);
+        }
+
+        this._createdFullScreenTarget = null;
+
+    },
+
+    /**
+    * Used to prepare/restore extra fullscreen mode settings.
+    * (This does move any elements within the DOM tree.)
+    *
+    * @method Phaser.ScaleManager#prepScreenMode
+    * @private
+    * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_.
+    */
+    prepScreenMode: function (enteringFullscreen) {
+
+        var createdTarget = !!this._createdFullScreenTarget;
+        var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget;
+
+        if (enteringFullscreen)
+        {
+            if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
+            {
+                // Resize target, as long as it's not the canvas
+                if (fsTarget !== this.game.canvas)
+                {
+                    this._fullScreenRestore = {
+                        targetWidth: fsTarget.style.width,
+                        targetHeight: fsTarget.style.height
+                    };
+
+                    fsTarget.style.width = '100%';
+                    fsTarget.style.height = '100%';
+                }
+            }
+        }
+        else
+        {
+            // Have restore information
+            if (this._fullScreenRestore)
+            {
+                fsTarget.style.width = this._fullScreenRestore.targetWidth;
+                fsTarget.style.height = this._fullScreenRestore.targetHeight;
+
+                this._fullScreenRestore = null;
+            }
+
+            // Always reset to game size
+            this.updateDimensions(this._gameSize.width, this._gameSize.height, true);
+            this.resetCanvas();
+        }
+
+    },
+
+    /**
+    * Called automatically when the browser enters of leaves fullscreen mode.
+    *
+    * @method Phaser.ScaleManager#fullScreenChange
+    * @private
+    * @param {Event} [event=undefined] - The fullscreenchange event
+    */
+    fullScreenChange: function (event) {
+
+        this.event = event;
+
+        if (this.isFullScreen)
+        {
+            this.prepScreenMode(true);
+
+            this.updateLayout();
+            this.queueUpdate(true);
+
+            this.enterFullScreen.dispatch(this.width, this.height);
+        }
+        else
+        {
+            this.prepScreenMode(false);
+
+            this.cleanupCreatedTarget();
+
+            this.updateLayout();
+            this.queueUpdate(true);
+
+            this.leaveFullScreen.dispatch(this.width, this.height);
+        }
+
+        this.onFullScreenChange.dispatch(this);
+
+    },
+
+    /**
+    * Called automatically when the browser fullscreen request fails;
+    * or called when a fullscreen request is made on a device for which it is not supported.
+    *
+    * @method Phaser.ScaleManager#fullScreenError
+    * @private
+    * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API.
+    */
+    fullScreenError: function (event) {
+
+        this.event = event;
+
+        this.cleanupCreatedTarget();
+
+        console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API');
+
+        this.onFullScreenError.dispatch(this);
+
+    },
+
+    /**
+    * Takes a Sprite or Image object and scales it to fit the given dimensions.
+    * Scaling happens proportionally without distortion to the sprites texture.
+    * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the
+    * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either
+    * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite.
+    *
+    * @method Phaser.ScaleManager#scaleSprite
+    * @protected
+    * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale.
+    * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width.
+    * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height.
+    * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode.
+    * @return {Phaser.Sprite|Phaser.Image} The scaled sprite.
+    */
+    scaleSprite: function (sprite, width, height, letterBox) {
+
+        if (width === undefined) { width = this.width; }
+        if (height === undefined) { height = this.height; }
+        if (letterBox === undefined) { letterBox = false; }
+
+        if (!sprite || !sprite['scale'])
+        {
+            return sprite;
+        }
+
+        sprite.scale.x = 1;
+        sprite.scale.y = 1;
+
+        if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0))
+        {
+            return sprite;
+        }
+
+        var scaleX1 = width;
+        var scaleY1 = (sprite.height * width) / sprite.width;
+
+        var scaleX2 = (sprite.width * height) / sprite.height;
+        var scaleY2 = height;
+
+        var scaleOnWidth = (scaleX2 > width);
+
+        if (scaleOnWidth)
+        {
+            scaleOnWidth = letterBox;
+        }
+        else
+        {
+            scaleOnWidth = !letterBox;
+        }
+
+        if (scaleOnWidth)
+        {
+            sprite.width = Math.floor(scaleX1);
+            sprite.height = Math.floor(scaleY1);
+        }
+        else
+        {
+            sprite.width = Math.floor(scaleX2);
+            sprite.height = Math.floor(scaleY2);
+        }
+
+        //  Enable at some point?
+        // sprite.x = Math.floor((width - sprite.width) / 2);
+        // sprite.y = Math.floor((height - sprite.height) / 2);
+
+        return sprite;
+
+    },
+
+    /**
+    * Destroys the ScaleManager and removes any event listeners.
+    * This should probably only be called when the game is destroyed.
+    *
+    * @method Phaser.ScaleManager#destroy
+    * @protected
+    */
+    destroy: function () {
+
+        this.game.onResume.remove(this._gameResumed, this);
+
+        window.removeEventListener('orientationchange', this._orientationChange, false);
+        window.removeEventListener('resize', this._windowResize, false);
+
+        if (this.compatibility.supportsFullScreen)
+        {
+            document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false);
+            document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false);
+            document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false);
+            document.removeEventListener('fullscreenchange', this._fullScreenChange, false);
+
+            document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false);
+            document.removeEventListener('mozfullscreenerror', this._fullScreenError, false);
+            document.removeEventListener('MSFullscreenError', this._fullScreenError, false);
+            document.removeEventListener('fullscreenerror', this._fullScreenError, false);
+        }
+
+    }
+
+};
+
+Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
+
+/**
+* The DOM element that is considered the Parent bounding element, if any.
+*
+* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified.
+* It will also be null if there is no game canvas or if the game canvas has no parent.
+*
+* @name Phaser.ScaleManager#boundingParent
+* @property {?DOMElement} boundingParent
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", {
+
+    get: function () {
+        if (this.parentIsWindow ||
+            (this.isFullScreen && !this._createdFullScreenTarget))
+        {
+            return null;
+        }
+
+        var parentNode = this.game.canvas && this.game.canvas.parentNode;
+        return parentNode || null;
+    }
+
+});
+
+/**
+* The scaling method used by the ScaleManager when not in fullscreen.
+* 
+* <dl>
+*   <dt>{@link Phaser.ScaleManager.NO_SCALE}</dt>
+*   <dd>
+*       The Game display area will not be scaled - even if it is too large for the canvas/screen.
+*       This mode _ignores_ any applied scaling factor and displays the canvas at the Game size.
+*   </dd>
+*   <dt>{@link Phaser.ScaleManager.EXACT_FIT}</dt>
+*   <dd>
+*       The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen.
+*       Proportions are not mainted.
+*   </dd>
+*   <dt>{@link Phaser.ScaleManager.SHOW_ALL}</dt>
+*   <dd>
+*       Show the entire game display area while _maintaining_ the original aspect ratio.
+*   </dd>
+*   <dt>{@link Phaser.ScaleManager.RESIZE}</dt>
+*   <dd>
+*       The dimensions of the game display area are changed to match the size of the parent container.
+*       That is, this mode _changes the Game size_ to match the display size.
+*       <p>
+*       Any manually set Game size (see {@link #setGameSize}) is ignored while in effect.
+*   </dd>
+*   <dt>{@link Phaser.ScaleManager.USER_SCALE}</dt>
+*   <dd>
+*       The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}.
+*       <p>
+*       This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback}
+*       for flexible custom-sizing needs.
+*   </dd>
+* </dl>
+*
+* @name Phaser.ScaleManager#scaleMode
+* @property {integer} scaleMode
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", {
+
+    get: function () {
+
+        return this._scaleMode;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this._scaleMode)
+        {
+            if (!this.isFullScreen)
+            {
+                this.updateDimensions(this._gameSize.width, this._gameSize.height, true);
+                this.queueUpdate(true);
+            }
+
+            this._scaleMode = value;
+        }
+
+        return this._scaleMode;
+
+    }
+
+});
+
+/**
+* The scaling method used by the ScaleManager when in fullscreen.
+*
+* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed.
+*
+* @name Phaser.ScaleManager#fullScreenScaleMode
+* @property {integer} fullScreenScaleMode
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", {
+
+    get: function () {
+
+        return this._fullScreenScaleMode;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this._fullScreenScaleMode)
+        {
+            // If in fullscreen then need a wee bit more work
+            if (this.isFullScreen)
+            {
+                this.prepScreenMode(false);
+                this._fullScreenScaleMode = value;
+                this.prepScreenMode(true);
+
+                this.queueUpdate(true);
+            }
+            else
+            {
+                this._fullScreenScaleMode = value;
+            }
+        }
+
+        return this._fullScreenScaleMode;
+
+    }
+
+});
+
+/**
+* Returns the current scale mode - for normal or fullscreen operation.
+*
+* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed.
+*
+* @name Phaser.ScaleManager#currentScaleMode
+* @property {number} currentScaleMode
+* @protected
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", {
+
+    get: function () {
+
+        return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode;
+
+    }
+
+});
+
+/**
+* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}).
+*
+* To align horizontally across the page the Display canvas should be added directly to page;
+* or the parent container should itself be horizontally aligned.
+*
+* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode.
+*
+* @name Phaser.ScaleManager#pageAlignHorizontally
+* @property {boolean} pageAlignHorizontally
+* @default false
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", {
+
+    get: function () {
+
+        return this._pageAlignHorizontally;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this._pageAlignHorizontally)
+        {
+            this._pageAlignHorizontally = value;
+            this.queueUpdate(true);
+        }
+
+    }
+
+});
+
+/**
+* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}).
+*
+* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain
+* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically
+* _within_ the remaining available height dictated by the Parent element.
+*
+* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element.
+* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note).
+*
+* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height.
+* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true.
+*
+* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode.
+*
+* @name Phaser.ScaleManager#pageAlignVertically
+* @property {boolean} pageAlignVertically
+* @default false
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", {
+
+    get: function () {
+
+        return this._pageAlignVertically;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this._pageAlignVertically)
+        {
+            this._pageAlignVertically = value;
+            this.queueUpdate(true);
+        }
+
+    }
+
+});
+
+/**
+* Returns true if the browser is in fullscreen mode, otherwise false.
+* @name Phaser.ScaleManager#isFullScreen
+* @property {boolean} isFullScreen
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
+
+    get: function () {
+        return !!(document['fullscreenElement'] ||
+            document['webkitFullscreenElement'] ||
+            document['mozFullScreenElement'] ||
+            document['msFullscreenElement']);
+    }
+
+});
+
+/**
+* Returns true if the screen orientation is in portrait mode.
+*
+* @name Phaser.ScaleManager#isPortrait
+* @property {boolean} isPortrait
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
+
+    get: function () {
+        return this.classifyOrientation(this.screenOrientation) === 'portrait';
+    }
+
+});
+
+/**
+* Returns true if the screen orientation is in landscape mode.
+*
+* @name Phaser.ScaleManager#isLandscape
+* @property {boolean} isLandscape
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
+
+    get: function () {
+        return this.classifyOrientation(this.screenOrientation) === 'landscape';
+    }
+
+});
+
+/**
+* Returns true if the game dimensions are portrait (height > width).
+* This is especially useful to check when using the RESIZE scale mode 
+* but wanting to maintain game orientation on desktop browsers, 
+* where typically the screen orientation will always be landscape regardless of the browser viewport.
+*
+* @name Phaser.ScaleManager#isGamePortrait
+* @property {boolean} isGamePortrait
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", {
+
+    get: function () {
+        return (this.height > this.width);
+    }
+
+});
+
+/**
+* Returns true if the game dimensions are landscape (width > height).
+* This is especially useful to check when using the RESIZE scale mode 
+* but wanting to maintain game orientation on desktop browsers, 
+* where typically the screen orientation will always be landscape regardless of the browser viewport.
+*
+* @name Phaser.ScaleManager#isGameLandscape
+* @property {boolean} isGameLandscape
+* @readonly
+*/
+Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", {
+
+    get: function () {
+        return (this.width > this.height);
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* This is where the magic happens. The Game object is the heart of your game,
+* providing quick access to common functions and handling the boot process.
+* 
+* "Hell, there are no rules here - we're trying to accomplish something."
+*                                                       Thomas A. Edison
+*
+* @class Phaser.Game
+* @constructor
+* @param {number|string} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given.
+* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given.
+* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all).
+* @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
+* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
+* @param {boolean} [transparent=false] - Use a transparent canvas background or not.
+* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art.
+* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
+*/
+Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
+
+    /**
+    * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
+    * @readonly
+    */
+    this.id = Phaser.GAMES.push(this) - 1;
+
+    /**
+    * @property {object} config - The Phaser.Game configuration object.
+    */
+    this.config = null;
+
+    /**
+    * @property {object} physicsConfig - The Phaser.Physics.World configuration object.
+    */
+    this.physicsConfig = physicsConfig;
+
+    /**
+    * @property {string|HTMLElement} parent - The Games DOM parent.
+    * @default
+    */
+    this.parent = '';
+
+    /**
+    * The current Game Width in pixels.
+    *
+    * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
+    *
+    * @property {integer} width
+    * @readonly
+    * @default
+    */
+    this.width = 800;
+
+    /**
+    * The current Game Height in pixels.
+    *
+    * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
+    *
+    * @property {integer} height
+    * @readonly
+    * @default
+    */
+    this.height = 600;
+
+    /**
+    * The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object.
+    *
+    * @property {integer} resolution
+    * @readonly
+    * @default
+    */
+    this.resolution = 1;
+
+    /**
+    * @property {integer} _width - Private internal var.
+    * @private
+    */
+    this._width = 800;
+
+    /**
+    * @property {integer} _height - Private internal var.
+    * @private
+    */
+    this._height = 600;
+
+    /**
+    * @property {boolean} transparent - Use a transparent canvas background or not.
+    * @default
+    */
+    this.transparent = false;
+
+    /**
+    * @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
+    * @default
+    */
+    this.antialias = true;
+
+    /**
+    * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
+    * @default
+    */
+    this.preserveDrawingBuffer = false;
+
+    /**
+    * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
+    * @protected
+    */
+    this.renderer = null;
+
+    /**
+    * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
+    * @readonly
+    */
+    this.renderType = Phaser.AUTO;
+
+    /**
+    * @property {Phaser.StateManager} state - The StateManager.
+    */
+    this.state = null;
+
+    /**
+    * @property {boolean} isBooted - Whether the game engine is booted, aka available.
+    * @readonly
+    */
+    this.isBooted = false;
+
+    /**
+    * @property {boolean} isRunning - Is game running or paused?
+    * @readonly
+    */
+    this.isRunning = false;
+
+    /**
+    * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
+    * @protected
+    */
+    this.raf = null;
+
+    /**
+    * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
+    */
+    this.add = null;
+
+    /**
+    * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
+    */
+    this.make = null;
+
+    /**
+    * @property {Phaser.Cache} cache - Reference to the assets cache.
+    */
+    this.cache = null;
+
+    /**
+    * @property {Phaser.Input} input - Reference to the input manager
+    */
+    this.input = null;
+
+    /**
+    * @property {Phaser.Loader} load - Reference to the assets loader.
+    */
+    this.load = null;
+
+    /**
+    * @property {Phaser.Math} math - Reference to the math helper.
+    */
+    this.math = null;
+
+    /**
+    * @property {Phaser.Net} net - Reference to the network class.
+    */
+    this.net = null;
+
+    /**
+    * @property {Phaser.ScaleManager} scale - The game scale manager.
+    */
+    this.scale = null;
+
+    /**
+    * @property {Phaser.SoundManager} sound - Reference to the sound manager.
+    */
+    this.sound = null;
+
+    /**
+    * @property {Phaser.Stage} stage - Reference to the stage.
+    */
+    this.stage = null;
+
+    /**
+    * @property {Phaser.Time} time - Reference to the core game clock.
+    */
+    this.time = null;
+
+    /**
+    * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
+    */
+    this.tweens = null;
+
+    /**
+    * @property {Phaser.World} world - Reference to the world.
+    */
+    this.world = null;
+
+    /**
+    * @property {Phaser.Physics} physics - Reference to the physics manager.
+    */
+    this.physics = null;
+    
+    /**
+    * @property {Phaser.PluginManager} plugins - Reference to the plugin manager.
+    */
+    this.plugins = null;
+
+    /**
+    * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
+    */
+    this.rnd = null;
+
+    /**
+    * @property {Phaser.Device} device - Contains device information and capabilities.
+    */
+    this.device = Phaser.Device;
+
+    /**
+    * @property {Phaser.Camera} camera - A handy reference to world.camera.
+    */
+    this.camera = null;
+
+    /**
+    * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
+    */
+    this.canvas = null;
+
+    /**
+    * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
+    */
+    this.context = null;
+
+    /**
+    * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities.
+    */
+    this.debug = null;
+
+    /**
+    * @property {Phaser.Particles} particles - The Particle Manager.
+    */
+    this.particles = null;
+
+    /**
+    * @property {Phaser.Create} create - The Asset Generator.
+    */
+    this.create = null;
+
+    /**
+    * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped.
+    * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application.
+    * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
+    * @property {boolean} lockRender
+    * @default
+    */
+    this.lockRender = false;
+
+    /**
+    * @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
+    * @default
+    * @readonly
+    */
+    this.stepping = false;
+
+    /**
+    * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
+    * @default
+    * @readonly
+    */
+    this.pendingStep = false;
+
+    /**
+    * @property {number} stepCount - When stepping is enabled this contains the current step cycle.
+    * @default
+    * @readonly
+    */
+    this.stepCount = 0;
+
+    /**
+    * @property {Phaser.Signal} onPause - This event is fired when the game pauses.
+    */
+    this.onPause = null;
+
+    /**
+    * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
+    */
+    this.onResume = null;
+
+    /**
+    * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
+    */
+    this.onBlur = null;
+
+    /**
+    * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
+    */
+    this.onFocus = null;
+
+    /**
+    * @property {boolean} _paused - Is game paused?
+    * @private
+    */
+    this._paused = false;
+
+    /**
+    * @property {boolean} _codePaused - Was the game paused via code or a visibility change?
+    * @private
+    */
+    this._codePaused = false;
+
+    /**
+    * The ID of the current/last logic update applied this render frame, starting from 0.
+    * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.`
+    * @property {integer} currentUpdateID
+    * @protected
+    */
+    this.currentUpdateID = 0;
+
+    /**
+    * Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed).
+    * @property {integer} updatesThisFrame
+    * @protected
+    */
+    this.updatesThisFrame = 1;
+
+    /**
+    * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due.
+    * @private
+    */
+    this._deltaTime = 0;
+
+    /**
+    * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame.
+    * @private
+    */
+    this._lastCount = 0;
+
+    /**
+    * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented.
+    * @private
+    */
+    this._spiraling = 0;
+
+    /**
+    * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap)
+    * @private
+    */
+    this._kickstart = true;
+
+    /**
+    * If the game is struggling to maintain the desired FPS, this signal will be dispatched.
+    * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value.
+    * @property {Phaser.Signal} fpsProblemNotifier
+    * @public
+    */
+    this.fpsProblemNotifier = new Phaser.Signal();
+
+    /**
+    * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly.
+    */
+    this.forceSingleUpdate = false;
+
+    /**
+    * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched.
+    * @private
+    */
+    this._nextFpsNotification = 0;
+
+    //  Parse the configuration object (if any)
+    if (arguments.length === 1 && typeof arguments[0] === 'object')
+    {
+        this.parseConfig(arguments[0]);
+    }
+    else
+    {
+        this.config = { enableDebug: true };
+
+        if (typeof width !== 'undefined')
+        {
+            this._width = width;
+        }
+
+        if (typeof height !== 'undefined')
+        {
+            this._height = height;
+        }
+
+        if (typeof renderer !== 'undefined')
+        {
+            this.renderType = renderer;
+        }
+
+        if (typeof parent !== 'undefined')
+        {
+            this.parent = parent;
+        }
+
+        if (typeof transparent !== 'undefined')
+        {
+            this.transparent = transparent;
+        }
+
+        if (typeof antialias !== 'undefined')
+        {
+            this.antialias = antialias;
+        }
+
+        this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
+
+        this.state = new Phaser.StateManager(this, state);
+    }
+
+    this.device.whenReady(this.boot, this);
+
+    return this;
+
+};
+
+Phaser.Game.prototype = {
+
+    /**
+    * Parses a Game configuration object.
+    *
+    * @method Phaser.Game#parseConfig
+    * @protected
+    */
+    parseConfig: function (config) {
+
+        this.config = config;
+
+        if (config['enableDebug'] === undefined)
+        {
+            this.config.enableDebug = true;
+        }
+
+        if (config['width'])
+        {
+            this._width = config['width'];
+        }
+
+        if (config['height'])
+        {
+            this._height = config['height'];
+        }
+
+        if (config['renderer'])
+        {
+            this.renderType = config['renderer'];
+        }
+
+        if (config['parent'])
+        {
+            this.parent = config['parent'];
+        }
+
+        if (config['transparent'])
+        {
+            this.transparent = config['transparent'];
+        }
+
+        if (config['antialias'])
+        {
+            this.antialias = config['antialias'];
+        }
+
+        if (config['resolution'])
+        {
+            this.resolution = config['resolution'];
+        }
+
+        if (config['preserveDrawingBuffer'])
+        {
+            this.preserveDrawingBuffer = config['preserveDrawingBuffer'];
+        }
+
+        if (config['physicsConfig'])
+        {
+            this.physicsConfig = config['physicsConfig'];
+        }
+
+        var seed = [(Date.now() * Math.random()).toString()];
+
+        if (config['seed'])
+        {
+            seed = config['seed'];
+        }
+
+        this.rnd = new Phaser.RandomDataGenerator(seed);
+
+        var state = null;
+
+        if (config['state'])
+        {
+            state = config['state'];
+        }
+
+        this.state = new Phaser.StateManager(this, state);
+
+    },
+
+    /**
+    * Initialize engine sub modules and start the game.
+    *
+    * @method Phaser.Game#boot
+    * @protected
+    */
+    boot: function () {
+
+        if (this.isBooted)
+        {
+            return;
+        }
+
+        this.onPause = new Phaser.Signal();
+        this.onResume = new Phaser.Signal();
+        this.onBlur = new Phaser.Signal();
+        this.onFocus = new Phaser.Signal();
+
+        this.isBooted = true;
+
+        this.math = Phaser.Math;
+
+        this.scale = new Phaser.ScaleManager(this, this._width, this._height);
+        this.stage = new Phaser.Stage(this);
+
+        this.setUpRenderer();
+
+        this.world = new Phaser.World(this);
+        this.add = new Phaser.GameObjectFactory(this);
+        this.make = new Phaser.GameObjectCreator(this);
+        this.cache = new Phaser.Cache(this);
+        this.load = new Phaser.Loader(this);
+        this.time = new Phaser.Time(this);
+        this.tweens = new Phaser.TweenManager(this);
+        this.input = new Phaser.Input(this);
+        this.sound = new Phaser.SoundManager(this);
+        this.physics = new Phaser.Physics(this, this.physicsConfig);
+        this.particles = new Phaser.Particles(this);
+        this.create = new Phaser.Create(this);
+        this.plugins = new Phaser.PluginManager(this);
+        this.net = new Phaser.Net(this);
+
+        this.time.boot();
+        this.stage.boot();
+        this.world.boot();
+        this.scale.boot();
+        this.input.boot();
+        this.sound.boot();
+        this.state.boot();
+
+        if (this.config['enableDebug'])
+        {
+            this.debug = new Phaser.Utils.Debug(this);
+            this.debug.boot();
+        }
+        else
+        {
+            this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} };
+        }
+
+        this.showDebugHeader();
+
+        this.isRunning = true;
+
+        if (this.config && this.config['forceSetTimeOut'])
+        {
+            this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
+        }
+        else
+        {
+            this.raf = new Phaser.RequestAnimationFrame(this, false);
+        }
+
+        this._kickstart = true;
+
+        if (window['focus'])
+        {
+            if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus))
+            {
+                window.focus();
+            }
+        }
+
+        this.raf.start();
+
+    },
+
+    /**
+    * Displays a Phaser version debug header in the console.
+    *
+    * @method Phaser.Game#showDebugHeader
+    * @protected
+    */
+    showDebugHeader: function () {
+
+        if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner)
+        {
+            return;
+        }
+
+        var v = Phaser.VERSION;
+        var r = 'Canvas';
+        var a = 'HTML Audio';
+        var c = 1;
+
+        if (this.renderType === Phaser.WEBGL)
+        {
+            r = 'WebGL';
+            c++;
+        }
+        else if (this.renderType == Phaser.HEADLESS)
+        {
+            r = 'Headless';
+        }
+
+        if (this.device.webAudio)
+        {
+            a = 'WebAudio';
+            c++;
+        }
+
+        if (this.device.chrome)
+        {
+            var args = [
+                '%c %c %c Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + '  %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665',
+                'background: #9854d8',
+                'background: #6c2ca7',
+                'color: #ffffff; background: #450f78;',
+                'background: #6c2ca7',
+                'background: #9854d8',
+                'background: #ffffff'
+            ];
+
+            for (var i = 0; i < 3; i++)
+            {
+                if (i < c)
+                {
+                    args.push('color: #ff2424; background: #fff');
+                }
+                else
+                {
+                    args.push('color: #959595; background: #fff');
+                }
+            }
+
+            console.log.apply(console, args);
+        }
+        else if (window['console'])
+        {
+            console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io');
+        }
+
+    },
+
+    /**
+    * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
+    *
+    * @method Phaser.Game#setUpRenderer
+    * @protected
+    */
+    setUpRenderer: function () {
+
+        if (this.config['canvasID'])
+        {
+            this.canvas = Phaser.Canvas.create(this.width, this.height, this.config['canvasID']);
+        }
+        else
+        {
+            this.canvas = Phaser.Canvas.create(this.width, this.height);
+        }
+
+        if (this.config['canvasStyle'])
+        {
+            this.canvas.style = this.config['canvasStyle'];
+        }
+        else
+        {
+            this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
+        }
+
+        if (this.device.cocoonJS)
+        {
+            if (this.renderType === Phaser.CANVAS)
+            {
+                this.canvas.screencanvas = true;
+            }
+            else
+            {
+                // Some issue related to scaling arise with Cocoon using screencanvas and webgl renderer.
+                this.canvas.screencanvas = false;
+            }
+        }
+
+        if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL === false))
+        {
+            if (this.device.canvas)
+            {
+                if (this.renderType === Phaser.AUTO)
+                {
+                    this.renderType = Phaser.CANVAS;
+                }
+
+                this.renderer = new PIXI.CanvasRenderer(this.width, this.height, { "view": this.canvas,
+                                                                                    "transparent": this.transparent,
+                                                                                    "resolution": this.resolution,
+                                                                                    "clearBeforeRender": true });
+                this.context = this.renderer.context;
+            }
+            else
+            {
+                throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.');
+            }
+        }
+        else
+        {
+            //  They requested WebGL and their browser supports it
+            this.renderType = Phaser.WEBGL;
+
+            this.renderer = new PIXI.WebGLRenderer(this.width, this.height, { "view": this.canvas,
+                                                                                "transparent": this.transparent,
+                                                                                "resolution": this.resolution,
+                                                                                "antialias": this.antialias,
+                                                                                "preserveDrawingBuffer": this.preserveDrawingBuffer });
+            this.context = null;
+
+            this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false);
+            this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false);
+        }
+
+        if (this.renderType !== Phaser.HEADLESS)
+        {
+            this.stage.smoothed = this.antialias;
+            
+            Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
+            Phaser.Canvas.setTouchAction(this.canvas);
+        }
+
+    },
+
+    /**
+    * Handles WebGL context loss.
+    *
+    * @method Phaser.Game#contextLost
+    * @private
+    * @param {Event} event - The webglcontextlost event.
+    */
+    contextLost: function (event) {
+
+        event.preventDefault();
+
+        this.renderer.contextLost = true;
+
+    },
+
+    /**
+    * Handles WebGL context restoration.
+    *
+    * @method Phaser.Game#contextRestored
+    * @private
+    */
+    contextRestored: function () {
+
+        this.renderer.initContext();
+
+        this.cache.clearGLTextures();
+
+        this.renderer.contextLost = false;
+
+    },
+
+    /**
+    * The core game loop.
+    *
+    * @method Phaser.Game#update
+    * @protected
+    * @param {number} time - The current time as provided by RequestAnimationFrame.
+    */
+    update: function (time) {
+
+        this.time.update(time);
+
+        if (this._kickstart)
+        {
+            this.updateLogic(1.0 / this.time.desiredFps);
+
+            //  Sync the scene graph after _every_ logic update to account for moved game objects                
+            this.stage.updateTransform();
+
+            // call the game render update exactly once every frame
+            this.updateRender(this.time.slowMotion * this.time.desiredFps);
+
+            this._kickstart = false;
+
+            return;
+        }
+
+        // if the logic time is spiraling upwards, skip a frame entirely
+        if (this._spiraling > 1 && !this.forceSingleUpdate)
+        {
+            // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate
+            if (this.time.time > this._nextFpsNotification)
+            {
+                // only permit one fps notification per 10 seconds
+                this._nextFpsNotification = this.time.time + 1000 * 10;
+
+                // dispatch the notification signal
+                this.fpsProblemNotifier.dispatch();
+            }
+
+            // reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped
+            this._deltaTime = 0;
+            this._spiraling = 0;
+
+            // call the game render update exactly once every frame
+            this.updateRender(this.time.slowMotion * this.time.desiredFps);
+        }
+        else
+        {
+            // step size taking into account the slow motion speed
+            var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps;
+
+            // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals
+            this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0);
+
+            // call the game update logic multiple times if necessary to "catch up" with dropped frames
+            // unless forceSingleUpdate is true
+            var count = 0;
+
+            this.updatesThisFrame = Math.floor(this._deltaTime / slowStep);
+
+            if (this.forceSingleUpdate)
+            {
+                this.updatesThisFrame = Math.min(1, this.updatesThisFrame);
+            }
+
+            while (this._deltaTime >= slowStep)
+            {
+                this._deltaTime -= slowStep;
+                this.currentUpdateID = count;
+
+                this.updateLogic(1.0 / this.time.desiredFps);
+
+                //  Sync the scene graph after _every_ logic update to account for moved game objects
+                this.stage.updateTransform();
+
+                count++;
+
+                if (this.forceSingleUpdate && count === 1)
+                {
+                    break;
+                }
+            }
+
+            // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly)
+            if (count > this._lastCount)
+            {
+                this._spiraling++;
+            }
+            else if (count < this._lastCount)
+            {
+                // looks like it caught up successfully, reset the spiral alert counter
+                this._spiraling = 0;
+            }
+
+            this._lastCount = count;
+
+            // call the game render update exactly once every frame unless we're playing catch-up from a spiral condition
+            this.updateRender(this._deltaTime / slowStep);
+        }
+
+    },
+
+    /**
+    * Updates all logic subsystems in Phaser. Called automatically by Game.update.
+    *
+    * @method Phaser.Game#updateLogic
+    * @protected
+    * @param {number} timeStep - The current timeStep value as determined by Game.update.
+    */
+    updateLogic: function (timeStep) {
+
+        if (!this._paused && !this.pendingStep)
+        {
+            if (this.stepping)
+            {
+                this.pendingStep = true;
+            }
+
+            this.scale.preUpdate();
+            this.debug.preUpdate();
+            this.world.camera.preUpdate();
+            this.physics.preUpdate();
+            this.state.preUpdate(timeStep);
+            this.plugins.preUpdate(timeStep);
+            this.stage.preUpdate();
+
+            this.state.update();
+            this.stage.update();
+            this.tweens.update(timeStep);
+            this.sound.update();
+            this.input.update();
+            this.physics.update();
+            this.particles.update();
+            this.plugins.update();
+
+            this.stage.postUpdate();
+            this.plugins.postUpdate();
+        }
+        else
+        {
+            // Scaling and device orientation changes are still reflected when paused.
+            this.scale.pauseUpdate();
+            this.state.pauseUpdate();
+            this.debug.preUpdate();
+        }
+
+    },
+
+    /**
+    * Runs the Render cycle.
+    * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required.
+    * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down.
+    * It then calls plugin.render on any loaded plugins, in the order in which they were enabled.
+    * After this State.render is called. Any rendering that happens here will take place on-top of the display list.
+    * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled.
+    * This method is called automatically by Game.update, you don't need to call it directly.
+    * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean.
+    * Phaser will only render when this boolean is `false`.
+    *
+    * @method Phaser.Game#updateRender
+    * @protected
+    * @param {number} elapsedTime - The time elapsed since the last update.
+    */
+    updateRender: function (elapsedTime) {
+
+        if (this.lockRender)
+        {
+            return;
+        }
+
+        this.state.preRender(elapsedTime);
+        this.renderer.render(this.stage);
+
+        this.plugins.render(elapsedTime);
+        this.state.render(elapsedTime);
+        this.plugins.postRender(elapsedTime);
+
+    },
+
+    /**
+    * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
+    * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
+    *
+    * @method Phaser.Game#enableStep
+    */
+    enableStep: function () {
+
+        this.stepping = true;
+        this.pendingStep = false;
+        this.stepCount = 0;
+
+    },
+
+    /**
+    * Disables core game loop stepping.
+    *
+    * @method Phaser.Game#disableStep
+    */
+    disableStep: function () {
+
+        this.stepping = false;
+        this.pendingStep = false;
+
+    },
+
+    /**
+    * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
+    * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
+    *
+    * @method Phaser.Game#step
+    */
+    step: function () {
+
+        this.pendingStep = false;
+        this.stepCount++;
+
+    },
+
+    /**
+    * Nukes the entire game from orbit.
+    *
+    * @method Phaser.Game#destroy
+    */
+    destroy: function () {
+
+        this.raf.stop();
+
+        this.state.destroy();
+        this.sound.destroy();
+
+        this.scale.destroy();
+        this.stage.destroy();
+        this.input.destroy();
+        this.physics.destroy();
+
+        this.state = null;
+        this.cache = null;
+        this.input = null;
+        this.load = null;
+        this.sound = null;
+        this.stage = null;
+        this.time = null;
+        this.world = null;
+        this.isBooted = false;
+
+        this.renderer.destroy(false);
+        Phaser.Canvas.removeFromDOM(this.canvas);
+
+        Phaser.GAMES[this.id] = null;
+
+    },
+
+    /**
+    * Called by the Stage visibility handler.
+    *
+    * @method Phaser.Game#gamePaused
+    * @param {object} event - The DOM event that caused the game to pause, if any.
+    * @protected
+    */
+    gamePaused: function (event) {
+
+        //   If the game is already paused it was done via game code, so don't re-pause it
+        if (!this._paused)
+        {
+            this._paused = true;
+            this.time.gamePaused();
+            this.sound.setMute();
+            this.onPause.dispatch(event);
+
+            //  Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
+            if (this.device.cordova && this.device.iOS)
+            {
+                this.lockRender = true;
+            }
+        }
+
+    },
+
+    /**
+    * Called by the Stage visibility handler.
+    *
+    * @method Phaser.Game#gameResumed
+    * @param {object} event - The DOM event that caused the game to pause, if any.
+    * @protected
+    */
+    gameResumed: function (event) {
+
+        //  Game is paused, but wasn't paused via code, so resume it
+        if (this._paused && !this._codePaused)
+        {
+            this._paused = false;
+            this.time.gameResumed();
+            this.input.reset();
+            this.sound.unsetMute();
+            this.onResume.dispatch(event);
+
+            //  Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
+            if (this.device.cordova && this.device.iOS)
+            {
+                this.lockRender = false;
+            }
+        }
+
+    },
+
+    /**
+    * Called by the Stage visibility handler.
+    *
+    * @method Phaser.Game#focusLoss
+    * @param {object} event - The DOM event that caused the game to pause, if any.
+    * @protected
+    */
+    focusLoss: function (event) {
+
+        this.onBlur.dispatch(event);
+
+        if (!this.stage.disableVisibilityChange)
+        {
+            this.gamePaused(event);
+        }
+
+    },
+
+    /**
+    * Called by the Stage visibility handler.
+    *
+    * @method Phaser.Game#focusGain
+    * @param {object} event - The DOM event that caused the game to pause, if any.
+    * @protected
+    */
+    focusGain: function (event) {
+
+        this.onFocus.dispatch(event);
+
+        if (!this.stage.disableVisibilityChange)
+        {
+            this.gameResumed(event);
+        }
+
+    }
+
+};
+
+Phaser.Game.prototype.constructor = Phaser.Game;
+
+/**
+* The paused state of the Game. A paused game doesn't update any of its subsystems.
+* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
+* @name Phaser.Game#paused
+* @property {boolean} paused - Gets and sets the paused state of the Game.
+*/
+Object.defineProperty(Phaser.Game.prototype, "paused", {
+
+    get: function () {
+        return this._paused;
+    },
+
+    set: function (value) {
+
+        if (value === true)
+        {
+            if (this._paused === false)
+            {
+                this._paused = true;
+                this.sound.setMute();
+                this.time.gamePaused();
+                this.onPause.dispatch(this);
+            }
+            this._codePaused = true;
+        }
+        else
+        {
+            if (this._paused)
+            {
+                this._paused = false;
+                this.input.reset();
+                this.sound.unsetMute();
+                this.time.gameResumed();
+                this.onResume.dispatch(this);
+            }
+            this._codePaused = false;
+        }
+
+    }
+
+});
+
+/**
+ * 
+ * "Deleted code is debugged code." - Jeff Sickel
+ *
+ * ヽ(〃＾▽＾〃)ﾉ
+ * 
+*/
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
+* The Input manager is updated automatically by the core game loop.
+*
+* @class Phaser.Input
+* @constructor
+* @param {Phaser.Game} game - Current game instance.
+*/
+Phaser.Input = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
+    * @default
+    */
+    this.hitCanvas = null;
+
+    /**
+    * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
+    * @default
+    */
+    this.hitContext = null;
+
+    /**
+    * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM.
+    * To add a callback to this array please use `Input.addMoveCallback`.
+    * @property {array} moveCallbacks
+    * @protected
+    */
+    this.moveCallbacks = [];
+
+    /**
+    * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on.
+    * @default
+    */
+    this.pollRate = 0;
+
+    /**
+    * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves.
+    *
+    * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`.
+    * @property {boolean} enabled
+    * @default
+    */
+    this.enabled = true;
+
+    /**
+    * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device.
+    * @default
+    */
+    this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE;
+
+    /**
+    * @property {Phaser.Point} position - A point object representing the current position of the Pointer.
+    * @default
+    */
+    this.position = null;
+
+    /**
+    * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly.
+    */
+    this.speed = null;
+
+    /**
+    * A Circle object centered on the x/y screen coordinates of the Input.
+    * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
+    * @property {Phaser.Circle} circle
+    */
+    this.circle = null;
+
+    /**
+    * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1.
+    */
+    this.scale = null;
+
+    /**
+    * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1.
+    * @default -1 (Limited by total pointers.)
+    */
+    this.maxPointers = -1;
+
+    /**
+    * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click.
+    * @default
+    */
+    this.tapRate = 200;
+
+    /**
+    * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click.
+    * @default
+    */
+    this.doubleTapRate = 300;
+
+    /**
+    * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event.
+    * @default
+    */
+    this.holdRate = 2000;
+
+    /**
+    * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed.
+    * @default
+    */
+    this.justPressedRate = 200;
+
+    /**
+    * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased .
+    * @default
+    */
+    this.justReleasedRate = 200;
+
+    /**
+    * Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
+    * The history is cleared each time the Pointer is pressed down.
+    * The history is updated at the rate specified in Input.pollRate
+    * @property {boolean} recordPointerHistory
+    * @default
+    */
+    this.recordPointerHistory = false;
+
+    /**
+    * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history.
+    * @default
+    */
+    this.recordRate = 100;
+
+    /**
+    * The total number of entries that can be recorded into the Pointer objects tracking history.
+    * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history.
+    * @property {number} recordLimit
+    * @default
+    */
+    this.recordLimit = 100;
+
+    /**
+    * @property {Phaser.Pointer} pointer1 - A Pointer object.
+    */
+    this.pointer1 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer2 - A Pointer object.
+    */
+    this.pointer2 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer3 - A Pointer object.
+    */
+    this.pointer3 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer4 - A Pointer object.
+    */
+    this.pointer4 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer5 - A Pointer object.
+    */
+    this.pointer5 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer6 - A Pointer object.
+    */
+    this.pointer6 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer7 - A Pointer object.
+    */
+    this.pointer7 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer8 - A Pointer object.
+    */
+    this.pointer8 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer9 - A Pointer object.
+    */
+    this.pointer9 = null;
+
+    /**
+    * @property {Phaser.Pointer} pointer10 - A Pointer object.
+    */
+    this.pointer10 = null;
+
+    /**
+    * An array of non-mouse pointers that have been added to the game.
+    * The properties `pointer1..N` are aliases for `pointers[0..N-1]`.
+    * @property {Phaser.Pointer[]} pointers
+    * @public
+    * @readonly
+    */
+    this.pointers = [];
+
+    /**
+    * The most recently active Pointer object.
+    * 
+    * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
+    * 
+    * @property {Phaser.Pointer} activePointer
+    */
+    this.activePointer = null;
+
+    /**
+    * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
+    * 
+    * @property {Pointer} mousePointer
+    */
+    this.mousePointer = null;
+
+    /**
+    * The Mouse Input manager.
+    * 
+    * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer 
+    * which normalizes all the input values for you, regardless of browser.
+    * 
+    * @property {Phaser.Mouse} mouse
+    */
+    this.mouse = null;
+
+    /**
+    * The Keyboard Input manager.
+    * 
+    * @property {Phaser.Keyboard} keyboard
+    */
+    this.keyboard = null;
+
+    /**
+    * The Touch Input manager.
+    * 
+    * You should not usually access this manager directly, but instead use Input.activePointer 
+    * which normalizes all the input values for you, regardless of browser.
+    * 
+    * @property {Phaser.Touch} touch
+    */
+    this.touch = null;
+
+    /**
+    * The MSPointer Input manager.
+    * 
+    * You should not usually access this manager directly, but instead use Input.activePointer 
+    * which normalizes all the input values for you, regardless of browser.
+    * 
+    * @property {Phaser.MSPointer} mspointer
+    */
+    this.mspointer = null;
+
+    /**
+    * The Gamepad Input manager.
+    * 
+    * @property {Phaser.Gamepad} gamepad
+    */
+    this.gamepad = null;
+
+    /**
+    * If the Input Manager has been reset locked then all calls made to InputManager.reset, 
+    * such as from a State change, are ignored.
+    * @property {boolean} resetLocked
+    * @default
+    */
+    this.resetLocked = false;
+
+    /**
+    * A Signal that is dispatched each time a pointer is pressed down.
+    * @property {Phaser.Signal} onDown
+    */
+    this.onDown = null;
+
+    /**
+    * A Signal that is dispatched each time a pointer is released.
+    * @property {Phaser.Signal} onUp
+    */
+    this.onUp = null;
+
+    /**
+    * A Signal that is dispatched each time a pointer is tapped.
+    * @property {Phaser.Signal} onTap
+    */
+    this.onTap = null;
+
+    /**
+    * A Signal that is dispatched each time a pointer is held down.
+    * @property {Phaser.Signal} onHold
+    */
+    this.onHold = null;
+
+    /**
+    * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value.
+    * This is useful when stacking UI layers. Set to zero to disable.
+    * @property {number} minPriorityID
+    * @default
+    */
+    this.minPriorityID = 0;
+
+    /**
+    * A list of interactive objects. The InputHandler components add and remove themselves from this list.
+    * @property {Phaser.ArraySet} interactiveItems
+    */
+    this.interactiveItems = new Phaser.ArraySet();
+
+    /**
+    * @property {Phaser.Point} _localPoint - Internal cache var.
+    * @private
+    */
+    this._localPoint = new Phaser.Point();
+
+    /**
+    * @property {number} _pollCounter - Internal var holding the current poll counter.
+    * @private
+    */
+    this._pollCounter = 0;
+
+    /**
+    * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
+    * @private
+    */
+    this._oldPosition = null;
+
+    /**
+    * @property {number} _x - x coordinate of the most recent Pointer event
+    * @private
+    */
+    this._x = 0;
+
+    /**
+    * @property {number} _y - Y coordinate of the most recent Pointer event
+    * @private
+    */
+    this._y = 0;
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
+
+/**
+* The maximum number of pointers that can be added. This excludes the mouse pointer.
+* @constant
+* @type {integer}
+*/
+Phaser.Input.MAX_POINTERS = 10;
+
+Phaser.Input.prototype = {
+
+    /**
+    * Starts the Input Manager running.
+    *
+    * @method Phaser.Input#boot
+    * @protected
+    */
+    boot: function () {
+
+        this.mousePointer = new Phaser.Pointer(this.game, 0);
+        this.addPointer();
+        this.addPointer();
+
+        this.mouse = new Phaser.Mouse(this.game);
+        this.touch = new Phaser.Touch(this.game);
+        this.mspointer = new Phaser.MSPointer(this.game);
+
+        if (Phaser.Keyboard)
+        {
+            this.keyboard = new Phaser.Keyboard(this.game);
+        }
+
+        if (Phaser.Gamepad)
+        {
+            this.gamepad = new Phaser.Gamepad(this.game);
+        }
+
+        this.onDown = new Phaser.Signal();
+        this.onUp = new Phaser.Signal();
+        this.onTap = new Phaser.Signal();
+        this.onHold = new Phaser.Signal();
+
+        this.scale = new Phaser.Point(1, 1);
+        this.speed = new Phaser.Point();
+        this.position = new Phaser.Point();
+        this._oldPosition = new Phaser.Point();
+
+        this.circle = new Phaser.Circle(0, 0, 44);
+
+        this.activePointer = this.mousePointer;
+
+        this.hitCanvas = document.createElement('canvas');
+        this.hitCanvas.width = 1;
+        this.hitCanvas.height = 1;
+        this.hitContext = this.hitCanvas.getContext('2d');
+
+        this.mouse.start();
+        this.touch.start();
+        this.mspointer.start();
+        this.mousePointer.active = true;
+
+        if (this.keyboard)
+        {
+            this.keyboard.start();
+        }
+
+        var _this = this;
+
+        this._onClickTrampoline = function (event) {
+            _this.onClickTrampoline(event);
+        };
+
+        this.game.canvas.addEventListener('click', this._onClickTrampoline, false);
+
+    },
+
+    /**
+    * Stops all of the Input Managers from running.
+    *
+    * @method Phaser.Input#destroy
+    */
+    destroy: function () {
+
+        this.mouse.stop();
+        this.touch.stop();
+        this.mspointer.stop();
+
+        if (this.keyboard)
+        {
+            this.keyboard.stop();
+        }
+
+        if (this.gamepad)
+        {
+            this.gamepad.stop();
+        }
+
+        this.moveCallbacks = [];
+
+        this.game.canvas.removeEventListener('click', this._onClickTrampoline);
+
+    },
+
+    /**
+    * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
+    *
+    * The callback will be sent 4 parameters: The Pointer that moved, the x position of the pointer, the y position and the down state.
+    * 
+    * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best
+    * to only use if you've limited input to a single pointer (i.e. mouse or touch).
+    * 
+    * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback.
+    * 
+    * @method Phaser.Input#addMoveCallback
+    * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
+    * @param {object} context - The context in which the callback will be called.
+    */
+    addMoveCallback: function (callback, context) {
+
+        this.moveCallbacks.push({ callback: callback, context: context });
+
+    },
+
+    /**
+    * Removes the callback from the Phaser.Input.moveCallbacks array.
+    * 
+    * @method Phaser.Input#deleteMoveCallback
+    * @param {function} callback - The callback to be removed.
+    * @param {object} context - The context in which the callback exists.
+    */
+    deleteMoveCallback: function (callback, context) {
+
+        var i = this.moveCallbacks.length;
+
+        while (i--)
+        {
+            if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context)
+            {
+                this.moveCallbacks.splice(i, 1);
+                return;
+            }
+        }
+
+    },
+
+    /**
+    * Add a new Pointer object to the Input Manager.
+    * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`.
+    * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10).
+    *
+    * @method Phaser.Input#addPointer
+    * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added.
+    */
+    addPointer: function () {
+
+        if (this.pointers.length >= Phaser.Input.MAX_POINTERS)
+        {
+            console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached.");
+            return null;
+        }
+
+        var id = this.pointers.length + 1;
+        var pointer = new Phaser.Pointer(this.game, id);
+
+        this.pointers.push(pointer);
+        this['pointer' + id] = pointer;
+
+        return pointer;
+
+    },
+
+    /**
+    * Updates the Input Manager. Called by the core Game loop.
+    * 
+    * @method Phaser.Input#update
+    * @protected
+    */
+    update: function () {
+
+        if (this.keyboard)
+        {
+            this.keyboard.update();
+        }
+
+        if (this.pollRate > 0 && this._pollCounter < this.pollRate)
+        {
+            this._pollCounter++;
+            return;
+        }
+
+        this.speed.x = this.position.x - this._oldPosition.x;
+        this.speed.y = this.position.y - this._oldPosition.y;
+
+        this._oldPosition.copyFrom(this.position);
+        this.mousePointer.update();
+
+        if (this.gamepad && this.gamepad.active)
+        {
+            this.gamepad.update();
+        }
+
+        for (var i = 0; i < this.pointers.length; i++)
+        {
+            this.pointers[i].update();
+        }
+
+        this._pollCounter = 0;
+
+    },
+
+    /**
+    * Reset all of the Pointers and Input states.
+    *
+    * The optional `hard` parameter will reset any events or callbacks that may be bound.
+    * Input.reset is called automatically during a State change or if a game loses focus / visibility.
+    * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`.
+    *
+    * @method Phaser.Input#reset
+    * @public
+    * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will.
+    */
+    reset: function (hard) {
+
+        if (!this.game.isBooted || this.resetLocked)
+        {
+            return;
+        }
+
+        if (hard === undefined) { hard = false; }
+
+        this.mousePointer.reset();
+
+        if (this.keyboard)
+        {
+            this.keyboard.reset(hard);
+        }
+
+        if (this.gamepad)
+        {
+            this.gamepad.reset();
+        }
+
+        for (var i = 0; i < this.pointers.length; i++)
+        {
+            this.pointers[i].reset();
+        }
+
+        if (this.game.canvas.style.cursor !== 'none')
+        {
+            this.game.canvas.style.cursor = 'inherit';
+        }
+
+        if (hard)
+        {
+            this.onDown.dispose();
+            this.onUp.dispose();
+            this.onTap.dispose();
+            this.onHold.dispose();
+            this.onDown = new Phaser.Signal();
+            this.onUp = new Phaser.Signal();
+            this.onTap = new Phaser.Signal();
+            this.onHold = new Phaser.Signal();
+            this.moveCallbacks = [];
+        }
+
+        this._pollCounter = 0;
+
+    },
+
+    /**
+    * Resets the speed and old position properties.
+    *
+    * @method Phaser.Input#resetSpeed
+    * @param {number} x - Sets the oldPosition.x value.
+    * @param {number} y - Sets the oldPosition.y value.
+    */
+    resetSpeed: function (x, y) {
+
+        this._oldPosition.setTo(x, y);
+        this.speed.setTo(0, 0);
+
+    },
+
+    /**
+    * Find the first free Pointer object and start it, passing in the event data.
+    * This is called automatically by Phaser.Touch and Phaser.MSPointer.
+    *
+    * @method Phaser.Input#startPointer
+    * @protected
+    * @param {any} event - The event data from the Touch event.
+    * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
+    */
+    startPointer: function (event) {
+
+        if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers)
+        {
+            return null;
+        }
+
+        if (!this.pointer1.active)
+        {
+            return this.pointer1.start(event);
+        }
+
+        if (!this.pointer2.active)
+        {
+            return this.pointer2.start(event);
+        }
+
+        for (var i = 2; i < this.pointers.length; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (!pointer.active)
+            {
+                return pointer.start(event);
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Updates the matching Pointer object, passing in the event data.
+    * This is called automatically and should not normally need to be invoked.
+    *
+    * @method Phaser.Input#updatePointer
+    * @protected
+    * @param {any} event - The event data from the Touch event.
+    * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated.
+    */
+    updatePointer: function (event) {
+
+        if (this.pointer1.active && this.pointer1.identifier === event.identifier)
+        {
+            return this.pointer1.move(event);
+        }
+
+        if (this.pointer2.active && this.pointer2.identifier === event.identifier)
+        {
+            return this.pointer2.move(event);
+        }
+
+        for (var i = 2; i < this.pointers.length; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (pointer.active && pointer.identifier === event.identifier)
+            {
+                return pointer.move(event);
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Stops the matching Pointer object, passing in the event data.
+    *
+    * @method Phaser.Input#stopPointer
+    * @protected
+    * @param {any} event - The event data from the Touch event.
+    * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
+    */
+    stopPointer: function (event) {
+
+        if (this.pointer1.active && this.pointer1.identifier === event.identifier)
+        {
+            return this.pointer1.stop(event);
+        }
+
+        if (this.pointer2.active && this.pointer2.identifier === event.identifier)
+        {
+            return this.pointer2.stop(event);
+        }
+
+        for (var i = 2; i < this.pointers.length; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (pointer.active && pointer.identifier === event.identifier)
+            {
+                return pointer.stop(event);
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Returns the total number of active pointers, not exceeding the specified limit
+    *
+    * @name Phaser.Input#countActivePointers
+    * @private
+    * @property {integer} [limit=(max pointers)] - Stop counting after this.
+    * @return {integer} The number of active pointers, or limit - whichever is less.
+    */
+    countActivePointers: function (limit) {
+
+        if (limit === undefined) { limit = this.pointers.length; }
+
+        var count = limit;
+
+        for (var i = 0; i < this.pointers.length && count > 0; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (pointer.active)
+            {
+                count--;
+            }
+        }
+
+        return (limit - count);
+
+    },
+
+    /**
+    * Get the first Pointer with the given active state.
+    *
+    * @method Phaser.Input#getPointer
+    * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive?
+    * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
+    */
+    getPointer: function (isActive) {
+
+        if (isActive === undefined) { isActive = false; }
+
+        for (var i = 0; i < this.pointers.length; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (pointer.active === isActive)
+            {
+                return pointer;
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Get the Pointer object whos `identifier` property matches the given identifier value.
+    *
+    * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event.
+    * Also it can change every time you press the pointer down, and is not fixed once set.
+    * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead.
+    *
+    * @method Phaser.Input#getPointerFromIdentifier
+    * @param {number} identifier - The Pointer.identifier value to search for.
+    * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
+    */
+    getPointerFromIdentifier: function (identifier) {
+
+        for (var i = 0; i < this.pointers.length; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (pointer.identifier === identifier)
+            {
+                return pointer;
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Get the Pointer object whos `pointerId` property matches the given value.
+    *
+    * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event.
+    * Also it can change every time you press the pointer down if the browser recycles it.
+    *
+    * @method Phaser.Input#getPointerFromId
+    * @param {number} pointerId - The `pointerId` (not 'id') value to search for.
+    * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
+    */
+    getPointerFromId: function (pointerId) {
+
+        for (var i = 0; i < this.pointers.length; i++)
+        {
+            var pointer = this.pointers[i];
+
+            if (pointer.pointerId === pointerId)
+            {
+                return pointer;
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * This will return the local coordinates of the specified displayObject based on the given Pointer.
+    *
+    * @method Phaser.Input#getLocalPosition
+    * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for.
+    * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject.
+    * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject.
+    */
+    getLocalPosition: function (displayObject, pointer, output) {
+
+        if (output === undefined) { output = new Phaser.Point(); }
+
+        var wt = displayObject.worldTransform;
+        var id = 1 / (wt.a * wt.d + wt.c * -wt.b);
+
+        return output.setTo(
+            wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id,
+            wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id
+        );
+
+    },
+
+    /**
+    * Tests if the pointer hits the given object.
+    *
+    * @method Phaser.Input#hitTest
+    * @param {DisplayObject} displayObject - The displayObject to test for a hit.
+    * @param {Phaser.Pointer} pointer - The pointer to use for the test.
+    * @param {Phaser.Point} localPoint - The local translated point.
+    */
+    hitTest: function (displayObject, pointer, localPoint) {
+
+        if (!displayObject.worldVisible)
+        {
+            return false;
+        }
+
+        this.getLocalPosition(displayObject, pointer, this._localPoint);
+
+        localPoint.copyFrom(this._localPoint);
+
+        if (displayObject.hitArea && displayObject.hitArea.contains)
+        {
+            return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y));
+        }
+        else if (displayObject instanceof Phaser.TileSprite)
+        {
+            var width = displayObject.width;
+            var height = displayObject.height;
+            var x1 = -width * displayObject.anchor.x;
+
+            if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width)
+            {
+                var y1 = -height * displayObject.anchor.y;
+
+                if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height)
+                {
+                    return true;
+                }
+            }
+        }
+        else if (displayObject instanceof PIXI.Sprite)
+        {
+            var width = displayObject.texture.frame.width;
+            var height = displayObject.texture.frame.height;
+            var x1 = -width * displayObject.anchor.x;
+
+            if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width)
+            {
+                var y1 = -height * displayObject.anchor.y;
+
+                if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height)
+                {
+                    return true;
+                }
+            }
+        }
+        else if (displayObject instanceof Phaser.Graphics)
+        {
+            for (var i = 0; i < displayObject.graphicsData.length; i++)
+            {
+                var data = displayObject.graphicsData[i];
+
+                if (!data.fill)
+                {
+                    continue;
+                }
+
+                //  Only deal with fills..
+                if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y))
+                {
+                    return true;
+                }
+            }
+        }
+
+        //  Didn't hit the parent, does it have any children?
+
+        for (var i = 0, len = displayObject.children.length; i < len; i++)
+        {
+            if (this.hitTest(displayObject.children[i], pointer, localPoint))
+            {
+                return true;
+            }
+        }
+
+        return false;
+    },
+
+    /**
+    * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}.
+    *
+    * @method Phaser.Input#onClickTrampoline
+    * @private
+    */
+    onClickTrampoline: function () {
+
+        // It might not always be the active pointer, but this does work on
+        // Desktop browsers (read: IE) with Mouse or MSPointer input.
+        this.activePointer.processClickTrampolines();
+
+    }
+
+};
+
+Phaser.Input.prototype.constructor = Phaser.Input;
+
+/**
+* The X coordinate of the most recently active pointer.
+* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
+* @name Phaser.Input#x
+* @property {number} x
+*/
+Object.defineProperty(Phaser.Input.prototype, "x", {
+
+    get: function () {
+        return this._x;
+    },
+
+    set: function (value) {
+        this._x = Math.floor(value);
+    }
+
+});
+
+/**
+* The Y coordinate of the most recently active pointer.
+* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
+* @name Phaser.Input#y
+* @property {number} y
+*/
+Object.defineProperty(Phaser.Input.prototype, "y", {
+
+    get: function () {
+        return this._y;
+    },
+
+    set: function (value) {
+        this._y = Math.floor(value);
+    }
+
+});
+
+/**
+* True if the Input is currently poll rate locked.
+* @name Phaser.Input#pollLocked
+* @property {boolean} pollLocked
+* @readonly
+*/
+Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
+
+    get: function () {
+        return (this.pollRate > 0 && this._pollCounter < this.pollRate);
+    }
+
+});
+
+/**
+* The total number of inactive Pointers.
+* @name Phaser.Input#totalInactivePointers
+* @property {number} totalInactivePointers
+* @readonly
+*/
+Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
+
+    get: function () {
+        return this.pointers.length - this.countActivePointers();
+    }
+
+});
+
+/**
+* The total number of active Pointers, not counting the mouse pointer.
+* @name Phaser.Input#totalActivePointers
+* @property {integers} totalActivePointers
+* @readonly
+*/
+Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
+
+    get: function () {
+        return this.countActivePointers();
+    }
+
+});
+
+/**
+* The world X coordinate of the most recently active pointer.
+* @name Phaser.Input#worldX
+* @property {number} worldX - The world X coordinate of the most recently active pointer.
+* @readonly
+*/
+Object.defineProperty(Phaser.Input.prototype, "worldX", {
+
+    get: function () {
+        return this.game.camera.view.x + this.x;
+    }
+
+});
+
+/**
+* The world Y coordinate of the most recently active pointer.
+* @name Phaser.Input#worldY
+* @property {number} worldY - The world Y coordinate of the most recently active pointer.
+* @readonly
+*/
+Object.defineProperty(Phaser.Input.prototype, "worldY", {
+
+    get: function () {
+        return this.game.camera.view.y + this.y;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Mouse class is responsible for handling all aspects of mouse interaction with the browser.
+*
+* It captures and processes mouse events that happen on the game canvas object.
+* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released 
+* when not over the game.
+*
+* You should not normally access this class directly, but instead use a Phaser.Pointer object 
+* which normalises all game input for you, including accurate button handling.
+*
+* @class Phaser.Mouse
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Mouse = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Input} input - A reference to the Phaser Input Manager.
+    * @protected
+    */
+    this.input = game.input;
+
+    /**
+    * @property {object} callbackContext - The context under which callbacks are called.
+    */
+    this.callbackContext = this.game;
+
+    /**
+    * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
+    */
+    this.mouseDownCallback = null;
+
+    /**
+    * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
+    */
+    this.mouseUpCallback = null;
+
+    /**
+    * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas.
+    */
+    this.mouseOutCallback = null;
+
+    /**
+    * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout).
+    */
+    this.mouseOverCallback = null;
+
+    /**
+     * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used.
+     */
+    this.mouseWheelCallback = null;
+
+    /**
+    * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully.
+    */
+    this.capture = false;
+
+    /**
+    * This property was removed in Phaser 2.4 and should no longer be used.
+    * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on.
+    * Or Pointer.button holds the DOM event button value if you require that.
+    * @property {number} button
+    * @default
+    */
+    this.button = -1;
+
+    /**
+     * The direction of the _last_ mousewheel usage 1 for up -1 for down.
+     * @property {number} wheelDelta
+     */
+    this.wheelDelta = 0;
+
+    /**
+    * Mouse input will only be processed if enabled.
+    * @property {boolean} enabled
+    * @default
+    */
+    this.enabled = true;
+
+    /**
+    * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
+    * @default
+    */
+    this.locked = false;
+
+    /**
+    * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas.
+    * @default
+    */
+    this.stopOnGameOut = false;
+
+    /**
+    * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
+    * @default
+    */
+    this.pointerLock = new Phaser.Signal();
+
+    /**
+    * The browser mouse DOM event. Will be null if no mouse event has ever been received.
+    * Access this property only inside a Mouse event handler and do not keep references to it.
+    * @property {MouseEvent|null} event
+    * @default
+    */
+    this.event = null;
+
+    /**
+    * @property {function} _onMouseDown - Internal event handler reference.
+    * @private
+    */
+    this._onMouseDown = null;
+
+    /**
+    * @property {function} _onMouseMove - Internal event handler reference.
+    * @private
+    */
+    this._onMouseMove = null;
+
+    /**
+    * @property {function} _onMouseUp - Internal event handler reference.
+    * @private
+    */
+    this._onMouseUp = null;
+
+    /**
+    * @property {function} _onMouseOut - Internal event handler reference.
+    * @private
+    */
+    this._onMouseOut = null;
+
+    /**
+    * @property {function} _onMouseOver - Internal event handler reference.
+    * @private
+    */
+    this._onMouseOver = null;
+
+    /**
+    * @property {function} _onMouseWheel - Internal event handler reference.
+    * @private
+    */
+    this._onMouseWheel = null;
+
+    /**
+    * Wheel proxy event object, if required. Shared for all wheel events for this mouse.
+    * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent
+    * @private
+    */
+    this._wheelEvent = null;
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Mouse.NO_BUTTON = -1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Mouse.LEFT_BUTTON = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Mouse.MIDDLE_BUTTON = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Mouse.RIGHT_BUTTON = 2;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Mouse.BACK_BUTTON = 3;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Mouse.FORWARD_BUTTON = 4;
+
+/**
+ * @constant
+ * @type {number}
+ */
+Phaser.Mouse.WHEEL_UP = 1;
+
+/**
+ * @constant
+ * @type {number}
+ */
+Phaser.Mouse.WHEEL_DOWN = -1;
+
+Phaser.Mouse.prototype = {
+
+    /**
+    * Starts the event listeners running.
+    * @method Phaser.Mouse#start
+    */
+    start: function () {
+
+        if (this.game.device.android && this.game.device.chrome === false)
+        {
+            //  Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
+            return;
+        }
+
+        if (this._onMouseDown !== null)
+        {
+            //  Avoid setting multiple listeners
+            return;
+        }
+
+        var _this = this;
+
+        this._onMouseDown = function (event) {
+            return _this.onMouseDown(event);
+        };
+
+        this._onMouseMove = function (event) {
+            return _this.onMouseMove(event);
+        };
+
+        this._onMouseUp = function (event) {
+            return _this.onMouseUp(event);
+        };
+
+        this._onMouseUpGlobal = function (event) {
+            return _this.onMouseUpGlobal(event);
+        };
+
+        this._onMouseOut = function (event) {
+            return _this.onMouseOut(event);
+        };
+
+        this._onMouseOver = function (event) {
+            return _this.onMouseOver(event);
+        };
+
+        this._onMouseWheel = function (event) {
+            return _this.onMouseWheel(event);
+        };
+
+        var canvas = this.game.canvas;
+
+        canvas.addEventListener('mousedown', this._onMouseDown, true);
+        canvas.addEventListener('mousemove', this._onMouseMove, true);
+        canvas.addEventListener('mouseup', this._onMouseUp, true);
+
+        if (!this.game.device.cocoonJS)
+        {
+            window.addEventListener('mouseup', this._onMouseUpGlobal, true);
+            canvas.addEventListener('mouseover', this._onMouseOver, true);
+            canvas.addEventListener('mouseout', this._onMouseOut, true);
+        }
+
+        var wheelEvent = this.game.device.wheelEvent;
+
+        if (wheelEvent)
+        {
+            canvas.addEventListener(wheelEvent, this._onMouseWheel, true);
+
+            if (wheelEvent === 'mousewheel')
+            {
+                this._wheelEvent = new WheelEventProxy(-1/40, 1);
+            }
+            else if (wheelEvent === 'DOMMouseScroll')
+            {
+                this._wheelEvent = new WheelEventProxy(1, 1);
+            }
+        }
+
+    },
+
+    /**
+    * The internal method that handles the mouse down event from the browser.
+    * @method Phaser.Mouse#onMouseDown
+    * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    onMouseDown: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        if (this.mouseDownCallback)
+        {
+            this.mouseDownCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        event['identifier'] = 0;
+
+        this.input.mousePointer.start(event);
+
+    },
+
+    /**
+    * The internal method that handles the mouse move event from the browser.
+    * @method Phaser.Mouse#onMouseMove
+    * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    onMouseMove: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        if (this.mouseMoveCallback)
+        {
+            this.mouseMoveCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        event['identifier'] = 0;
+
+        this.input.mousePointer.move(event);
+
+    },
+
+    /**
+    * The internal method that handles the mouse up event from the browser.
+    * @method Phaser.Mouse#onMouseUp
+    * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    onMouseUp: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        if (this.mouseUpCallback)
+        {
+            this.mouseUpCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        event['identifier'] = 0;
+
+        this.input.mousePointer.stop(event);
+
+    },
+
+    /**
+    * The internal method that handles the mouse up event from the window.
+    * 
+    * @method Phaser.Mouse#onMouseUpGlobal
+    * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    onMouseUpGlobal: function (event) {
+
+        if (!this.input.mousePointer.withinGame)
+        {
+            if (this.mouseUpCallback)
+            {
+                this.mouseUpCallback.call(this.callbackContext, event);
+            }
+
+            event['identifier'] = 0;
+
+            this.input.mousePointer.stop(event);
+        }
+
+    },
+
+    /**
+    * The internal method that handles the mouse out event from the browser.
+    *
+    * @method Phaser.Mouse#onMouseOut
+    * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    onMouseOut: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        this.input.mousePointer.withinGame = false;
+
+        if (this.mouseOutCallback)
+        {
+            this.mouseOutCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        if (this.stopOnGameOut)
+        {
+            event['identifier'] = 0;
+
+            this.input.mousePointer.stop(event);
+        }
+
+    },
+
+    /**
+     * The internal method that handles the mouse wheel event from the browser.
+     *
+     * @method Phaser.Mouse#onMouseWheel
+     * @param {MouseEvent} event - The native event from the browser.
+     */
+    onMouseWheel: function (event) {
+
+        if (this._wheelEvent) {
+            event = this._wheelEvent.bindEvent(event);
+        }
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        // reverse detail for firefox
+        this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1);
+
+        if (this.mouseWheelCallback)
+        {
+            this.mouseWheelCallback.call(this.callbackContext, event);
+        }
+
+    },
+
+    /**
+    * The internal method that handles the mouse over event from the browser.
+    *
+    * @method Phaser.Mouse#onMouseOver
+    * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    onMouseOver: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        this.input.mousePointer.withinGame = true;
+
+        if (this.mouseOverCallback)
+        {
+            this.mouseOverCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+    },
+
+    /**
+    * If the browser supports it you can request that the pointer be locked to the browser window.
+    * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
+    * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
+    * @method Phaser.Mouse#requestPointerLock
+    */
+    requestPointerLock: function () {
+
+        if (this.game.device.pointerLock)
+        {
+            var element = this.game.canvas;
+
+            element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
+
+            element.requestPointerLock();
+
+            var _this = this;
+
+            this._pointerLockChange = function (event) {
+                return _this.pointerLockChange(event);
+            };
+
+            document.addEventListener('pointerlockchange', this._pointerLockChange, true);
+            document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
+            document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
+        }
+
+    },
+
+    /**
+    * Internal pointerLockChange handler.
+    * 
+    * @method Phaser.Mouse#pointerLockChange
+    * @param {Event} event - The native event from the browser. This gets stored in Mouse.event.
+    */
+    pointerLockChange: function (event) {
+
+        var element = this.game.canvas;
+
+        if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
+        {
+            //  Pointer was successfully locked
+            this.locked = true;
+            this.pointerLock.dispatch(true, event);
+        }
+        else
+        {
+            //  Pointer was unlocked
+            this.locked = false;
+            this.pointerLock.dispatch(false, event);
+        }
+
+    },
+
+    /**
+    * Internal release pointer lock handler.
+    * @method Phaser.Mouse#releasePointerLock
+    */
+    releasePointerLock: function () {
+
+        document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
+
+        document.exitPointerLock();
+
+        document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
+        document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
+        document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
+
+    },
+
+    /**
+    * Stop the event listeners.
+    * @method Phaser.Mouse#stop
+    */
+    stop: function () {
+
+        var canvas = this.game.canvas;
+
+        canvas.removeEventListener('mousedown', this._onMouseDown, true);
+        canvas.removeEventListener('mousemove', this._onMouseMove, true);
+        canvas.removeEventListener('mouseup', this._onMouseUp, true);
+        canvas.removeEventListener('mouseover', this._onMouseOver, true);
+        canvas.removeEventListener('mouseout', this._onMouseOut, true);
+
+        var wheelEvent = this.game.device.wheelEvent;
+
+        if (wheelEvent)
+        {
+            canvas.removeEventListener(wheelEvent, this._onMouseWheel, true);
+        }
+
+        window.removeEventListener('mouseup', this._onMouseUpGlobal, true);
+
+        document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
+        document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
+        document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
+
+    }
+
+};
+
+Phaser.Mouse.prototype.constructor = Phaser.Mouse;
+
+/* jshint latedef:nofunc */
+/**
+* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel'
+* events to 'wheel'-like events.
+*
+* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode.
+*
+* @method Phaser.Mouse#WheelEventProxy
+* @private
+* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details.
+* @param {integer} deltaMode - The reported delta mode.
+*/
+function WheelEventProxy (scaleFactor, deltaMode) {
+
+    /**
+    * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details.
+    * @private
+    */
+    this._scaleFactor = scaleFactor;
+
+    /**
+    * @property {number} _deltaMode - The reported delta mode.
+    * @private
+    */
+    this._deltaMode = deltaMode;
+
+    /**
+    * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit.
+    * @private
+    */
+    this.originalEvent = null;
+
+}
+
+WheelEventProxy.prototype = {};
+WheelEventProxy.prototype.constructor = WheelEventProxy;
+
+WheelEventProxy.prototype.bindEvent = function (event) {
+
+    // Generate stubs automatically
+    if (!WheelEventProxy._stubsGenerated && event)
+    {
+        var makeBinder = function (name) {
+
+            return function () {
+                var v = this.originalEvent[name];
+                return typeof v !== 'function' ? v : v.bind(this.originalEvent);
+            };
+
+        };
+
+        for (var prop in event)
+        {
+            if (!(prop in WheelEventProxy.prototype))
+            {
+                Object.defineProperty(WheelEventProxy.prototype, prop, {
+                    get: makeBinder(prop)
+                });
+            }
+        }
+        WheelEventProxy._stubsGenerated = true;
+    }
+
+    this.originalEvent = event;
+    return this;
+
+};
+
+Object.defineProperties(WheelEventProxy.prototype, {
+    "type": { value: "wheel" },
+    "deltaMode": { get: function () { return this._deltaMode; } },
+    "deltaY": {
+        get: function () {
+            return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0;
+        }
+    },
+    "deltaX": {
+        get: function () {
+            return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0;
+        }
+    },
+    "deltaZ": { value: 0 }
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The MSPointer class handles Microsoft touch interactions with the game and the resulting Pointer objects.
+*
+* It will work only in Internet Explorer 10+ and Windows Store or Windows Phone 8 apps using JavaScript.
+* http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
+*
+* You should not normally access this class directly, but instead use a Phaser.Pointer object which 
+* normalises all game input for you including accurate button handling.
+*
+* Please note that at the current time of writing Phaser does not yet support chorded button interactions:
+* http://www.w3.org/TR/pointerevents/#chorded-button-interactions
+*
+* @class Phaser.MSPointer
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.MSPointer = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Input} input - A reference to the Phaser Input Manager.
+    * @protected
+    */
+    this.input = game.input;
+
+    /**
+    * @property {object} callbackContext - The context under which callbacks are called (defaults to game).
+    */
+    this.callbackContext = this.game;
+
+    /**
+    * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event.
+    */
+    this.pointerDownCallback = null;
+
+    /**
+    * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event.
+    */
+    this.pointerMoveCallback = null;
+
+    /**
+    * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event.
+    */
+    this.pointerUpCallback = null;
+
+    /**
+    * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, if false they will propagate fully.
+    */
+    this.capture = true;
+
+    /**
+    * This property was removed in Phaser 2.4 and should no longer be used.
+    * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on.
+    * Or Pointer.button holds the DOM event button value if you require that.
+    * @property {number} button
+    */
+    this.button = -1;
+
+    /**
+    * The browser MSPointer DOM event. Will be null if no event has ever been received.
+    * Access this property only inside a Pointer event handler and do not keep references to it.
+    * @property {MSPointerEvent|null} event
+    * @default
+    */
+    this.event = null;
+
+    /**
+    * MSPointer input will only be processed if enabled.
+    * @property {boolean} enabled
+    * @default
+    */
+    this.enabled = true;
+
+    /**
+    * @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
+    * @private
+    */
+    this._onMSPointerDown = null;
+
+    /**
+    * @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
+    * @private
+    */
+    this._onMSPointerMove = null;
+
+    /**
+    * @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
+    * @private
+    */
+    this._onMSPointerUp = null;
+
+};
+
+Phaser.MSPointer.prototype = {
+
+    /**
+    * Starts the event listeners running.
+    * @method Phaser.MSPointer#start
+    */
+    start: function () {
+
+        if (this._onMSPointerDown !== null)
+        {
+            //  Avoid setting multiple listeners
+            return;
+        }
+
+        var _this = this;
+
+        if (this.game.device.mspointer)
+        {
+            this._onMSPointerDown = function (event) {
+                return _this.onPointerDown(event);
+            };
+
+            this._onMSPointerMove = function (event) {
+                return _this.onPointerMove(event);
+            };
+
+            this._onMSPointerUp = function (event) {
+                return _this.onPointerUp(event);
+            };
+
+            var canvas = this.game.canvas;
+
+            canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false);
+            canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false);
+            canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false);
+
+            //  IE11+ uses non-prefix events
+            canvas.addEventListener('pointerDown', this._onMSPointerDown, false);
+            canvas.addEventListener('pointerMove', this._onMSPointerMove, false);
+            canvas.addEventListener('pointerUp', this._onMSPointerUp, false);
+
+            canvas.style['-ms-content-zooming'] = 'none';
+            canvas.style['-ms-touch-action'] = 'none';
+        }
+
+    },
+
+    /**
+    * The function that handles the PointerDown event.
+    * 
+    * @method Phaser.MSPointer#onPointerDown
+    * @param {PointerEvent} event - The native DOM event.
+    */
+    onPointerDown: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        if (this.pointerDownCallback)
+        {
+            this.pointerDownCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        event.identifier = event.pointerId;
+
+        if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
+        {
+            this.input.mousePointer.start(event);
+        }
+        else
+        {
+            this.input.startPointer(event);
+        }
+
+    },
+
+    /**
+    * The function that handles the PointerMove event.
+    * @method Phaser.MSPointer#onPointerMove
+    * @param {PointerEvent} event - The native DOM event.
+    */
+    onPointerMove: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        if (this.pointerMoveCallback)
+        {
+            this.pointerMoveCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        event.identifier = event.pointerId;
+
+        if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
+        {
+            this.input.mousePointer.move(event);
+        }
+        else
+        {
+            this.input.updatePointer(event);
+        }
+
+    },
+
+    /**
+    * The function that handles the PointerUp event.
+    * @method Phaser.MSPointer#onPointerUp
+    * @param {PointerEvent} event - The native DOM event.
+    */
+    onPointerUp: function (event) {
+
+        this.event = event;
+
+        if (this.capture)
+        {
+            event.preventDefault();
+        }
+
+        if (this.pointerUpCallback)
+        {
+            this.pointerUpCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        event.identifier = event.pointerId;
+
+        if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
+        {
+            this.input.mousePointer.stop(event);
+        }
+        else
+        {
+            this.input.stopPointer(event);
+        }
+
+    },
+
+    /**
+    * Stop the event listeners.
+    * @method Phaser.MSPointer#stop
+    */
+    stop: function () {
+
+        var canvas = this.game.canvas;
+
+        canvas.removeEventListener('MSPointerDown', this._onMSPointerDown);
+        canvas.removeEventListener('MSPointerMove', this._onMSPointerMove);
+        canvas.removeEventListener('MSPointerUp', this._onMSPointerUp);
+
+        canvas.removeEventListener('pointerDown', this._onMSPointerDown);
+        canvas.removeEventListener('pointerMove', this._onMSPointerMove);
+        canvas.removeEventListener('pointerUp', this._onMSPointerUp);
+
+    }
+
+};
+
+Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @author       @karlmacklin <tacklemcclean@gmail.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances.
+*
+* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button,
+* middle button and advanced buttons like back and forward.
+*
+* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on.
+*
+* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons.
+*
+* At the time of writing this there are device limitations you should be aware of:
+*
+* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions 
+*   (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, 
+*   even when they are pressed.
+* - On Linux (GTK), the 4th button and the 5th button are not supported.
+* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons.
+* 
+* @class Phaser.DeviceButton
+* @constructor
+* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad.
+* @param {number} buttonCode - The button code this DeviceButton is responsible for.
+*/
+Phaser.DeviceButton = function (parent, buttonCode) {
+
+    /**
+    * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button.
+    */
+    this.parent = parent;
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = parent.game;
+
+    /**
+    * @property {object} event - The DOM event that caused the change in button state.
+    * @default
+    */
+    this.event = null;
+
+    /**
+    * @property {boolean} isDown - The "down" state of the button.
+    * @default
+    */
+    this.isDown = false;
+
+    /**
+    * @property {boolean} isUp - The "up" state of the button.
+    * @default
+    */
+    this.isUp = true;
+
+    /**
+    * @property {number} timeDown - The timestamp when the button was last pressed down.
+    * @default
+    */
+    this.timeDown = 0;
+
+    /**
+    * If the button is down this value holds the duration of that button press and is constantly updated.
+    * If the button is up it holds the duration of the previous down session.
+    * The value is stored in milliseconds.
+    * @property {number} duration
+    * @default
+    */
+    this.duration = 0;
+
+    /**
+    * @property {number} timeUp - The timestamp when the button was last released.
+    * @default
+    */
+    this.timeUp = 0;
+
+    /**
+    * Gamepad only.
+    * If a button is held down this holds down the number of times the button has 'repeated'.
+    * @property {number} repeats
+    * @default
+    */
+    this.repeats = 0;
+
+    /**
+    * True if the alt key was held down when this button was last pressed or released.
+    * Not supported on Gamepads.
+    * @property {boolean} altKey
+    * @default
+    */
+    this.altKey = false;
+
+    /**
+    * True if the shift key was held down when this button was last pressed or released.
+    * Not supported on Gamepads.
+    * @property {boolean} shiftKey
+    * @default
+    */
+    this.shiftKey = false;
+
+    /**
+    * True if the control key was held down when this button was last pressed or released.
+    * Not supported on Gamepads.
+    * @property {boolean} ctrlKey
+    * @default
+    */
+    this.ctrlKey = false;
+
+    /**
+    * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads.
+    * @default
+    */
+    this.value = 0;
+
+    /**
+    * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer.
+    */
+    this.buttonCode = buttonCode;
+
+    /**
+    * This Signal is dispatched every time this DeviceButton is pressed down.
+    * It is only dispatched once (until the button is released again).
+    * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
+    * @property {Phaser.Signal} onDown
+    */
+    this.onDown = new Phaser.Signal();
+
+    /**
+    * This Signal is dispatched every time this DeviceButton is released from a down state.
+    * It is only dispatched once (until the button is pressed again).
+    * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
+    * @property {Phaser.Signal} onUp
+    */
+    this.onUp = new Phaser.Signal();
+
+    /**
+    * Gamepad only.
+    * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1).
+    * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
+    * @property {Phaser.Signal} onFloat
+    */
+    this.onFloat = new Phaser.Signal();
+
+};
+
+Phaser.DeviceButton.prototype = {
+
+    /**
+    * Called automatically by Phaser.Pointer and Phaser.SinglePad.
+    * Handles the button down state.
+    * 
+    * @method Phaser.DeviceButton#start
+    * @protected
+    * @param {object} [event] - The DOM event that triggered the button change.
+    * @param {number} [value] - The button value. Only get for Gamepads.
+    */
+    start: function (event, value) {
+
+        if (this.isDown)
+        {
+            return;
+        }
+
+        this.isDown = true;
+        this.isUp = false;
+        this.timeDown = this.game.time.time;
+        this.duration = 0;
+        this.repeats = 0;
+
+        this.event = event;
+        this.value = value;
+
+        if (event)
+        {
+            this.altKey = event.altKey;
+            this.shiftKey = event.shiftKey;
+            this.ctrlKey = event.ctrlKey;
+        }
+
+        this.onDown.dispatch(this, value);
+
+    },
+
+    /**
+    * Called automatically by Phaser.Pointer and Phaser.SinglePad.
+    * Handles the button up state.
+    * 
+    * @method Phaser.DeviceButton#stop
+    * @protected
+    * @param {object} [event] - The DOM event that triggered the button change.
+    * @param {number} [value] - The button value. Only get for Gamepads.
+    */
+    stop: function (event, value) {
+
+        if (this.isUp)
+        {
+            return;
+        }
+
+        this.isDown = false;
+        this.isUp = true;
+        this.timeUp = this.game.time.time;
+
+        this.event = event;
+        this.value = value;
+
+        if (event)
+        {
+            this.altKey = event.altKey;
+            this.shiftKey = event.shiftKey;
+            this.ctrlKey = event.ctrlKey;
+        }
+
+        this.onUp.dispatch(this, value);
+
+    },
+
+    /**
+    * Called automatically by Phaser.SinglePad.
+    * 
+    * @method Phaser.DeviceButton#padFloat
+    * @protected
+    * @param {number} value - Button value
+    */
+    padFloat: function (value) {
+
+        this.value = value;
+
+        this.onFloat.dispatch(this, value);
+
+    },
+
+    /**
+    * Returns the "just pressed" state of this button.
+    * Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
+    * 
+    * @method Phaser.DeviceButton#justPressed
+    * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed.
+    * @return {boolean} True if the button is just pressed otherwise false.
+    */
+    justPressed: function (duration) {
+
+        duration = duration || 250;
+
+        return (this.isDown && (this.timeDown + duration) > this.game.time.time);
+
+    },
+
+    /**
+    * Returns the "just released" state of this button.
+    * Just released is considered as being true if the button was released within the duration given (default 250ms).
+    * 
+    * @method Phaser.DeviceButton#justReleased
+    * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released.
+    * @return {boolean} True if the button is just released otherwise false.
+    */
+    justReleased: function (duration) {
+
+        duration = duration || 250;
+
+        return (this.isUp && (this.timeUp + duration) > this.game.time.time);
+
+    },
+
+    /**
+    * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters.
+    * 
+    * @method Phaser.DeviceButton#reset
+    */
+    reset: function () {
+
+        this.isDown = false;
+        this.isUp = true;
+
+        this.timeDown = this.game.time.time;
+        this.duration = 0;
+        this.repeats = 0;
+
+        this.altKey = false;
+        this.shiftKey = false;
+        this.ctrlKey = false;
+
+    },
+
+    /**
+    * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals 
+    * and clears the parent and game references.
+    * 
+    * @method Phaser.DeviceButton#destroy
+    */
+    destroy: function () {
+
+        this.onDown.dispose();
+        this.onUp.dispose();
+        this.onFloat.dispose();
+
+        this.parent = null;
+        this.game = null;
+
+    }
+
+};
+
+Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton;
+
+/**
+* How long the button has been held down.
+* If not currently down it returns -1.
+* 
+* @name Phaser.DeviceButton#duration
+* @property {number} duration
+* @readonly
+*/
+Object.defineProperty(Phaser.DeviceButton.prototype, "duration", {
+
+    get: function () {
+
+        if (this.isUp)
+        {
+            return -1;
+        }
+
+        return this.game.time.time - this.timeDown;
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
+*
+* @class Phaser.Pointer
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
+*/
+Phaser.Pointer = function (game, id) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
+    */
+    this.id = id;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.POINTER;
+
+    /**
+    * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps.
+    * @default
+    */
+    this.exists = true;
+
+    /**
+    * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started.
+    * @default
+    */
+    this.identifier = 0;
+
+    /**
+    * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value.
+    * @default
+    */
+    this.pointerId = null;
+
+    /**
+    * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started.
+    * @default
+    */
+    this.target = null;
+
+    /**
+    * The button property of the most recent DOM event when this Pointer is started.
+    * You should not rely on this value for accurate button detection, instead use the Pointer properties
+    * `leftButton`, `rightButton`, `middleButton` and so on.
+    * @property {any} button
+    * @default
+    */
+    this.button = null;
+
+    /**
+    * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property.
+    * 
+    * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
+    * button control.
+    * 
+    * @property {Phaser.DeviceButton} leftButton
+    * @default
+    */
+    this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON);
+
+    /**
+    * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property.
+    * 
+    * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
+    * button control.
+    *
+    * Please see the DeviceButton docs for details on browser button limitations.
+    * 
+    * @property {Phaser.DeviceButton} middleButton
+    * @default
+    */
+    this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON);
+
+    /**
+    * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property.
+    * 
+    * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
+    * button control.
+    *
+    * Please see the DeviceButton docs for details on browser button limitations.
+    * 
+    * @property {Phaser.DeviceButton} rightButton
+    * @default
+    */
+    this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON);
+
+    /**
+    * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property.
+    * 
+    * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
+    * button control.
+    *
+    * Please see the DeviceButton docs for details on browser button limitations.
+    * 
+    * @property {Phaser.DeviceButton} backButton
+    * @default
+    */
+    this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON);
+
+    /**
+    * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property.
+    * 
+    * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
+    * button control.
+    *
+    * Please see the DeviceButton docs for details on browser button limitations.
+    * 
+    * @property {Phaser.DeviceButton} forwardButton
+    * @default
+    */
+    this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON);
+
+    /**
+    * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property.
+    * 
+    * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
+    * button control.
+    *
+    * Please see the DeviceButton docs for details on browser button limitations.
+    * 
+    * @property {Phaser.DeviceButton} eraserButton
+    * @default
+    */
+    this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON);
+
+    /**
+    * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
+    * @private
+    * @default
+    */
+    this._holdSent = false;
+
+    /**
+    * @property {array} _history - Local private variable storing the short-term history of pointer movements.
+    * @private
+    */
+    this._history = [];
+
+    /**
+    * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur.
+    * @private
+    */
+    this._nextDrop = 0;
+
+    /**
+    * @property {boolean} _stateReset - Monitor events outside of a state reset loop.
+    * @private
+    */
+    this._stateReset = false;
+
+    /**
+    * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false.
+    */
+    this.withinGame = false;
+
+    /**
+    * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
+    */
+    this.clientX = -1;
+
+    /**
+    * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
+    */
+    this.clientY = -1;
+
+    /**
+    * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document.
+    */
+    this.pageX = -1;
+
+    /**
+    * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document.
+    */
+    this.pageY = -1;
+
+    /**
+    * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen.
+    */
+    this.screenX = -1;
+
+    /**
+    * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen.
+    */
+    this.screenY = -1;
+
+    /**
+    * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event.
+    * @default
+    */
+    this.rawMovementX = 0;
+
+    /**
+    * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event.
+    * @default
+    */
+    this.rawMovementY = 0;
+
+    /**
+    * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event.
+    * @default
+    */
+    this.movementX = 0;
+
+    /**
+    * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event.
+    * @default
+    */
+    this.movementY = 0;
+
+    /**
+    * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale.
+    * @default
+    */
+    this.x = -1;
+
+    /**
+    * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale.
+    * @default
+    */
+    this.y = -1;
+
+    /**
+    * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false.
+    */
+    this.isMouse = (id === 0);
+
+    /**
+    * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true.
+    * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown.
+    * @property {boolean} isDown
+    * @default
+    */
+    this.isDown = false;
+
+    /**
+    * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true.
+    * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp.
+    * @property {boolean} isUp
+    * @default
+    */
+    this.isUp = true;
+
+    /**
+    * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
+    * @default
+    */
+    this.timeDown = 0;
+
+    /**
+    * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
+    * @default
+    */
+    this.timeUp = 0;
+
+    /**
+    * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
+    * @default
+    */
+    this.previousTapTime = 0;
+
+    /**
+    * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
+    * @default
+    */
+    this.totalTouches = 0;
+
+    /**
+    * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event.
+    * @default
+    */
+    this.msSinceLastClick = Number.MAX_VALUE;
+
+    /**
+    * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
+    * @default
+    */
+    this.targetObject = null;
+
+    /**
+    * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
+    * @default
+    */
+    this.active = false;
+
+    /**
+    * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not.
+    * @default
+    */
+    this.dirty = false;
+
+    /**
+    * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
+    */
+    this.position = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display.
+    */
+    this.positionDown = new Phaser.Point();
+    
+    /**
+    * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
+    */
+    this.positionUp = new Phaser.Point();
+
+    /**
+    * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
+    * The Circle size is 44px (Apples recommended "finger tip" size).
+    * @property {Phaser.Circle} circle
+    */
+    this.circle = new Phaser.Circle(0, 0, 44);
+
+    /**
+    * Click trampolines associated with this pointer. See `addClickTrampoline`.
+    * @property {object[]|null} _clickTrampolines
+    * @private
+    */
+    this._clickTrampolines = null;
+
+    /**
+    * When the Pointer has click trampolines the last target object is stored here
+    * so it can be used to check for validity of the trampoline in a post-Up/'stop'.
+    * @property {object} _trampolineTargetObject
+    * @private
+    */
+    this._trampolineTargetObject = null;
+
+};
+
+/**
+* No buttons at all.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.NO_BUTTON = 0;
+
+/**
+* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.LEFT_BUTTON = 1;
+
+/**
+* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.RIGHT_BUTTON = 2;
+
+/**
+* The Middle Mouse button.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.MIDDLE_BUTTON = 4;
+
+/**
+* The X1 button. This is typically the mouse Back button, but is often reconfigured.
+* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.BACK_BUTTON = 8;
+
+/**
+* The X2 button. This is typically the mouse Forward button, but is often reconfigured.
+* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.FORWARD_BUTTON = 16;
+
+/**
+* The Eraser pen button on PointerEvent supported devices only.
+* @constant
+* @type {number}
+*/
+Phaser.Pointer.ERASER_BUTTON = 32;
+
+Phaser.Pointer.prototype = {
+
+    /**
+    * Resets the states of all the button booleans.
+    * 
+    * @method Phaser.Pointer#resetButtons
+    * @protected
+    */
+    resetButtons: function () {
+
+        this.isDown = false;
+        this.isUp = true;
+
+        if (this.isMouse)
+        {
+            this.leftButton.reset();
+            this.middleButton.reset();
+            this.rightButton.reset();
+            this.backButton.reset();
+            this.forwardButton.reset();
+            this.eraserButton.reset();
+        }
+
+    },
+
+    /**
+    * Called by updateButtons.
+    * 
+    * @method Phaser.Pointer#processButtonsDown
+    * @private
+    * @param {integer} buttons - The DOM event.buttons property.
+    * @param {MouseEvent} event - The DOM event.
+    */
+    processButtonsDown: function (buttons, event) {
+
+        //  Note: These are bitwise checks, not booleans
+
+        if (Phaser.Pointer.LEFT_BUTTON & buttons)
+        {
+            this.leftButton.start(event);
+        }
+
+        if (Phaser.Pointer.RIGHT_BUTTON & buttons)
+        {
+            this.rightButton.start(event);
+        }
+                
+        if (Phaser.Pointer.MIDDLE_BUTTON & buttons)
+        {
+            this.middleButton.start(event);
+        }
+
+        if (Phaser.Pointer.BACK_BUTTON & buttons)
+        {
+            this.backButton.start(event);
+        }
+
+        if (Phaser.Pointer.FORWARD_BUTTON & buttons)
+        {
+            this.forwardButton.start(event);
+        }
+
+        if (Phaser.Pointer.ERASER_BUTTON & buttons)
+        {
+            this.eraserButton.start(event);
+        }
+
+    },
+
+    /**
+    * Called by updateButtons.
+    * 
+    * @method Phaser.Pointer#processButtonsUp
+    * @private
+    * @param {integer} buttons - The DOM event.buttons property.
+    * @param {MouseEvent} event - The DOM event.
+    */
+    processButtonsUp: function (button, event) {
+
+        //  Note: These are bitwise checks, not booleans
+
+        if (button === Phaser.Mouse.LEFT_BUTTON)
+        {
+            this.leftButton.stop(event);
+        }
+
+        if (button === Phaser.Mouse.RIGHT_BUTTON)
+        {
+            this.rightButton.stop(event);
+        }
+                
+        if (button === Phaser.Mouse.MIDDLE_BUTTON)
+        {
+            this.middleButton.stop(event);
+        }
+
+        if (button === Phaser.Mouse.BACK_BUTTON)
+        {
+            this.backButton.stop(event);
+        }
+
+        if (button === Phaser.Mouse.FORWARD_BUTTON)
+        {
+            this.forwardButton.stop(event);
+        }
+
+        if (button === 5)
+        {
+            this.eraserButton.stop(event);
+        }
+
+    },
+
+    /**
+    * Called when the event.buttons property changes from zero.
+    * Contains a button bitmask.
+    * 
+    * @method Phaser.Pointer#updateButtons
+    * @protected
+    * @param {MouseEvent} event - The DOM event.
+    */
+    updateButtons: function (event) {
+
+        this.button = event.button;
+
+        var down = (event.type.toLowerCase().substr(-4) === 'down');
+
+        if (event.buttons !== undefined)
+        {
+            if (down)
+            {
+                this.processButtonsDown(event.buttons, event);
+            }
+            else
+            {
+                this.processButtonsUp(event.button, event);
+            }
+        }
+        else
+        {
+            //  No buttons property (like Safari on OSX when using a trackpad)
+            if (down)
+            {
+                this.leftButton.start(event);
+            }
+            else
+            {
+                this.leftButton.stop(event);
+                this.rightButton.stop(event);
+            }
+        }
+
+        //  On OS X (and other devices with trackpads) you have to press CTRL + the pad
+        //  to initiate a right-click event, so we'll check for that here
+
+        if (event.ctrlKey && this.leftButton.isDown)
+        {
+            this.rightButton.start(event);
+        }
+
+        this.isUp = true;
+        this.isDown = false;
+
+        if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown)
+        {
+            this.isUp = false;
+            this.isDown = true;
+        }
+
+    },
+
+    /**
+    * Called when the Pointer is pressed onto the touchscreen.
+    * @method Phaser.Pointer#start
+    * @param {any} event - The DOM event from the browser.
+    */
+    start: function (event) {
+
+        // console.log(event);
+
+        if (event['pointerId'])
+        {
+            this.pointerId = event.pointerId;
+        }
+
+        this.identifier = event.identifier;
+        this.target = event.target;
+
+        if (this.isMouse)
+        {
+            this.updateButtons(event);
+        }
+        else
+        {
+            this.isDown = true;
+            this.isUp = false;
+        }
+
+        this._history = [];
+        this.active = true;
+        this.withinGame = true;
+        this.dirty = false;
+        this._clickTrampolines = null;
+        this._trampolineTargetObject = null;
+
+        //  Work out how long it has been since the last click
+        this.msSinceLastClick = this.game.time.time - this.timeDown;
+        this.timeDown = this.game.time.time;
+        this._holdSent = false;
+
+        //  This sets the x/y and other local values
+        this.move(event, true);
+
+        // x and y are the old values here?
+        this.positionDown.setTo(this.x, this.y);
+
+        if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
+            this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
+            (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.totalActivePointers === 0))
+        {
+            this.game.input.x = this.x;
+            this.game.input.y = this.y;
+            this.game.input.position.setTo(this.x, this.y);
+            this.game.input.onDown.dispatch(this, event);
+            this.game.input.resetSpeed(this.x, this.y);
+        }
+
+        this._stateReset = false;
+        this.totalTouches++;
+
+        if (this.targetObject !== null)
+        {
+            this.targetObject._touchedHandler(this);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Called by the Input Manager.
+    * @method Phaser.Pointer#update
+    */
+    update: function () {
+
+        if (this.active)
+        {
+            //  Force a check?
+            if (this.dirty)
+            {
+                if (this.game.input.interactiveItems.total > 0)
+                {
+                    this.processInteractiveObjects(false);
+                }
+
+                this.dirty = false;
+            }
+
+            if (this._holdSent === false && this.duration >= this.game.input.holdRate)
+            {
+                if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
+                    this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
+                    (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.totalActivePointers === 0))
+                {
+                    this.game.input.onHold.dispatch(this);
+                }
+
+                this._holdSent = true;
+            }
+
+            //  Update the droppings history
+            if (this.game.input.recordPointerHistory && this.game.time.time >= this._nextDrop)
+            {
+                this._nextDrop = this.game.time.time + this.game.input.recordRate;
+
+                this._history.push({
+                    x: this.position.x,
+                    y: this.position.y
+                });
+
+                if (this._history.length > this.game.input.recordLimit)
+                {
+                    this._history.shift();
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Called when the Pointer is moved.
+    * 
+    * @method Phaser.Pointer#move
+    * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
+    * @param {boolean} [fromClick=false] - Was this called from the click event?
+    */
+    move: function (event, fromClick) {
+
+        if (this.game.input.pollLocked)
+        {
+            return;
+        }
+
+        if (fromClick === undefined) { fromClick = false; }
+
+        if (event.button !== undefined)
+        {
+            this.button = event.button;
+        }
+
+        if (fromClick && this.isMouse)
+        {
+            this.updateButtons(event);
+        }
+
+        this.clientX = event.clientX;
+        this.clientY = event.clientY;
+
+        this.pageX = event.pageX;
+        this.pageY = event.pageY;
+
+        this.screenX = event.screenX;
+        this.screenY = event.screenY;
+
+        if (this.isMouse && this.game.input.mouse.locked && !fromClick)
+        {
+            this.rawMovementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
+            this.rawMovementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
+
+            this.movementX += this.rawMovementX;
+            this.movementY += this.rawMovementY;
+        }
+
+        this.x = (this.pageX - this.game.scale.offset.x) * this.game.input.scale.x;
+        this.y = (this.pageY - this.game.scale.offset.y) * this.game.input.scale.y;
+
+        this.position.setTo(this.x, this.y);
+        this.circle.x = this.x;
+        this.circle.y = this.y;
+
+        if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
+            this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
+            (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.totalActivePointers === 0))
+        {
+            this.game.input.activePointer = this;
+            this.game.input.x = this.x;
+            this.game.input.y = this.y;
+            this.game.input.position.setTo(this.game.input.x, this.game.input.y);
+            this.game.input.circle.x = this.game.input.x;
+            this.game.input.circle.y = this.game.input.y;
+        }
+
+        this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY);
+
+        //  If the game is paused we don't process any target objects or callbacks
+        if (this.game.paused)
+        {
+            return this;
+        }
+
+        var i = this.game.input.moveCallbacks.length;
+
+        while (i--)
+        {
+            this.game.input.moveCallbacks[i].callback.call(this.game.input.moveCallbacks[i].context, this, this.x, this.y, fromClick);
+        }
+
+        //  Easy out if we're dragging something and it still exists
+        if (this.targetObject !== null && this.targetObject.isDragged === true)
+        {
+            if (this.targetObject.update(this) === false)
+            {
+                this.targetObject = null;
+            }
+        }
+        else if (this.game.input.interactiveItems.total > 0)
+        {
+            this.processInteractiveObjects(fromClick);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Process all interactive objects to find out which ones were updated in the recent Pointer move.
+    * 
+    * @method Phaser.Pointer#processInteractiveObjects
+    * @protected
+    * @param {boolean} [fromClick=false] - Was this called from the click event?
+    * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false.
+    */
+    processInteractiveObjects: function (fromClick) {
+
+        //  Work out which object is on the top
+        var highestRenderOrderID = Number.MAX_VALUE;
+        var highestInputPriorityID = -1;
+        var candidateTarget = null;
+
+        //  First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID
+        //  We know they'll be valid for input detection but not which is the top just yet
+
+        var currentNode = this.game.input.interactiveItems.first;
+
+        while (currentNode)
+        {
+            //  Reset checked status
+            currentNode.checked = false;
+
+            if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false))
+            {
+                //  Flag it as checked so we don't re-scan it on the next phase
+                currentNode.checked = true;
+
+                if ((fromClick && currentNode.checkPointerDown(this, true)) ||
+                    (!fromClick && currentNode.checkPointerOver(this, true)))
+                {
+                    highestRenderOrderID = currentNode.sprite.renderOrderID;
+                    highestInputPriorityID = currentNode.priorityID;
+                    candidateTarget = currentNode;
+                }
+            }
+
+            currentNode = this.game.input.interactiveItems.next;
+        }
+
+        //  Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID
+        //  because if their ID is lower anyway then we can just automatically discount them
+        //  (A node that was previously checked did not request a pixel-perfect check.)
+
+        var currentNode = this.game.input.interactiveItems.first;
+
+        while(currentNode)
+        {
+            if (!currentNode.checked &&
+                currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true))
+            {
+                if ((fromClick && currentNode.checkPointerDown(this, false)) ||
+                    (!fromClick && currentNode.checkPointerOver(this, false)))
+                {
+                    highestRenderOrderID = currentNode.sprite.renderOrderID;
+                    highestInputPriorityID = currentNode.priorityID;
+                    candidateTarget = currentNode;
+                }
+            }
+
+            currentNode = this.game.input.interactiveItems.next;
+        }
+
+        //  Now we know the top-most item (if any) we can process it
+        if (candidateTarget === null)
+        {
+            //  The pointer isn't currently over anything, check if we've got a lingering previous target
+            if (this.targetObject)
+            {
+                this.targetObject._pointerOutHandler(this);
+                this.targetObject = null;
+            }
+        }
+        else
+        {
+            if (this.targetObject === null)
+            {
+                //  And now set the new one
+                this.targetObject = candidateTarget;
+                candidateTarget._pointerOverHandler(this);
+            }
+            else
+            {
+                //  We've got a target from the last update
+                if (this.targetObject === candidateTarget)
+                {
+                    //  Same target as before, so update it
+                    if (candidateTarget.update(this) === false)
+                    {
+                        this.targetObject = null;
+                    }
+                }
+                else
+                {
+                    //  The target has changed, so tell the old one we've left it
+                    this.targetObject._pointerOutHandler(this);
+
+                    //  And now set the new one
+                    this.targetObject = candidateTarget;
+                    this.targetObject._pointerOverHandler(this);
+                }
+            }
+        }
+
+        return (this.targetObject !== null);
+
+    },
+
+    /**
+    * Called when the Pointer leaves the target area.
+    *
+    * @method Phaser.Pointer#leave
+    * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
+    */
+    leave: function (event) {
+
+        this.withinGame = false;
+        this.move(event, false);
+
+    },
+
+    /**
+    * Called when the Pointer leaves the touchscreen.
+    *
+    * @method Phaser.Pointer#stop
+    * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
+    */
+    stop: function (event) {
+
+        if (this._stateReset && this.withinGame)
+        {
+            event.preventDefault();
+            return;
+        }
+
+        if (this.isMouse)
+        {
+            this.updateButtons(event);
+        }
+        else
+        {
+            this.isDown = false;
+            this.isUp = true;
+        }
+
+        this.timeUp = this.game.time.time;
+
+        if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
+            this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
+            (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.totalActivePointers === 0))
+        {
+            this.game.input.onUp.dispatch(this, event);
+
+            //  Was it a tap?
+            if (this.duration >= 0 && this.duration <= this.game.input.tapRate)
+            {
+                //  Was it a double-tap?
+                if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate)
+                {
+                    //  Yes, let's dispatch the signal then with the 2nd parameter set to true
+                    this.game.input.onTap.dispatch(this, true);
+                }
+                else
+                {
+                    //  Wasn't a double-tap, so dispatch a single tap signal
+                    this.game.input.onTap.dispatch(this, false);
+                }
+
+                this.previousTapTime = this.timeUp;
+            }
+        }
+
+        //  Mouse is always active
+        if (this.id > 0)
+        {
+            this.active = false;
+        }
+
+        this.withinGame = false;
+        this.pointerId = null;
+        this.identifier = null;
+        
+        this.positionUp.setTo(this.x, this.y);
+        
+        if (this.isMouse === false)
+        {
+            this.game.input.currentPointers--;
+        }
+
+        this.game.input.interactiveItems.callAll('_releasedHandler', this);
+
+        if (this._clickTrampolines)
+        {
+            this._trampolineTargetObject = this.targetObject;
+        }
+
+        this.targetObject = null;
+
+        return this;
+
+    },
+
+    /**
+    * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
+    * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
+    * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
+    * @method Phaser.Pointer#justPressed
+    * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
+    * @return {boolean} true if the Pointer was pressed down within the duration given.
+    */
+    justPressed: function (duration) {
+
+        duration = duration || this.game.input.justPressedRate;
+
+        return (this.isDown === true && (this.timeDown + duration) > this.game.time.time);
+
+    },
+
+    /**
+    * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
+    * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
+    * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
+    * @method Phaser.Pointer#justReleased
+    * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
+    * @return {boolean} true if the Pointer was released within the duration given.
+    */
+    justReleased: function (duration) {
+
+        duration = duration || this.game.input.justReleasedRate;
+
+        return (this.isUp && (this.timeUp + duration) > this.game.time.time);
+
+    },
+
+    /**
+    * Add a click trampoline to this pointer.
+    *
+    * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily
+    * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen
+    * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events.
+    *
+    * This is used internally by the ScaleManager; click trampoline usage is uncommon.
+    * Click trampolines can only be added to pointers that are currently down.
+    *
+    * @method Phaser.Pointer#addClickTrampoline
+    * @protected
+    * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer.
+    * @param {function} callback - Callback to run/trampoline.
+    * @param {object} callbackContext - Context of the callback.
+    * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array.
+    */
+    addClickTrampoline: function (name, callback, callbackContext, callbackArgs) {
+
+        if (!this.isDown)
+        {
+            return;
+        }
+
+        var trampolines = (this._clickTrampolines = this._clickTrampolines || []);
+
+        for (var i = 0; i < trampolines.length; i++)
+        {
+            if (trampolines[i].name === name)
+            {
+                trampolines.splice(i, 1);
+                break;
+            }
+        }
+
+        trampolines.push({
+            name: name,
+            targetObject: this.targetObject,
+            callback: callback,
+            callbackContext: callbackContext,
+            callbackArgs: callbackArgs
+        });
+
+    },
+
+    /**
+    * Fire all click trampolines for which the pointers are still referring to the registered object.
+    * @method Phaser.Pointer#processClickTrampolines
+    * @private
+    */
+    processClickTrampolines: function () {
+
+        var trampolines = this._clickTrampolines;
+
+        if (!trampolines)
+        {
+            return;
+        }
+
+        for (var i = 0; i < trampolines.length; i++)
+        {
+            var trampoline = trampolines[i];
+
+            if (trampoline.targetObject === this._trampolineTargetObject)
+            {
+                trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs);
+            }
+        }
+
+        this._clickTrampolines = null;
+        this._trampolineTargetObject = null;
+
+    },
+
+    /**
+    * Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
+    * @method Phaser.Pointer#reset
+    */
+    reset: function () {
+
+        if (this.isMouse === false)
+        {
+            this.active = false;
+        }
+
+        this.pointerId = null;
+        this.identifier = null;
+        this.dirty = false;
+        this.totalTouches = 0;
+        this._holdSent = false;
+        this._history.length = 0;
+        this._stateReset = true;
+
+        this.resetButtons();
+
+        if (this.targetObject)
+        {
+            this.targetObject._releasedHandler(this);
+        }
+
+        this.targetObject = null;
+
+    },
+
+    /**
+     * Resets the movementX and movementY properties. Use in your update handler after retrieving the values.
+     * @method Phaser.Pointer#resetMovement
+     */
+    resetMovement: function() {
+
+        this.movementX = 0;
+        this.movementY = 0;
+
+    }
+
+};
+
+Phaser.Pointer.prototype.constructor = Phaser.Pointer;
+
+/**
+* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down.
+* If not currently down it returns -1.
+* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`.
+* 
+* @name Phaser.Pointer#duration
+* @property {number} duration
+* @readonly
+*/
+Object.defineProperty(Phaser.Pointer.prototype, "duration", {
+
+    get: function () {
+
+        if (this.isUp)
+        {
+            return -1;
+        }
+
+        return this.game.time.time - this.timeDown;
+
+    }
+
+});
+
+/**
+* Gets the X value of this Pointer in world coordinates based on the world camera.
+* @name Phaser.Pointer#worldX
+* @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
+* @readonly
+*/
+Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
+
+    get: function () {
+
+        return this.game.world.camera.x + this.x;
+
+    }
+
+});
+
+/**
+* Gets the Y value of this Pointer in world coordinates based on the world camera.
+* @name Phaser.Pointer#worldY
+* @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
+* @readonly
+*/
+Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
+
+    get: function () {
+
+        return this.game.world.camera.y + this.y;
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
+*
+* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you.
+*
+* @class Phaser.Touch
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Touch = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * Touch events will only be processed if enabled.
+    * @property {boolean} enabled
+    * @default
+    */
+    this.enabled = true;
+
+    /**
+    * An array of callbacks that will be fired every time a native touch start event is received from the browser.
+    * This is used internally to handle audio and video unlocking on mobile devices.
+    * To add a callback to this array please use `Touch.addTouchLockCallback`.
+    * @property {array} touchLockCallbacks
+    * @protected
+    */
+    this.touchLockCallbacks = [];
+
+    /**
+    * @property {object} callbackContext - The context under which callbacks are called.
+    */
+    this.callbackContext = this.game;
+
+    /**
+    * @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
+    */
+    this.touchStartCallback = null;
+
+    /**
+    * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
+    */
+    this.touchMoveCallback = null;
+
+    /**
+    * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
+    */
+    this.touchEndCallback = null;
+
+    /**
+    * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
+    */
+    this.touchEnterCallback = null;
+
+    /**
+    * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
+    */
+    this.touchLeaveCallback = null;
+
+    /**
+    * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
+    */
+    this.touchCancelCallback = null;
+
+    /**
+    * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
+    * @default
+    */
+    this.preventDefault = true;
+
+    /**
+    * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
+    * @default
+    */
+    this.event = null;
+
+    /**
+    * @property {function} _onTouchStart - Internal event handler reference.
+    * @private
+    */
+    this._onTouchStart = null;
+
+    /**
+    * @property {function} _onTouchMove - Internal event handler reference.
+    * @private
+    */
+    this._onTouchMove = null;
+
+    /**
+    * @property {function} _onTouchEnd - Internal event handler reference.
+    * @private
+    */
+    this._onTouchEnd = null;
+
+    /**
+    * @property {function} _onTouchEnter - Internal event handler reference.
+    * @private
+    */
+    this._onTouchEnter = null;
+
+    /**
+    * @property {function} _onTouchLeave - Internal event handler reference.
+    * @private
+    */
+    this._onTouchLeave = null;
+
+    /**
+    * @property {function} _onTouchCancel - Internal event handler reference.
+    * @private
+    */
+    this._onTouchCancel = null;
+
+    /**
+    * @property {function} _onTouchMove - Internal event handler reference.
+    * @private
+    */
+    this._onTouchMove = null;
+
+};
+
+Phaser.Touch.prototype = {
+
+    /**
+    * Starts the event listeners running.
+    * @method Phaser.Touch#start
+    */
+    start: function () {
+
+        if (this._onTouchStart !== null)
+        {
+            //  Avoid setting multiple listeners
+            return;
+        }
+
+        var _this = this;
+
+        if (this.game.device.touch)
+        {
+            this._onTouchStart = function (event) {
+                return _this.onTouchStart(event);
+            };
+
+            this._onTouchMove = function (event) {
+                return _this.onTouchMove(event);
+            };
+
+            this._onTouchEnd = function (event) {
+                return _this.onTouchEnd(event);
+            };
+
+            this._onTouchEnter = function (event) {
+                return _this.onTouchEnter(event);
+            };
+
+            this._onTouchLeave = function (event) {
+                return _this.onTouchLeave(event);
+            };
+
+            this._onTouchCancel = function (event) {
+                return _this.onTouchCancel(event);
+            };
+
+            this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
+            this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
+            this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
+            this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
+
+            if (!this.game.device.cocoonJS)
+            {
+                this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
+                this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
+            }
+        }
+
+    },
+
+    /**
+    * Consumes all touchmove events on the document (only enable this if you know you need it!).
+    * @method Phaser.Touch#consumeTouchMove
+    */
+    consumeDocumentTouches: function () {
+
+        this._documentTouchMove = function (event) {
+            event.preventDefault();
+        };
+
+        document.addEventListener('touchmove', this._documentTouchMove, false);
+
+    },
+
+    /**
+    * Adds a callback that is fired when a browser touchstart event is received.
+    *
+    * This is used internally to handle audio and video unlocking on mobile devices.
+    *
+    * If the callback returns 'true' then the callback is automatically deleted once invoked.
+    *
+    * The callback is added to the Phaser.Touch.touchLockCallbacks array and should be removed with Phaser.Touch.removeTouchLockCallback.
+    * 
+    * @method Phaser.Touch#addTouchLockCallback
+    * @param {function} callback - The callback that will be called when a touchstart event is received.
+    * @param {object} context - The context in which the callback will be called.
+    */
+    addTouchLockCallback: function (callback, context) {
+
+        this.touchLockCallbacks.push({ callback: callback, context: context });
+
+    },
+
+    /**
+    * Removes the callback at the defined index from the Phaser.Touch.touchLockCallbacks array
+    * 
+    * @method Phaser.Touch#removeTouchLockCallback
+    * @param {function} callback - The callback to be removed.
+    * @param {object} context - The context in which the callback exists.
+    * @return {boolean} True if the callback was deleted, otherwise false.
+    */
+    removeTouchLockCallback: function (callback, context) {
+
+        var i = this.touchLockCallbacks.length;
+
+        while (i--)
+        {
+            if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context)
+            {
+                this.touchLockCallbacks.splice(i, 1);
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * The internal method that handles the touchstart event from the browser.
+    * @method Phaser.Touch#onTouchStart
+    * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
+    */
+    onTouchStart: function (event) {
+
+        var i = this.touchLockCallbacks.length;
+
+        while (i--)
+        {
+            if (this.touchLockCallbacks[i].callback.call(this.touchLockCallbacks[i].context, this, event))
+            {
+                this.touchLockCallbacks.splice(i, 1);
+            }
+        }
+
+        this.event = event;
+
+        if (!this.game.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        if (this.touchStartCallback)
+        {
+            this.touchStartCallback.call(this.callbackContext, event);
+        }
+
+        if (this.preventDefault)
+        {
+            event.preventDefault();
+        }
+
+        //  event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
+        //  event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
+        //  event.changedTouches = the touches that CHANGED in this event, not the total number of them
+        for (var i = 0; i < event.changedTouches.length; i++)
+        {
+            this.game.input.startPointer(event.changedTouches[i]);
+        }
+
+    },
+
+    /**
+    * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
+    * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
+    * @method Phaser.Touch#onTouchCancel
+    * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
+    */
+    onTouchCancel: function (event) {
+
+        this.event = event;
+
+        if (this.touchCancelCallback)
+        {
+            this.touchCancelCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.game.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        if (this.preventDefault)
+        {
+            event.preventDefault();
+        }
+
+        //  Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
+        //  http://www.w3.org/TR/touch-events/#dfn-touchcancel
+        for (var i = 0; i < event.changedTouches.length; i++)
+        {
+            this.game.input.stopPointer(event.changedTouches[i]);
+        }
+
+    },
+
+    /**
+    * For touch enter and leave its a list of the touch points that have entered or left the target.
+    * Doesn't appear to be supported by most browsers on a canvas element yet.
+    * @method Phaser.Touch#onTouchEnter
+    * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
+    */
+    onTouchEnter: function (event) {
+
+        this.event = event;
+
+        if (this.touchEnterCallback)
+        {
+            this.touchEnterCallback.call(this.callbackContext, event);
+        }
+
+        if (!this.game.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        if (this.preventDefault)
+        {
+            event.preventDefault();
+        }
+
+    },
+
+    /**
+    * For touch enter and leave its a list of the touch points that have entered or left the target.
+    * Doesn't appear to be supported by most browsers on a canvas element yet.
+    * @method Phaser.Touch#onTouchLeave
+    * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
+    */
+    onTouchLeave: function (event) {
+
+        this.event = event;
+
+        if (this.touchLeaveCallback)
+        {
+            this.touchLeaveCallback.call(this.callbackContext, event);
+        }
+
+        if (this.preventDefault)
+        {
+            event.preventDefault();
+        }
+
+    },
+
+    /**
+    * The handler for the touchmove events.
+    * @method Phaser.Touch#onTouchMove
+    * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
+    */
+    onTouchMove: function (event) {
+
+        this.event = event;
+
+        if (this.touchMoveCallback)
+        {
+            this.touchMoveCallback.call(this.callbackContext, event);
+        }
+
+        if (this.preventDefault)
+        {
+            event.preventDefault();
+        }
+
+        for (var i = 0; i < event.changedTouches.length; i++)
+        {
+            this.game.input.updatePointer(event.changedTouches[i]);
+        }
+
+    },
+
+    /**
+    * The handler for the touchend events.
+    * @method Phaser.Touch#onTouchEnd
+    * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
+    */
+    onTouchEnd: function (event) {
+
+        this.event = event;
+
+        if (this.touchEndCallback)
+        {
+            this.touchEndCallback.call(this.callbackContext, event);
+        }
+
+        if (this.preventDefault)
+        {
+            event.preventDefault();
+        }
+
+        //  For touch end its a list of the touch points that have been removed from the surface
+        //  https://developer.mozilla.org/en-US/docs/DOM/TouchList
+        //  event.changedTouches = the touches that CHANGED in this event, not the total number of them
+        for (var i = 0; i < event.changedTouches.length; i++)
+        {
+            this.game.input.stopPointer(event.changedTouches[i]);
+        }
+
+    },
+
+    /**
+    * Stop the event listeners.
+    * @method Phaser.Touch#stop
+    */
+    stop: function () {
+
+        if (this.game.device.touch)
+        {
+            this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
+            this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
+            this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
+            this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
+            this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
+            this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
+        }
+
+    }
+
+};
+
+Phaser.Touch.prototype.constructor = Phaser.Touch;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
+*
+* @class Phaser.InputHandler
+* @constructor
+* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
+*/
+Phaser.InputHandler = function (sprite) {
+
+    /**
+    * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
+    */
+    this.sprite = sprite;
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = sprite.game;
+
+    /**
+    * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
+    * @default
+    */
+    this.enabled = false;
+
+    /**
+    * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks.
+    * @protected
+    */
+    this.checked = false;
+
+    /**
+    * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have
+    * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can
+    * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events.
+    * @property {number} priorityID
+    * @default
+    */
+    this.priorityID = 0;
+
+    /**
+    * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
+    * @default
+    */
+    this.useHandCursor = false;
+
+    /**
+    * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
+    * @private
+    */
+    this._setHandCursor = false;
+
+    /**
+    * @property {boolean} isDragged - true if the Sprite is being currently dragged.
+    * @default
+    */
+    this.isDragged = false;
+
+    /**
+    * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
+    * @default
+    */
+    this.allowHorizontalDrag = true;
+
+    /**
+    * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
+    * @default
+    */
+    this.allowVerticalDrag = true;
+
+    /**
+    * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within.
+    * @default
+    */
+    this.bringToTop = false;
+
+    /**
+    * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
+    * @default
+    */
+    this.snapOffset = null;
+
+    /**
+    * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not.
+    * @default
+    */
+    this.snapOnDrag = false;
+
+    /**
+    * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
+    * @default
+    */
+    this.snapOnRelease = false;
+
+    /**
+    * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
+    * @default
+    */
+    this.snapX = 0;
+
+    /**
+    * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
+    * @default
+    */
+    this.snapY = 0;
+
+    /**
+    * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
+    * @default
+    */
+    this.snapOffsetX = 0;
+
+    /**
+    * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
+    * @default
+    */
+    this.snapOffsetY = 0;
+
+    /**
+    * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
+    * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
+    * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope.
+    * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick.
+    * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
+    * @default
+    */
+    this.pixelPerfectOver = false;
+
+    /**
+    * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
+    * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
+    * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope.
+    * Warning: This is expensive so only enable if you really need it.
+    * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
+    * @default
+    */
+    this.pixelPerfectClick = false;
+
+    /**
+    * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit.
+    * @default
+    */
+    this.pixelPerfectAlpha = 255;
+
+    /**
+    * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
+    * @default
+    */
+    this.draggable = false;
+
+    /**
+    * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
+    * @default
+    */
+    this.boundsRect = null;
+
+    /**
+    * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
+    * @default
+    */
+    this.boundsSprite = null;
+
+    /**
+    * If this object is set to consume the pointer event then it will stop all propagation from this object on.
+    * For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it.
+    * @property {boolean} consumePointerEvent
+    * @default
+    */
+    this.consumePointerEvent = false;
+
+    /**
+    * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future.
+    */
+    this.scaleLayer = false;
+
+    /**
+    * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from.
+    */
+    this.dragOffset = new Phaser.Point();
+
+    /**
+    * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it?
+    */
+    this.dragFromCenter = false;
+
+    /**
+    * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position.
+    */
+    this.dragStartPoint = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event.
+    */
+    this.snapPoint = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} _dragPoint - Internal cache var.
+    * @private
+    */
+    this._dragPoint = new Phaser.Point();
+
+    /**
+    * @property {boolean} _dragPhase - Internal cache var.
+    * @private
+    */
+    this._dragPhase = false;
+
+    /**
+    * @property {boolean} _wasEnabled - Internal cache var.
+    * @private
+    */
+    this._wasEnabled = false;
+
+    /**
+    * @property {Phaser.Point} _tempPoint - Internal cache var.
+    * @private
+    */
+    this._tempPoint = new Phaser.Point();
+
+    /**
+    * @property {array} _pointerData - Internal cache var.
+    * @private
+    */
+    this._pointerData = [];
+
+    this._pointerData.push({
+        id: 0,
+        x: 0,
+        y: 0,
+        isDown: false,
+        isUp: false,
+        isOver: false,
+        isOut: false,
+        timeOver: 0,
+        timeOut: 0,
+        timeDown: 0,
+        timeUp: 0,
+        downDuration: 0,
+        isDragged: false
+    });
+
+};
+
+Phaser.InputHandler.prototype = {
+
+    /**
+    * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority.
+    * @method Phaser.InputHandler#start
+    * @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
+    * @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
+    * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
+    */
+    start: function (priority, useHandCursor) {
+
+        priority = priority || 0;
+        if (useHandCursor === undefined) { useHandCursor = false; }
+
+        //  Turning on
+        if (this.enabled === false)
+        {
+            //  Register, etc
+            this.game.input.interactiveItems.add(this);
+            this.useHandCursor = useHandCursor;
+            this.priorityID = priority;
+
+            for (var i = 0; i < 10; i++)
+            {
+                this._pointerData[i] = {
+                    id: i,
+                    x: 0,
+                    y: 0,
+                    isDown: false,
+                    isUp: false,
+                    isOver: false,
+                    isOut: false,
+                    timeOver: 0,
+                    timeOut: 0,
+                    timeDown: 0,
+                    timeUp: 0,
+                    downDuration: 0,
+                    isDragged: false
+                };
+            }
+
+            this.snapOffset = new Phaser.Point();
+            this.enabled = true;
+            this._wasEnabled = true;
+
+        }
+
+        this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
+        this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
+
+        this.flagged = false;
+
+        return this.sprite;
+
+    },
+
+    /**
+    * Handles when the parent Sprite is added to a new Group.
+    *
+    * @method Phaser.InputHandler#addedToGroup
+    * @private
+    */
+    addedToGroup: function () {
+
+        if (this._dragPhase)
+        {
+            return;
+        }
+
+        if (this._wasEnabled && !this.enabled)
+        {
+            this.start();
+        }
+
+    },
+
+    /**
+    * Handles when the parent Sprite is removed from a Group.
+    *
+    * @method Phaser.InputHandler#removedFromGroup
+    * @private
+    */
+    removedFromGroup: function () {
+
+        if (this._dragPhase)
+        {
+            return;
+        }
+
+        if (this.enabled)
+        {
+            this._wasEnabled = true;
+            this.stop();
+        }
+        else
+        {
+            this._wasEnabled = false;
+        }
+
+    },
+
+    /**
+    * Resets the Input Handler and disables it.
+    * @method Phaser.InputHandler#reset
+    */
+    reset: function () {
+
+        this.enabled = false;
+        this.flagged = false;
+
+        for (var i = 0; i < 10; i++)
+        {
+            this._pointerData[i] = {
+                id: i,
+                x: 0,
+                y: 0,
+                isDown: false,
+                isUp: false,
+                isOver: false,
+                isOut: false,
+                timeOver: 0,
+                timeOut: 0,
+                timeDown: 0,
+                timeUp: 0,
+                downDuration: 0,
+                isDragged: false
+            };
+        }
+    },
+
+    /**
+    * Stops the Input Handler from running.
+    * @method Phaser.InputHandler#stop
+    */
+    stop: function () {
+
+        //  Turning off
+        if (this.enabled === false)
+        {
+            return;
+        }
+        else
+        {
+            //  De-register, etc
+            this.enabled = false;
+            this.game.input.interactiveItems.remove(this);
+        }
+
+    },
+
+    /**
+    * Clean up memory.
+    * @method Phaser.InputHandler#destroy
+    */
+    destroy: function () {
+
+        if (this.sprite)
+        {
+            if (this._setHandCursor)
+            {
+                this.game.canvas.style.cursor = "default";
+                this._setHandCursor = false;
+            }
+
+            this.enabled = false;
+
+            this.game.input.interactiveItems.remove(this);
+
+            this._pointerData.length = 0;
+            this.boundsRect = null;
+            this.boundsSprite = null;
+            this.sprite = null;
+        }
+
+    },
+
+    /**
+    * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
+    * This is called by Phaser.Pointer and shouldn't typically be called directly.
+    *
+    * @method Phaser.InputHandler#validForInput
+    * @protected
+    * @param {number} highestID - The highest ID currently processed by the Pointer.
+    * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
+    * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid?
+    * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
+    */
+    validForInput: function (highestID, highestRenderID, includePixelPerfect) {
+
+        if (includePixelPerfect === undefined) { includePixelPerfect = true; }
+
+        if (this.sprite.scale.x === 0 || this.sprite.scale.y === 0 || this.priorityID < this.game.input.minPriorityID)
+        {
+            return false;
+        }
+
+        //   If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it
+        if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver))
+        {
+            return false;
+        }
+
+        if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID < highestRenderID))
+        {
+            return true;
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Is this object using pixel perfect checking?
+    *
+    * @method Phaser.InputHandler#isPixelPerfect
+    * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`.
+    */
+    isPixelPerfect: function () {
+
+        return (this.pixelPerfectClick || this.pixelPerfectOver);
+
+    },
+
+    /**
+    * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
+    * This value is only set when the pointer is over this Sprite.
+    *
+    * @method Phaser.InputHandler#pointerX
+    * @param {number} pointer - The index of the pointer to check. You can get this from Phaser.Pointer.id.
+    * @return {number} The x coordinate of the Input pointer.
+    */
+    pointerX: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].x;
+
+    },
+
+    /**
+    * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
+    * This value is only set when the pointer is over this Sprite.
+    *
+    * @method Phaser.InputHandler#pointerY
+    * @param {number} pointer - The index of the pointer to check. You can get this from Phaser.Pointer.id.
+    * @return {number} The y coordinate of the Input pointer.
+    */
+    pointerY: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].y;
+
+    },
+
+    /**
+    * If the Pointer is down this returns true. Please note that it only checks if the Pointer is down, not if it's down over any specific Sprite.
+    *
+    * @method Phaser.InputHandler#pointerDown
+    * @param {number} pointer - The index of the pointer to check. You can get this from Phaser.Pointer.id.
+    * @return {boolean} - True if the given pointer is down, otherwise false.
+    */
+    pointerDown: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].isDown;
+
+    },
+
+    /**
+    * If the Pointer is up this returns true. Please note that it only checks if the Pointer is up, not if it's up over any specific Sprite.
+    *
+    * @method Phaser.InputHandler#pointerUp
+    * @param {number} pointer - The index of the pointer to check. You can get this from Phaser.Pointer.id.
+    * @return {boolean} - True if the given pointer is up, otherwise false.
+    */
+    pointerUp: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].isUp;
+
+    },
+
+    /**
+    * A timestamp representing when the Pointer first touched the touchscreen.
+    *
+    * @method Phaser.InputHandler#pointerTimeDown
+    * @param {number} pointer - The index of the pointer to check. You can get this from Phaser.Pointer.id.
+    * @return {number}
+    */
+    pointerTimeDown: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].timeDown;
+
+    },
+
+    /**
+    * A timestamp representing when the Pointer left the touchscreen.
+    * @method Phaser.InputHandler#pointerTimeUp
+    * @param {Phaser.Pointer} pointer
+    * @return {number}
+    */
+    pointerTimeUp: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].timeUp;
+
+    },
+
+    /**
+    * Is the Pointer over this Sprite?
+    *
+    * @method Phaser.InputHandler#pointerOver
+    * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
+    * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object.
+    */
+    pointerOver: function (index) {
+
+        if (this.enabled)
+        {
+            if (index === undefined)
+            {
+                for (var i = 0; i < 10; i++)
+                {
+                    if (this._pointerData[i].isOver)
+                    {
+                        return true;
+                    }
+                }
+            }
+            else
+            {
+                return this._pointerData[index].isOver;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Is the Pointer outside of this Sprite?
+    * @method Phaser.InputHandler#pointerOut
+    * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
+    * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
+    */
+    pointerOut: function (index) {
+
+        if (this.enabled)
+        {
+            if (index === undefined)
+            {
+                for (var i = 0; i < 10; i++)
+                {
+                    if (this._pointerData[i].isOut)
+                    {
+                        return true;
+                    }
+                }
+            }
+            else
+            {
+                return this._pointerData[index].isOut;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * A timestamp representing when the Pointer first touched the touchscreen.
+    * @method Phaser.InputHandler#pointerTimeOver
+    * @param {Phaser.Pointer} pointer
+    * @return {number}
+    */
+    pointerTimeOver: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].timeOver;
+
+    },
+
+    /**
+    * A timestamp representing when the Pointer left the touchscreen.
+    * @method Phaser.InputHandler#pointerTimeOut
+    * @param {Phaser.Pointer} pointer
+    * @return {number}
+    */
+    pointerTimeOut: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].timeOut;
+
+    },
+
+    /**
+    * Is this sprite being dragged by the mouse or not?
+    * @method Phaser.InputHandler#pointerDragged
+    * @param {Phaser.Pointer} pointer
+    * @return {boolean} True if the pointer is dragging an object, otherwise false.
+    */
+    pointerDragged: function (pointer) {
+
+        pointer = pointer || 0;
+
+        return this._pointerData[pointer].isDragged;
+
+    },
+
+    /**
+    * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to.
+    * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
+    *
+    * @method Phaser.InputHandler#checkPointerDown
+    * @param {Phaser.Pointer} pointer
+    * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
+    * @return {boolean} True if the pointer is down, otherwise false.
+    */
+    checkPointerDown: function (pointer, fastTest) {
+
+        if (!pointer.isDown || !this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
+        {
+            return false;
+        }
+
+        //  Need to pass it a temp point, in case we need it again for the pixel check
+        if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
+        {
+            if (fastTest === undefined) { fastTest = false; }
+
+            if (!fastTest && this.pixelPerfectClick)
+            {
+                return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
+            }
+            else
+            {
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Checks if the given pointer is over the Sprite this InputHandler belongs to.
+    * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
+    *
+    * @method Phaser.InputHandler#checkPointerOver
+    * @param {Phaser.Pointer} pointer
+    * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
+    * @return {boolean}
+    */
+    checkPointerOver: function (pointer, fastTest) {
+
+        if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
+        {
+            return false;
+        }
+
+        //  Need to pass it a temp point, in case we need it again for the pixel check
+        if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
+        {
+            if (fastTest === undefined) { fastTest = false; }
+
+            if (!fastTest && this.pixelPerfectOver)
+            {
+                return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
+            }
+            else
+            {
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
+    * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
+    * @method Phaser.InputHandler#checkPixel
+    * @param {number} x - The x coordinate to check.
+    * @param {number} y - The y coordinate to check.
+    * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
+    * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
+    */
+    checkPixel: function (x, y, pointer) {
+
+        //  Grab a pixel from our image into the hitCanvas and then test it
+        if (this.sprite.texture.baseTexture.source)
+        {
+            if (x === null && y === null)
+            {
+                //  Use the pointer parameter
+                this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
+
+                var x = this._tempPoint.x;
+                var y = this._tempPoint.y;
+            }
+
+            if (this.sprite.anchor.x !== 0)
+            {
+                x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
+            }
+
+            if (this.sprite.anchor.y !== 0)
+            {
+                y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
+            }
+
+            x += this.sprite.texture.frame.x;
+            y += this.sprite.texture.frame.y;
+
+            if (this.sprite.texture.trim)
+            {
+                x -= this.sprite.texture.trim.x;
+                y -= this.sprite.texture.trim.y;
+
+                //  If the coordinates are outside the trim area we return false immediately, to save doing a draw call
+                if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom)
+                {
+                    this._dx = x;
+                    this._dy = y;
+                    return false;
+                }
+            }
+
+            this._dx = x;
+            this._dy = y;
+
+            this.game.input.hitContext.clearRect(0, 0, 1, 1);
+            this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
+
+            var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
+
+            if (rgb.data[3] >= this.pixelPerfectAlpha)
+            {
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Update.
+    * 
+    * @method Phaser.InputHandler#update
+    * @protected
+    * @param {Phaser.Pointer} pointer
+    */
+    update: function (pointer) {
+
+        if (this.sprite === null || this.sprite.parent === undefined)
+        {
+            //  Abort. We've been destroyed.
+            return;
+        }
+
+        if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
+        {
+            this._pointerOutHandler(pointer);
+            return false;
+        }
+
+        if (this.draggable && this._draggedPointerID === pointer.id)
+        {
+            return this.updateDrag(pointer);
+        }
+        else if (this._pointerData[pointer.id].isOver)
+        {
+            if (this.checkPointerOver(pointer))
+            {
+                this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
+                this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
+                return true;
+            }
+            else
+            {
+                this._pointerOutHandler(pointer);
+                return false;
+            }
+        }
+    },
+
+    /**
+    * Internal method handling the pointer over event.
+    * 
+    * @method Phaser.InputHandler#_pointerOverHandler
+    * @private
+    * @param {Phaser.Pointer} pointer - The pointer that triggered the event
+    */
+    _pointerOverHandler: function (pointer) {
+
+        if (this.sprite === null)
+        {
+            //  Abort. We've been destroyed.
+            return;
+        }
+
+        if (this._pointerData[pointer.id].isOver === false || pointer.dirty)
+        {
+            this._pointerData[pointer.id].isOver = true;
+            this._pointerData[pointer.id].isOut = false;
+            this._pointerData[pointer.id].timeOver = this.game.time.time;
+            this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
+            this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
+
+            if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
+            {
+                this.game.canvas.style.cursor = "pointer";
+                this._setHandCursor = true;
+            }
+
+            if (this.sprite && this.sprite.events)
+            {
+                this.sprite.events.onInputOver$dispatch(this.sprite, pointer);
+            }
+        }
+
+    },
+
+    /**
+    * Internal method handling the pointer out event.
+    * 
+    * @method Phaser.InputHandler#_pointerOutHandler
+    * @private
+    * @param {Phaser.Pointer} pointer - The pointer that triggered the event.
+    */
+    _pointerOutHandler: function (pointer) {
+
+        if (this.sprite === null)
+        {
+            //  Abort. We've been destroyed.
+            return;
+        }
+
+        this._pointerData[pointer.id].isOver = false;
+        this._pointerData[pointer.id].isOut = true;
+        this._pointerData[pointer.id].timeOut = this.game.time.time;
+
+        if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
+        {
+            this.game.canvas.style.cursor = "default";
+            this._setHandCursor = false;
+        }
+
+        if (this.sprite && this.sprite.events)
+        {
+            this.sprite.events.onInputOut$dispatch(this.sprite, pointer);
+        }
+
+    },
+
+    /**
+    * Internal method handling the touched / clicked event.
+    * 
+    * @method Phaser.InputHandler#_touchedHandler
+    * @private
+    * @param {Phaser.Pointer} pointer - The pointer that triggered the event.
+    */
+    _touchedHandler: function (pointer) {
+
+        if (this.sprite === null)
+        {
+            //  Abort. We've been destroyed.
+            return;
+        }
+
+        if (!this._pointerData[pointer.id].isDown && this._pointerData[pointer.id].isOver)
+        {
+            if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
+            {
+                return;
+            }
+
+            this._pointerData[pointer.id].isDown = true;
+            this._pointerData[pointer.id].isUp = false;
+            this._pointerData[pointer.id].timeDown = this.game.time.time;
+
+            if (this.sprite && this.sprite.events)
+            {
+                this.sprite.events.onInputDown$dispatch(this.sprite, pointer);
+            }
+
+            //  It's possible the onInputDown event created a new Sprite that is on-top of this one, so we ought to force a Pointer update
+            pointer.dirty = true;
+
+            //  Start drag
+            if (this.draggable && this.isDragged === false)
+            {
+                this.startDrag(pointer);
+            }
+
+            if (this.bringToTop)
+            {
+                this.sprite.bringToTop();
+            }
+        }
+
+        //  Consume the event?
+        return this.consumePointerEvent;
+
+    },
+
+    /**
+    * Internal method handling the pointer released event.
+    * @method Phaser.InputHandler#_releasedHandler
+    * @private
+    * @param {Phaser.Pointer} pointer
+    */
+    _releasedHandler: function (pointer) {
+
+        if (this.sprite === null)
+        {
+            //  Abort. We've been destroyed.
+            return;
+        }
+
+        //  If was previously touched by this Pointer, check if still is AND still over this item
+        if (this._pointerData[pointer.id].isDown && pointer.isUp)
+        {
+            this._pointerData[pointer.id].isDown = false;
+            this._pointerData[pointer.id].isUp = true;
+            this._pointerData[pointer.id].timeUp = this.game.time.time;
+            this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
+
+            //  Only release the InputUp signal if the pointer is still over this sprite
+            if (this.checkPointerOver(pointer))
+            {
+                //  Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
+                if (this.sprite && this.sprite.events)
+                {
+                    this.sprite.events.onInputUp$dispatch(this.sprite, pointer, true);
+                }
+            }
+            else
+            {
+                //  Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
+                if (this.sprite && this.sprite.events)
+                {
+                    this.sprite.events.onInputUp$dispatch(this.sprite, pointer, false);
+                }
+
+                //  Pointer outside the sprite? Reset the cursor
+                if (this.useHandCursor)
+                {
+                    this.game.canvas.style.cursor = "default";
+                    this._setHandCursor = false;
+                }
+            }
+
+            //  It's possible the onInputUp event created a new Sprite that is on-top of this one, so we ought to force a Pointer update
+            pointer.dirty = true;
+
+            //  Stop drag
+            if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id)
+            {
+                this.stopDrag(pointer);
+            }
+        }
+
+    },
+
+    /**
+    * Updates the Pointer drag on this Sprite.
+    * @method Phaser.InputHandler#updateDrag
+    * @param {Phaser.Pointer} pointer
+    * @return {boolean}
+    */
+    updateDrag: function (pointer) {
+
+        if (pointer.isUp)
+        {
+            this.stopDrag(pointer);
+            return false;
+        }
+
+        var px = this.globalToLocalX(pointer.x) + this._dragPoint.x + this.dragOffset.x;
+        var py = this.globalToLocalY(pointer.y) + this._dragPoint.y + this.dragOffset.y;
+
+        if (this.sprite.fixedToCamera)
+        {
+            if (this.allowHorizontalDrag)
+            {
+                this.sprite.cameraOffset.x = px;
+            }
+
+            if (this.allowVerticalDrag)
+            {
+                this.sprite.cameraOffset.y = py;
+            }
+
+            if (this.boundsRect)
+            {
+                this.checkBoundsRect();
+            }
+
+            if (this.boundsSprite)
+            {
+                this.checkBoundsSprite();
+            }
+
+            if (this.snapOnDrag)
+            {
+                this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
+                this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
+                this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y);
+            }
+        }
+        else
+        {
+            if (this.allowHorizontalDrag)
+            {
+                this.sprite.x = px;
+            }
+
+            if (this.allowVerticalDrag)
+            {
+                this.sprite.y = py;
+            }
+
+            if (this.boundsRect)
+            {
+                this.checkBoundsRect();
+            }
+
+            if (this.boundsSprite)
+            {
+                this.checkBoundsSprite();
+            }
+
+            if (this.snapOnDrag)
+            {
+                this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
+                this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
+                this.snapPoint.set(this.sprite.x, this.sprite.y);
+            }
+        }
+
+        this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint);
+
+        return true;
+
+    },
+
+    /**
+    * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
+    * @method Phaser.InputHandler#justOver
+    * @param {Phaser.Pointer} pointer
+    * @param {number} delay - The time below which the pointer is considered as just over.
+    * @return {boolean}
+    */
+    justOver: function (pointer, delay) {
+
+        pointer = pointer || 0;
+        delay = delay || 500;
+
+        return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
+
+    },
+
+    /**
+    * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
+    * @method Phaser.InputHandler#justOut
+    * @param {Phaser.Pointer} pointer
+    * @param {number} delay - The time below which the pointer is considered as just out.
+    * @return {boolean}
+    */
+    justOut: function (pointer, delay) {
+
+        pointer = pointer || 0;
+        delay = delay || 500;
+
+        return (this._pointerData[pointer].isOut && (this.game.time.time - this._pointerData[pointer].timeOut < delay));
+
+    },
+
+    /**
+    * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
+    * @method Phaser.InputHandler#justPressed
+    * @param {Phaser.Pointer} pointer
+    * @param {number} delay - The time below which the pointer is considered as just over.
+    * @return {boolean}
+    */
+    justPressed: function (pointer, delay) {
+
+        pointer = pointer || 0;
+        delay = delay || 500;
+
+        return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
+
+    },
+
+    /**
+    * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
+    * @method Phaser.InputHandler#justReleased
+    * @param {Phaser.Pointer} pointer
+    * @param {number} delay - The time below which the pointer is considered as just out.
+    * @return {boolean}
+    */
+    justReleased: function (pointer, delay) {
+
+        pointer = pointer || 0;
+        delay = delay || 500;
+
+        return (this._pointerData[pointer].isUp && (this.game.time.time - this._pointerData[pointer].timeUp < delay));
+
+    },
+
+    /**
+    * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
+    * @method Phaser.InputHandler#overDuration
+    * @param {Phaser.Pointer} pointer
+    * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
+    */
+    overDuration: function (pointer) {
+
+        pointer = pointer || 0;
+
+        if (this._pointerData[pointer].isOver)
+        {
+            return this.game.time.time - this._pointerData[pointer].timeOver;
+        }
+
+        return -1;
+
+    },
+
+    /**
+    * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
+    * @method Phaser.InputHandler#downDuration
+    * @param {Phaser.Pointer} pointer
+    * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
+    */
+    downDuration: function (pointer) {
+
+        pointer = pointer || 0;
+
+        if (this._pointerData[pointer].isDown)
+        {
+            return this.game.time.time - this._pointerData[pointer].timeDown;
+        }
+
+        return -1;
+
+    },
+
+    /**
+    * Allow this Sprite to be dragged by any valid pointer.
+    *
+    * When the drag begins the Sprite.events.onDragStart event will be dispatched.
+    * 
+    * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched.
+    *
+    * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually
+    * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`.
+    * 
+    * @method Phaser.InputHandler#enableDrag
+    * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer.
+    * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
+    * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box.
+    * @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
+    * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere.
+    * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here.
+    */
+    enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
+
+        if (lockCenter === undefined) { lockCenter = false; }
+        if (bringToTop === undefined) { bringToTop = false; }
+        if (pixelPerfect === undefined) { pixelPerfect = false; }
+        if (alphaThreshold === undefined) { alphaThreshold = 255; }
+        if (boundsRect === undefined) { boundsRect = null; }
+        if (boundsSprite === undefined) { boundsSprite = null; }
+
+        this._dragPoint = new Phaser.Point();
+        this.draggable = true;
+        this.bringToTop = bringToTop;
+        this.dragOffset = new Phaser.Point();
+        this.dragFromCenter = lockCenter;
+
+        this.pixelPerfectClick = pixelPerfect;
+        this.pixelPerfectAlpha = alphaThreshold;
+
+        if (boundsRect)
+        {
+            this.boundsRect = boundsRect;
+        }
+
+        if (boundsSprite)
+        {
+            this.boundsSprite = boundsSprite;
+        }
+
+    },
+
+    /**
+    * Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks.
+    * @method Phaser.InputHandler#disableDrag
+    */
+    disableDrag: function () {
+
+        if (this._pointerData)
+        {
+            for (var i = 0; i < 10; i++)
+            {
+                this._pointerData[i].isDragged = false;
+            }
+        }
+
+        this.draggable = false;
+        this.isDragged = false;
+        this._draggedPointerID = -1;
+
+    },
+
+    /**
+    * Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
+    * @method Phaser.InputHandler#startDrag
+    * @param {Phaser.Pointer} pointer
+    */
+    startDrag: function (pointer) {
+
+        var x = this.sprite.x;
+        var y = this.sprite.y;
+
+        this.isDragged = true;
+        this._draggedPointerID = pointer.id;
+        this._pointerData[pointer.id].isDragged = true;
+
+        if (this.sprite.fixedToCamera)
+        {
+            if (this.dragFromCenter)
+            {
+                this.sprite.centerOn(pointer.x, pointer.y);
+                this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
+            }
+            else
+            {
+                this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
+            }
+        }
+        else
+        {
+            if (this.dragFromCenter)
+            {
+                var bounds = this.sprite.getBounds();
+
+                this.sprite.x = this.globalToLocalX(pointer.x) + (this.sprite.x - bounds.centerX);
+                this.sprite.y = this.globalToLocalY(pointer.y) + (this.sprite.y - bounds.centerY);
+            }
+
+            this._dragPoint.setTo(this.sprite.x - this.globalToLocalX(pointer.x), this.sprite.y - this.globalToLocalY(pointer.y));
+        }
+
+        this.updateDrag(pointer);
+
+        if (this.bringToTop)
+        {
+            this._dragPhase = true;
+            this.sprite.bringToTop();
+        }
+
+        this.dragStartPoint.set(x, y);
+        this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y);
+
+    },
+
+    /**
+    * Warning: EXPERIMENTAL
+    * @method Phaser.InputHandler#globalToLocalX
+    * @param {number} x
+    */
+    globalToLocalX: function (x) {
+
+        if (this.scaleLayer)
+        {
+            x -= this.game.scale.grid.boundsFluid.x;
+            x *= this.game.scale.grid.scaleFluidInversed.x;
+        }
+
+        return x;
+
+    },
+
+    /**
+    * Warning: EXPERIMENTAL
+    * @method Phaser.InputHandler#globalToLocalY
+    * @param {number} y
+    */
+    globalToLocalY: function (y) {
+
+        if (this.scaleLayer)
+        {
+            y -= this.game.scale.grid.boundsFluid.y;
+            y *= this.game.scale.grid.scaleFluidInversed.y;
+        }
+
+        return y;
+
+    },
+
+    /**
+    * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
+    * @method Phaser.InputHandler#stopDrag
+    * @param {Phaser.Pointer} pointer
+    */
+    stopDrag: function (pointer) {
+
+        this.isDragged = false;
+        this._draggedPointerID = -1;
+        this._pointerData[pointer.id].isDragged = false;
+        this._dragPhase = false;
+
+        if (this.snapOnRelease)
+        {
+            if (this.sprite.fixedToCamera)
+            {
+                this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
+                this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
+            }
+            else
+            {
+                this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
+                this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
+            }
+        }
+
+        this.sprite.events.onDragStop$dispatch(this.sprite, pointer);
+
+        if (this.checkPointerOver(pointer) === false)
+        {
+            this._pointerOutHandler(pointer);
+        }
+
+    },
+
+    /**
+    * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
+    * @method Phaser.InputHandler#setDragLock
+    * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
+    * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
+    */
+    setDragLock: function (allowHorizontal, allowVertical) {
+
+        if (allowHorizontal === undefined) { allowHorizontal = true; }
+        if (allowVertical === undefined) { allowVertical = true; }
+
+        this.allowHorizontalDrag = allowHorizontal;
+        this.allowVerticalDrag = allowVertical;
+
+    },
+
+    /**
+    * Make this Sprite snap to the given grid either during drag or when it's released.
+    * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
+    * @method Phaser.InputHandler#enableSnap
+    * @param {number} snapX - The width of the grid cell to snap to.
+    * @param {number} snapY - The height of the grid cell to snap to.
+    * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
+    * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
+    * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
+    * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid.
+    */
+    enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
+
+        if (onDrag === undefined) { onDrag = true; }
+        if (onRelease === undefined) { onRelease = false; }
+        if (snapOffsetX === undefined) { snapOffsetX = 0; }
+        if (snapOffsetY === undefined) { snapOffsetY = 0; }
+
+        this.snapX = snapX;
+        this.snapY = snapY;
+        this.snapOffsetX = snapOffsetX;
+        this.snapOffsetY = snapOffsetY;
+        this.snapOnDrag = onDrag;
+        this.snapOnRelease = onRelease;
+
+    },
+
+    /**
+    * Stops the sprite from snapping to a grid during drag or release.
+    * @method Phaser.InputHandler#disableSnap
+    */
+    disableSnap: function () {
+
+        this.snapOnDrag = false;
+        this.snapOnRelease = false;
+
+    },
+
+
+    /**
+    * Bounds Rect check for the sprite drag
+    * @method Phaser.InputHandler#checkBoundsRect
+    */
+    checkBoundsRect: function () {
+
+        if (this.sprite.fixedToCamera)
+        {
+            if (this.sprite.cameraOffset.x < this.boundsRect.left)
+            {
+                this.sprite.cameraOffset.x = this.boundsRect.left;
+            }
+            else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
+            {
+                this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
+            }
+
+            if (this.sprite.cameraOffset.y < this.boundsRect.top)
+            {
+                this.sprite.cameraOffset.y = this.boundsRect.top;
+            }
+            else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
+            {
+                this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
+            }
+        }
+        else
+        {
+            if (this.sprite.left < this.boundsRect.left)
+            {
+                this.sprite.x = this.boundsRect.x + this.sprite.offsetX;
+            }
+            else if (this.sprite.right > this.boundsRect.right)
+            {
+                this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX);
+            }
+
+            if (this.sprite.top < this.boundsRect.top)
+            {
+                this.sprite.y = this.boundsRect.top + this.sprite.offsetY;
+            }
+            else if (this.sprite.bottom > this.boundsRect.bottom)
+            {
+                this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY);
+            }
+        }
+
+    },
+
+    /**
+    * Parent Sprite Bounds check for the sprite drag.
+    * @method Phaser.InputHandler#checkBoundsSprite
+    */
+    checkBoundsSprite: function () {
+
+        if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
+        {
+            if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x)
+            {
+                this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x;
+            }
+            else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width))
+            {
+                this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width;
+            }
+
+            if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y)
+            {
+                this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y;
+            }
+            else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height))
+            {
+                this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height;
+            }
+        }
+        else
+        {
+            if (this.sprite.left < this.boundsSprite.left)
+            {
+                this.sprite.x = this.boundsSprite.left + this.sprite.offsetX;
+            }
+            else if (this.sprite.right > this.boundsSprite.right)
+            {
+                this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX);
+            }
+
+            if (this.sprite.top < this.boundsSprite.top)
+            {
+                this.sprite.y = this.boundsSprite.top + this.sprite.offsetY;
+            }
+            else if (this.sprite.bottom > this.boundsSprite.bottom)
+            {
+                this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY);
+            }
+
+            // if (this.sprite.x < this.boundsSprite.x)
+            // {
+            //     this.sprite.x = this.boundsSprite.x;
+            // }
+            // else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
+            // {
+            //     this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
+            // }
+
+            // if (this.sprite.y < this.boundsSprite.y)
+            // {
+            //     this.sprite.y = this.boundsSprite.y;
+            // }
+            // else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
+            // {
+            //     this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
+            // }
+        }
+
+    }
+
+};
+
+Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
+
+/**
+* @author       @karlmacklin <tacklemcclean@gmail.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Gamepad class handles gamepad input and dispatches gamepad events.
+*
+* Remember to call `gamepad.start()`.
+*
+* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
+* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
+* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
+* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller.
+*
+* @class Phaser.Gamepad
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Gamepad = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
+    * @private
+    */
+    this._gamepadIndexMap = {};
+
+    /**
+    * @property {Array} _rawPads - The raw state of the gamepads from the browser
+    * @private
+    */
+    this._rawPads = [];
+
+    /**
+    * @property {boolean} _active - Private flag for whether or not the API is polled
+    * @private
+    * @default
+    */
+    this._active = false;
+
+    /**
+    * Gamepad input will only be processed if enabled.
+    * @property {boolean} enabled
+    * @default
+    */
+    this.enabled = true;
+
+    /**
+    * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation.
+    * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
+    * @private
+    */
+    this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') != -1) || !!navigator.getGamepads;
+
+    /**
+    * Used to check for differences between earlier polls and current state of gamepads.
+    * @property {Array} _prevRawGamepadTypes
+    * @private
+    * @default
+    */
+    this._prevRawGamepadTypes = [];
+
+    /**
+    * Used to check for differences between earlier polls and current state of gamepads.
+    * @property {Array} _prevTimestamps
+    * @private
+    * @default
+    */
+    this._prevTimestamps = [];
+
+    /**
+    * @property {object} callbackContext - The context under which the callbacks are run.
+    */
+    this.callbackContext = this;
+
+    /**
+    * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
+    */
+    this.onConnectCallback = null;
+
+    /**
+    * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
+    */
+    this.onDisconnectCallback = null;
+
+    /**
+    * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
+    */
+    this.onDownCallback = null;
+
+    /**
+    * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
+    */
+    this.onUpCallback = null;
+
+    /**
+    * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
+    */
+    this.onAxisCallback = null;
+
+    /**
+    * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
+    */
+    this.onFloatCallback = null;
+
+    /**
+    * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
+    * @private
+    */
+    this._ongamepadconnected = null;
+
+    /**
+    * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
+    * @private
+    */
+    this._gamepaddisconnected = null;
+
+    /**
+    * @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
+    * @private
+    */
+    this._gamepads = [
+        new Phaser.SinglePad(game, this),
+        new Phaser.SinglePad(game, this),
+        new Phaser.SinglePad(game, this),
+        new Phaser.SinglePad(game, this)
+    ];
+
+};
+
+Phaser.Gamepad.prototype = {
+
+    /**
+    * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons.
+    * 
+    * @method Phaser.Gamepad#addCallbacks
+    * @param {object} context - The context under which the callbacks are run.
+    * @param {object} callbacks - Object that takes six different callback methods:
+    * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
+    */
+    addCallbacks: function (context, callbacks) {
+
+        if (typeof callbacks !== 'undefined')
+        {
+            this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
+            this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
+            this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
+            this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
+            this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
+            this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
+            this.callbackContext = context;
+        }
+
+    },
+
+    /**
+    * Starts the Gamepad event handling.
+    * This MUST be called manually before Phaser will start polling the Gamepad API.
+    *
+    * @method Phaser.Gamepad#start
+    */
+    start: function () {
+
+        if (this._active)
+        {
+            //  Avoid setting multiple listeners
+            return;
+        }
+
+        this._active = true;
+
+        var _this = this;
+
+        this._onGamepadConnected = function (event) {
+            return _this.onGamepadConnected(event);
+        };
+
+        this._onGamepadDisconnected = function (event) {
+            return _this.onGamepadDisconnected(event);
+        };
+
+        window.addEventListener('gamepadconnected', this._onGamepadConnected, false);
+        window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false);
+
+    },
+
+    /**
+     * Handles the connection of a Gamepad.
+     *
+     * @method onGamepadConnected
+     * @private
+     * @param {object} event - The DOM event.
+     */
+    onGamepadConnected: function (event) {
+
+        var newPad = event.gamepad;
+        this._rawPads.push(newPad);
+        this._gamepads[newPad.index].connect(newPad);
+
+    },
+
+    /**
+     * Handles the disconnection of a Gamepad.
+     *
+     * @method onGamepadDisconnected
+     * @private
+     * @param {object} event - The DOM event.
+     */
+    onGamepadDisconnected: function (event) {
+
+        var removedPad = event.gamepad;
+
+        for (var i in this._rawPads)
+        {
+            if (this._rawPads[i].index === removedPad.index)
+            {
+                this._rawPads.splice(i,1);
+            }
+        }
+
+        this._gamepads[removedPad.index].disconnect();
+
+    },
+
+    /**
+    * Main gamepad update loop. Should not be called manually.
+    * @method Phaser.Gamepad#update
+    * @protected
+    */
+    update: function () {
+
+        this._pollGamepads();
+
+        this.pad1.pollStatus();
+        this.pad2.pollStatus();
+        this.pad3.pollStatus();
+        this.pad4.pollStatus();
+
+    },
+
+    /**
+    * Updating connected gamepads (for Google Chrome). Should not be called manually.
+    * 
+    * @method Phaser.Gamepad#_pollGamepads
+    * @private
+    */
+    _pollGamepads: function () {
+
+        if (navigator['getGamepads'])
+        {
+            var rawGamepads = navigator.getGamepads();
+        }
+        else if (navigator['webkitGetGamepads'])
+        {
+            var rawGamepads = navigator.webkitGetGamepads();
+        }
+        else if (navigator['webkitGamepads'])
+        {
+            var rawGamepads = navigator.webkitGamepads();
+        }
+
+        if (rawGamepads)
+        {
+            this._rawPads = [];
+
+            var gamepadsChanged = false;
+
+            for (var i = 0; i < rawGamepads.length; i++)
+            {
+                if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
+                {
+                    gamepadsChanged = true;
+                    this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
+                }
+
+                if (rawGamepads[i])
+                {
+                    this._rawPads.push(rawGamepads[i]);
+                }
+
+                // Support max 4 pads at the moment
+                if (i === 3)
+                {
+                    break;
+                }
+            }
+
+            if (gamepadsChanged)
+            {
+                var validConnections = { rawIndices: {}, padIndices: {} };
+                var singlePad;
+
+                for (var j = 0; j < this._gamepads.length; j++)
+                {
+                    singlePad = this._gamepads[j];
+
+                    if (singlePad.connected)
+                    {
+                        for (var k = 0; k < this._rawPads.length; k++)
+                        {
+                            if (this._rawPads[k].index === singlePad.index)
+                            {
+                                validConnections.rawIndices[singlePad.index] = true;
+                                validConnections.padIndices[j] = true;
+                            }
+                        }
+                    }
+                }
+
+                for (var l = 0; l < this._gamepads.length; l++)
+                {
+                    singlePad = this._gamepads[l];
+
+                    if (validConnections.padIndices[l])
+                    {
+                        continue;
+                    }
+
+                    if (this._rawPads.length < 1)
+                    {
+                        singlePad.disconnect();
+                    }
+
+                    for (var m = 0; m < this._rawPads.length; m++)
+                    {
+                        if (validConnections.padIndices[l])
+                        {
+                            break;
+                        }
+
+                        var rawPad = this._rawPads[m];
+
+                        if (rawPad)
+                        {
+                            if (validConnections.rawIndices[rawPad.index])
+                            {
+                                singlePad.disconnect();
+                                continue;
+                            }
+                            else
+                            {
+                                singlePad.connect(rawPad);
+                                validConnections.rawIndices[rawPad.index] = true;
+                                validConnections.padIndices[l] = true;
+                            }
+                        }
+                        else
+                        {
+                            singlePad.disconnect();
+                        }
+                    }
+                }
+            }
+        }
+    },
+
+    /**
+    * Sets the deadZone variable for all four gamepads
+    * @method Phaser.Gamepad#setDeadZones
+    */
+    setDeadZones: function (value) {
+
+        for (var i = 0; i < this._gamepads.length; i++)
+        {
+            this._gamepads[i].deadZone = value;
+        }
+
+    },
+
+    /**
+    * Stops the Gamepad event handling.
+    *
+    * @method Phaser.Gamepad#stop
+    */
+    stop: function () {
+
+        this._active = false;
+
+        window.removeEventListener('gamepadconnected', this._onGamepadConnected);
+        window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected);
+
+    },
+
+    /**
+    * Reset all buttons/axes of all gamepads
+    * @method Phaser.Gamepad#reset
+    */
+    reset: function () {
+
+        this.update();
+
+        for (var i = 0; i < this._gamepads.length; i++)
+        {
+            this._gamepads[i].reset();
+        }
+
+    },
+
+    /**
+    * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
+    * @method Phaser.Gamepad#justPressed
+    * @param {number} buttonCode - The buttonCode of the button to check for.
+    * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
+    * @return {boolean} True if the button is just pressed otherwise false.
+    */
+    justPressed: function (buttonCode, duration) {
+
+        for (var i = 0; i < this._gamepads.length; i++)
+        {
+            if (this._gamepads[i].justPressed(buttonCode, duration) === true)
+            {
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms).
+    * @method Phaser.Gamepad#justPressed
+    * @param {number} buttonCode - The buttonCode of the button to check for.
+    * @param {number} [duration=250] - The duration below which the button is considered as being just released.
+    * @return {boolean} True if the button is just released otherwise false.
+    */
+    justReleased: function (buttonCode, duration) {
+
+        for (var i = 0; i < this._gamepads.length; i++)
+        {
+            if (this._gamepads[i].justReleased(buttonCode, duration) === true)
+            {
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Returns true if the button is currently pressed down, on ANY gamepad.
+    * @method Phaser.Gamepad#isDown
+    * @param {number} buttonCode - The buttonCode of the button to check for.
+    * @return {boolean} True if a button is currently down.
+    */
+    isDown: function (buttonCode) {
+
+        for (var i = 0; i < this._gamepads.length; i++)
+        {
+            if (this._gamepads[i].isDown(buttonCode) === true)
+            {
+                return true;
+            }
+        }
+
+        return false;
+    },
+
+    /**
+     * Destroys this object and the associated event listeners.
+     *
+     * @method Phaser.Gamepad#destroy
+     */
+    destroy: function () {
+
+        this.stop();
+
+        for (var i = 0; i < this._gamepads.length; i++)
+        {
+            this._gamepads[i].destroy();
+        }
+
+    }
+
+};
+
+Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
+
+/**
+* If the gamepad input is active or not - if not active it should not be updated from Input.js
+* @name Phaser.Gamepad#active
+* @property {boolean} active - If the gamepad input is active or not.
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "active", {
+
+    get: function () {
+        return this._active;
+    }
+
+});
+
+/**
+* Whether or not gamepads are supported in current browser.
+* @name Phaser.Gamepad#supported
+* @property {boolean} supported - Whether or not gamepads are supported in current browser.
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
+
+    get: function () {
+        return this._gamepadSupportAvailable;
+    }
+
+});
+
+/**
+* How many live gamepads are currently connected.
+* @name Phaser.Gamepad#padsConnected
+* @property {number} padsConnected - How many live gamepads are currently connected.
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
+
+    get: function () {
+        return this._rawPads.length;
+    }
+
+});
+
+/**
+* Gamepad #1
+* @name Phaser.Gamepad#pad1
+* @property {Phaser.SinglePad} pad1 - Gamepad #1;
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
+
+    get: function () {
+        return this._gamepads[0];
+    }
+
+});
+
+/**
+* Gamepad #2
+* @name Phaser.Gamepad#pad2
+* @property {Phaser.SinglePad} pad2 - Gamepad #2
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
+
+    get: function () {
+        return this._gamepads[1];
+    }
+
+});
+
+/**
+* Gamepad #3
+* @name Phaser.Gamepad#pad3
+* @property {Phaser.SinglePad} pad3 - Gamepad #3
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
+
+    get: function () {
+        return this._gamepads[2];
+    }
+
+});
+
+/**
+* Gamepad #4
+* @name Phaser.Gamepad#pad4
+* @property {Phaser.SinglePad} pad4 - Gamepad #4
+* @readonly
+*/
+Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
+
+    get: function () {
+        return this._gamepads[3];
+    }
+
+});
+
+Phaser.Gamepad.BUTTON_0 = 0;
+Phaser.Gamepad.BUTTON_1 = 1;
+Phaser.Gamepad.BUTTON_2 = 2;
+Phaser.Gamepad.BUTTON_3 = 3;
+Phaser.Gamepad.BUTTON_4 = 4;
+Phaser.Gamepad.BUTTON_5 = 5;
+Phaser.Gamepad.BUTTON_6 = 6;
+Phaser.Gamepad.BUTTON_7 = 7;
+Phaser.Gamepad.BUTTON_8 = 8;
+Phaser.Gamepad.BUTTON_9 = 9;
+Phaser.Gamepad.BUTTON_10 = 10;
+Phaser.Gamepad.BUTTON_11 = 11;
+Phaser.Gamepad.BUTTON_12 = 12;
+Phaser.Gamepad.BUTTON_13 = 13;
+Phaser.Gamepad.BUTTON_14 = 14;
+Phaser.Gamepad.BUTTON_15 = 15;
+
+Phaser.Gamepad.AXIS_0 = 0;
+Phaser.Gamepad.AXIS_1 = 1;
+Phaser.Gamepad.AXIS_2 = 2;
+Phaser.Gamepad.AXIS_3 = 3;
+Phaser.Gamepad.AXIS_4 = 4;
+Phaser.Gamepad.AXIS_5 = 5;
+Phaser.Gamepad.AXIS_6 = 6;
+Phaser.Gamepad.AXIS_7 = 7;
+Phaser.Gamepad.AXIS_8 = 8;
+Phaser.Gamepad.AXIS_9 = 9;
+
+// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
+// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
+// In other words - discrepancies when using gamepads.
+
+Phaser.Gamepad.XBOX360_A = 0;
+Phaser.Gamepad.XBOX360_B = 1;
+Phaser.Gamepad.XBOX360_X = 2;
+Phaser.Gamepad.XBOX360_Y = 3;
+Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
+Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
+Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
+Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
+Phaser.Gamepad.XBOX360_BACK = 8;
+Phaser.Gamepad.XBOX360_START = 9;
+Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
+Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
+
+Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
+Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
+Phaser.Gamepad.XBOX360_DPAD_UP = 12;
+Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
+
+//  On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right
+Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
+Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
+Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
+Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
+
+//  PlayStation 3 controller (masquerading as xbox360 controller) button mappings
+
+Phaser.Gamepad.PS3XC_X = 0;
+Phaser.Gamepad.PS3XC_CIRCLE = 1;
+Phaser.Gamepad.PS3XC_SQUARE = 2;
+Phaser.Gamepad.PS3XC_TRIANGLE = 3;
+Phaser.Gamepad.PS3XC_L1 = 4;
+Phaser.Gamepad.PS3XC_R1 = 5;
+Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1
+Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1
+Phaser.Gamepad.PS3XC_SELECT = 8;
+Phaser.Gamepad.PS3XC_START = 9;
+Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10;
+Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11;
+Phaser.Gamepad.PS3XC_DPAD_UP = 12;
+Phaser.Gamepad.PS3XC_DPAD_DOWN = 13;
+Phaser.Gamepad.PS3XC_DPAD_LEFT = 14;
+Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15;
+Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1
+Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1
+Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1
+Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1
+
+/**
+* @author       @karlmacklin <tacklemcclean@gmail.com>
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A single Phaser Gamepad
+* 
+* @class Phaser.SinglePad
+* @constructor
+* @param {Phaser.Game} game - Current game instance.
+* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
+*/
+Phaser.SinglePad = function (game, padParent) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {number} index - The gamepad index as per browsers data
+    * @readonly
+    */
+    this.index = null;
+
+    /**
+    * @property {boolean} connected - Whether or not this particular gamepad is connected or not.
+    * @readonly
+    */
+    this.connected = false;
+
+    /**
+    * @property {object} callbackContext - The context under which the callbacks are run.
+    */
+    this.callbackContext = this;
+
+    /**
+    * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
+    */
+    this.onConnectCallback = null;
+
+    /**
+    * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
+    */
+    this.onDisconnectCallback = null;
+
+    /**
+    * @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
+    */
+    this.onDownCallback = null;
+
+    /**
+    * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
+    */
+    this.onUpCallback = null;
+
+    /**
+    * @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
+    */
+    this.onAxisCallback = null;
+
+    /**
+    * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
+    */
+    this.onFloatCallback = null;
+
+    /**
+    * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
+    */
+    this.deadZone = 0.26;
+
+    /**
+    * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
+    * @private
+    */
+    this._padParent = padParent;
+
+    /**
+    * @property {object} _rawPad - The 'raw' gamepad data.
+    * @private
+    */
+    this._rawPad = null;
+
+    /**
+    * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
+    * @private
+    */
+    this._prevTimestamp = null;
+
+    /**
+    * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected.
+    * @private
+    */
+    this._buttons = [];
+
+    /**
+    * @property {number} _buttonsLen - Length of the _buttons array.
+    * @private
+    */
+    this._buttonsLen = 0;
+
+    /**
+    * @property {Array} _axes - Current axes state.
+    * @private
+    */
+    this._axes = [];
+
+    /**
+    * @property {number} _axesLen - Length of the _axes array.
+    * @private
+    */
+    this._axesLen = 0;
+
+};
+
+Phaser.SinglePad.prototype = {
+
+    /**
+    * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons.
+    * 
+    * @method Phaser.SinglePad#addCallbacks
+    * @param {object} context - The context under which the callbacks are run.
+    * @param {object} callbacks - Object that takes six different callbak methods:
+    * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
+    */
+    addCallbacks: function (context, callbacks) {
+
+        if (typeof callbacks !== 'undefined')
+        {
+            this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
+            this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
+            this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
+            this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
+            this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
+            this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
+        }
+
+    },
+
+    /**
+    * Gets a DeviceButton object from this controller to be stored and referenced locally.
+    * The DeviceButton object can then be polled, have events attached to it, etc.
+    *
+    * @method Phaser.SinglePad#getButton
+    * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc.
+    * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly.
+    */
+    getButton: function (buttonCode) {
+
+        if (this._buttons[buttonCode])
+        {
+            return this._buttons[buttonCode];
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Main update function called by Phaser.Gamepad.
+    * 
+    * @method Phaser.SinglePad#pollStatus
+    */
+    pollStatus: function () {
+
+        if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp)))
+        {
+            return;
+        }
+
+        for (var i = 0; i < this._buttonsLen; i++)
+        {
+            var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i];
+
+            if (rawButtonVal !== this._buttons[i].value)
+            {
+                if (rawButtonVal === 1)
+                {
+                    this.processButtonDown(i, rawButtonVal);
+                }
+                else if (rawButtonVal === 0)
+                {
+                    this.processButtonUp(i, rawButtonVal);
+                }
+                else
+                {
+                    this.processButtonFloat(i, rawButtonVal);
+                }
+            }
+        }
+        
+        for (var index = 0; index < this._axesLen; index++)
+        {
+            var value = this._rawPad.axes[index];
+
+            if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone))
+            {
+                this.processAxisChange(index, value);
+            }
+            else
+            {
+                this.processAxisChange(index, 0);
+            }
+        }
+
+        this._prevTimestamp = this._rawPad.timestamp;
+
+    },
+
+    /**
+    * Gamepad connect function, should be called by Phaser.Gamepad.
+    * 
+    * @method Phaser.SinglePad#connect
+    * @param {object} rawPad - The raw gamepad object
+    */
+    connect: function (rawPad) {
+
+        var triggerCallback = !this.connected;
+
+        this.connected = true;
+        this.index = rawPad.index;
+
+        this._rawPad = rawPad;
+
+        this._buttons = [];
+        this._buttonsLen = rawPad.buttons.length;
+
+        this._axes = [];
+        this._axesLen = rawPad.axes.length;
+
+        for (var a = 0; a < this._axesLen; a++)
+        {
+            this._axes[a] = rawPad.axes[a];
+        }
+
+        for (var buttonCode in rawPad.buttons)
+        {
+            buttonCode = parseInt(buttonCode, 10);
+            this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode);
+        }
+
+        if (triggerCallback && this._padParent.onConnectCallback)
+        {
+            this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index);
+        }
+
+        if (triggerCallback && this.onConnectCallback)
+        {
+            this.onConnectCallback.call(this.callbackContext);
+        }
+
+    },
+
+    /**
+    * Gamepad disconnect function, should be called by Phaser.Gamepad.
+    * 
+    * @method Phaser.SinglePad#disconnect
+    */
+    disconnect: function () {
+
+        var triggerCallback = this.connected;
+        var disconnectingIndex = this.index;
+
+        this.connected = false;
+        this.index = null;
+
+        this._rawPad = undefined;
+
+        for (var i = 0; i < this._buttonsLen; i++)
+        {
+            this._buttons[i].destroy();
+        }
+
+        this._buttons = [];
+        this._buttonsLen = 0;
+
+        this._axes = [];
+        this._axesLen = 0;
+
+        if (triggerCallback && this._padParent.onDisconnectCallback)
+        {
+            this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
+        }
+
+        if (triggerCallback && this.onDisconnectCallback)
+        {
+            this.onDisconnectCallback.call(this.callbackContext);
+        }
+
+    },
+
+    /**
+     * Destroys this object and associated callback references.
+     *
+     * @method Phaser.SinglePad#destroy
+     */
+    destroy: function () {
+
+        this._rawPad = undefined;
+
+        for (var i = 0; i < this._buttonsLen; i++)
+        {
+            this._buttons[i].destroy();
+        }
+
+        this._buttons = [];
+        this._buttonsLen = 0;
+
+        this._axes = [];
+        this._axesLen = 0;
+
+        this.onConnectCallback = null;
+        this.onDisconnectCallback = null;
+        this.onDownCallback = null;
+        this.onUpCallback = null;
+        this.onAxisCallback = null;
+        this.onFloatCallback = null;
+
+    },
+
+    /**
+    * Handles changes in axis.
+    * 
+    * @method Phaser.SinglePad#processAxisChange
+    * @param {object} axisState - State of the relevant axis
+    */
+    processAxisChange: function (index, value) {
+
+        if (this._axes[index] === value)
+        {
+            return;
+        }
+
+        this._axes[index] = value;
+
+        if (this._padParent.onAxisCallback)
+        {
+            this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value);
+        }
+
+        if (this.onAxisCallback)
+        {
+            this.onAxisCallback.call(this.callbackContext, this, index, value);
+        }
+
+    },
+
+    /**
+    * Handles button down press.
+    * 
+    * @method Phaser.SinglePad#processButtonDown
+    * @param {number} buttonCode - Which buttonCode of this button
+    * @param {object} value - Button value
+    */
+    processButtonDown: function (buttonCode, value) {
+
+        if (this._padParent.onDownCallback)
+        {
+            this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
+        }
+
+        if (this.onDownCallback)
+        {
+            this.onDownCallback.call(this.callbackContext, buttonCode, value);
+        }
+
+        if (this._buttons[buttonCode])
+        {
+            this._buttons[buttonCode].start(null, value);
+        }
+
+    },
+
+    /**
+    * Handles button release.
+    * 
+    * @method Phaser.SinglePad#processButtonUp
+    * @param {number} buttonCode - Which buttonCode of this button
+    * @param {object} value - Button value
+    */
+    processButtonUp: function (buttonCode, value) {
+
+        if (this._padParent.onUpCallback)
+        {
+            this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
+        }
+
+        if (this.onUpCallback)
+        {
+            this.onUpCallback.call(this.callbackContext, buttonCode, value);
+        }
+
+        if (this._buttons[buttonCode])
+        {
+            this._buttons[buttonCode].stop(null, value);
+        }
+
+    },
+
+    /**
+    * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
+    * 
+    * @method Phaser.SinglePad#processButtonFloat
+    * @param {number} buttonCode - Which buttonCode of this button
+    * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
+    */
+    processButtonFloat: function (buttonCode, value) {
+
+        if (this._padParent.onFloatCallback)
+        {
+            this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
+        }
+
+        if (this.onFloatCallback)
+        {
+            this.onFloatCallback.call(this.callbackContext, buttonCode, value);
+        }
+
+        if (this._buttons[buttonCode])
+        {
+            this._buttons[buttonCode].padFloat(value);
+        }
+
+    },
+
+    /**
+    * Returns value of requested axis.
+    * 
+    * @method Phaser.SinglePad#axis
+    * @param {number} axisCode - The index of the axis to check
+    * @return {number} Axis value if available otherwise false
+    */
+    axis: function (axisCode) {
+
+        if (this._axes[axisCode])
+        {
+            return this._axes[axisCode];
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Returns true if the button is pressed down.
+    * 
+    * @method Phaser.SinglePad#isDown
+    * @param {number} buttonCode - The buttonCode of the button to check.
+    * @return {boolean} True if the button is pressed down.
+    */
+    isDown: function (buttonCode) {
+
+        if (this._buttons[buttonCode])
+        {
+            return this._buttons[buttonCode].isDown;
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Returns true if the button is not currently pressed.
+    * 
+    * @method Phaser.SinglePad#isUp
+    * @param {number} buttonCode - The buttonCode of the button to check.
+    * @return {boolean} True if the button is not currently pressed down.
+    */
+    isUp: function (buttonCode) {
+
+        if (this._buttons[buttonCode])
+        {
+            return this._buttons[buttonCode].isUp;
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms).
+    * 
+    * @method Phaser.SinglePad#justReleased
+    * @param {number} buttonCode - The buttonCode of the button to check for.
+    * @param {number} [duration=250] - The duration below which the button is considered as being just released.
+    * @return {boolean} True if the button is just released otherwise false.
+    */
+    justReleased: function (buttonCode, duration) {
+
+        if (this._buttons[buttonCode])
+        {
+            return this._buttons[buttonCode].justReleased(duration);
+        }
+
+    },
+
+    /**
+    * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
+    * 
+    * @method Phaser.SinglePad#justPressed
+    * @param {number} buttonCode - The buttonCode of the button to check for.
+    * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
+    * @return {boolean} True if the button is just pressed otherwise false.
+    */
+    justPressed: function (buttonCode, duration) {
+
+        if (this._buttons[buttonCode])
+        {
+            return this._buttons[buttonCode].justPressed(duration);
+        }
+
+    },
+
+    /**
+    * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
+    * analog trigger buttons on the XBOX 360 controller.
+    * 
+    * @method Phaser.SinglePad#buttonValue
+    * @param {number} buttonCode - The buttonCode of the button to check.
+    * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0.
+    */
+    buttonValue: function (buttonCode) {
+
+        if (this._buttons[buttonCode])
+        {
+            return this._buttons[buttonCode].value;
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Reset all buttons/axes of this gamepad.
+    * 
+    * @method Phaser.SinglePad#reset
+    */
+    reset: function () {
+
+        for (var j = 0; j < this._axes.length; j++)
+        {
+            this._axes[j] = 0;
+        }
+
+    }
+
+};
+
+Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
+* 
+* @class Phaser.Key
+* @constructor
+* @param {Phaser.Game} game - Current game instance.
+* @param {number} keycode - The key code this Key is responsible for.
+*/
+Phaser.Key = function (game, keycode) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * The enabled state of the key - see `enabled`.
+    * @property {boolean} _enabled
+    * @private
+    */
+    this._enabled = true;
+
+    /**
+    * @property {object} event - Stores the most recent DOM event.
+    * @readonly
+    */
+    this.event = null;
+
+    /**
+    * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down.
+    * @default
+    */
+    this.isDown = false;
+
+    /**
+    * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up.
+    * @default
+    */
+    this.isUp = true;
+
+    /**
+    * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
+    * @default
+    */
+    this.altKey = false;
+
+    /**
+    * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
+    * @default
+    */
+    this.ctrlKey = false;
+
+    /**
+    * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
+    * @default
+    */
+    this.shiftKey = false;
+
+    /**
+    * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
+    */
+    this.timeDown = 0;
+
+    /**
+    * If the key is down this value holds the duration of that key press and is constantly updated.
+    * If the key is up it holds the duration of the previous down session.
+    * @property {number} duration - The number of milliseconds this key has been held down for.
+    * @default
+    */
+    this.duration = 0;
+
+    /**
+    * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
+    * @default
+    */
+    this.timeUp = -2500;
+
+    /**
+    * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
+    * @default
+    */
+    this.repeats = 0;
+
+    /**
+    * @property {number} keyCode - The keycode of this key.
+    */
+    this.keyCode = keycode;
+
+    /**
+    * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
+    */
+    this.onDown = new Phaser.Signal();
+
+    /**
+    * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
+    */
+    this.onHoldCallback = null;
+
+    /**
+    * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
+    */
+    this.onHoldContext = null;
+
+    /**
+    * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
+    */
+    this.onUp = new Phaser.Signal();
+
+    /**
+     * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
+     * @private
+     */
+    this._justDown = false;
+
+    /**
+     * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
+     * @private
+     */
+    this._justUp = false;
+
+};
+
+Phaser.Key.prototype = {
+
+    /**
+    * Called automatically by Phaser.Keyboard.
+    * 
+    * @method Phaser.Key#update
+    * @protected
+    */
+    update: function () {
+
+        if (!this._enabled) { return; }
+
+        if (this.isDown)
+        {
+            this.duration = this.game.time.time - this.timeDown;
+            this.repeats++;
+
+            if (this.onHoldCallback)
+            {
+                this.onHoldCallback.call(this.onHoldContext, this);
+            }
+        }
+
+    },
+
+    /**
+    * Called automatically by Phaser.Keyboard.
+    * 
+    * @method Phaser.Key#processKeyDown
+    * @param {KeyboardEvent} event - The DOM event that triggered this.
+    * @protected
+    */
+    processKeyDown: function (event) {
+
+        if (!this._enabled) { return; }
+
+        this.event = event;
+
+        // exit if this key down is from auto-repeat
+        if (this.isDown)
+        {
+            return;
+        }
+
+        this.altKey = event.altKey;
+        this.ctrlKey = event.ctrlKey;
+        this.shiftKey = event.shiftKey;
+
+        this.isDown = true;
+        this.isUp = false;
+        this.timeDown = this.game.time.time;
+        this.duration = 0;
+        this.repeats = 0;
+
+        // _justDown will remain true until it is read via the justDown Getter
+        // this enables the game to poll for past presses, or reset it at the start of a new game state
+        this._justDown = true;
+
+        this.onDown.dispatch(this);
+
+    },
+
+    /**
+    * Called automatically by Phaser.Keyboard.
+    * 
+    * @method Phaser.Key#processKeyUp
+    * @param {KeyboardEvent} event - The DOM event that triggered this.
+    * @protected
+    */
+    processKeyUp: function (event) {
+
+        if (!this._enabled) { return; }
+
+        this.event = event;
+
+        if (this.isUp)
+        {
+            return;
+        }
+
+        this.isDown = false;
+        this.isUp = true;
+        this.timeUp = this.game.time.time;
+        this.duration = this.game.time.time - this.timeDown;
+
+        // _justUp will remain true until it is read via the justUp Getter
+        // this enables the game to poll for past presses, or reset it at the start of a new game state
+        this._justUp = true;
+
+        this.onUp.dispatch(this);
+
+    },
+
+    /**
+    * Resets the state of this Key.
+    *
+    * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key.
+    * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback.
+    *
+    * @method Phaser.Key#reset
+    * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will.
+    */
+    reset: function (hard) {
+
+        if (hard === undefined) { hard = true; }
+
+        this.isDown = false;
+        this.isUp = true;
+        this.timeUp = this.game.time.time;
+        this.duration = 0;
+        this._enabled = true; // .enabled causes reset(false)
+        this._justDown = false;
+        this._justUp = false;
+
+        if (hard)
+        {
+            this.onDown.removeAll();
+            this.onUp.removeAll();
+            this.onHoldCallback = null;
+            this.onHoldContext = null;
+        }
+
+    },
+
+    /**
+    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
+    * or was pressed down longer ago than then given duration.
+    * 
+    * @method Phaser.Key#downDuration
+    * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
+    * @return {boolean} True if the key was pressed down within the given duration.
+    */
+    downDuration: function (duration) {
+
+        if (duration === undefined) { duration = 50; }
+
+        return (this.isDown && this.duration < duration);
+
+    },
+
+    /**
+    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
+    * or was pressed down longer ago than then given duration.
+    * 
+    * @method Phaser.Key#upDuration
+    * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
+    * @return {boolean} True if the key was released within the given duration.
+    */
+    upDuration: function (duration) {
+
+        if (duration === undefined) { duration = 50; }
+
+        return (!this.isDown && ((this.game.time.time - this.timeUp) < duration));
+
+    }
+
+};
+
+/**
+* The justDown value allows you to test if this Key has just been pressed down or not.
+* When you check this value it will return `true` if the Key is down, otherwise `false`.
+* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again.
+* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop.
+* 
+* @property {boolean} justDown
+* @memberof Phaser.Key
+* @default false
+*/
+Object.defineProperty(Phaser.Key.prototype, "justDown", {
+
+    get: function () {
+
+        var current = this._justDown;
+        this._justDown = false;
+        return current;
+
+    }
+
+});
+
+/**
+* The justUp value allows you to test if this Key has just been released or not.
+* When you check this value it will return `true` if the Key is up, otherwise `false`.
+* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again.
+* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop.
+* 
+* @property {boolean} justUp
+* @memberof Phaser.Key
+* @default false
+*/
+Object.defineProperty(Phaser.Key.prototype, "justUp", {
+
+    get: function () {
+
+        var current = this._justUp;
+        this._justUp = false;
+        return current;
+
+    }
+
+});
+
+/**
+* An enabled key processes its update and dispatches events.
+* A key can be disabled momentarily at runtime instead of deleting it.
+* 
+* @property {boolean} enabled
+* @memberof Phaser.Key
+* @default true
+*/
+Object.defineProperty(Phaser.Key.prototype, "enabled", {
+
+    get: function () {
+
+        return this._enabled;
+
+    },
+
+    set: function (value) {
+
+        value = !!value;
+
+        if (value !== this._enabled)
+        {
+            if (!value)
+            {
+                this.reset(false);
+            }
+
+            this._enabled = value;
+        }
+    }
+
+});
+
+Phaser.Key.prototype.constructor = Phaser.Key;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Keyboard class monitors keyboard input and dispatches keyboard events.
+*
+* _Be aware_ that many keyboards are unable to process certain combinations of keys due to hardware
+* limitations known as ghosting. Full details here: http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/
+*
+* @class Phaser.Keyboard
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Keyboard = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * Keyboard input will only be processed if enabled.
+    * @property {boolean} enabled
+    * @default
+    */
+    this.enabled = true;
+
+    /**
+    * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released.
+    */
+    this.event = null;
+
+    /**
+    * @property {object} pressEvent - The most recent DOM event from keypress.
+    */
+    this.pressEvent = null;
+
+    /**
+    * @property {object} callbackContext - The context under which the callbacks are run.
+    */
+    this.callbackContext = this;
+
+    /**
+    * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down.
+    */
+    this.onDownCallback = null;
+
+    /**
+    * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys.
+    */
+    this.onPressCallback = null;
+
+    /**
+    * @property {function} onUpCallback - This callback is invoked every time a key is released.
+    */
+    this.onUpCallback = null;
+
+    /**
+    * @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
+    * @private
+    */
+    this._keys = [];
+
+    /**
+    * @property {array} _capture - The array the key capture values are stored in.
+    * @private
+    */
+    this._capture = [];
+
+    /**
+    * @property {function} _onKeyDown
+    * @private
+    * @default
+    */
+    this._onKeyDown = null;
+
+    /**
+    * @property {function} _onKeyPress
+    * @private
+    * @default
+    */
+    this._onKeyPress = null;
+
+    /**
+    * @property {function} _onKeyUp
+    * @private
+    * @default
+    */
+    this._onKeyUp = null;
+
+    /**
+    * @property {number} _i - Internal cache var
+    * @private
+    */
+    this._i = 0;
+
+    /**
+    * @property {number} _k - Internal cache var
+    * @private
+    */
+    this._k = 0;
+
+};
+
+Phaser.Keyboard.prototype = {
+
+    /**
+    * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
+    *
+    * @method Phaser.Keyboard#addCallbacks
+    * @param {object} context - The context under which the callbacks are run.
+    * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down.
+    * @param {function} [onUp=null] - This callback is invoked every time a key is released.
+    * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised.
+    */
+    addCallbacks: function (context, onDown, onUp, onPress) {
+
+        this.callbackContext = context;
+
+        if (typeof onDown !== 'undefined')
+        {
+            this.onDownCallback = onDown;
+        }
+
+        if (typeof onUp !== 'undefined')
+        {
+            this.onUpCallback = onUp;
+        }
+
+        if (typeof onPress !== 'undefined')
+        {
+            this.onPressCallback = onPress;
+        }
+
+    },
+
+    /**
+    * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
+    * The Key object can then be polled, have events attached to it, etc.
+    *
+    * @method Phaser.Keyboard#addKey
+    * @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
+    * @return {Phaser.Key} The Key object which you can store locally and reference directly.
+    */
+    addKey: function (keycode) {
+
+        if (!this._keys[keycode])
+        {
+            this._keys[keycode] = new Phaser.Key(this.game, keycode);
+
+            this.addKeyCapture(keycode);
+        }
+
+        return this._keys[keycode];
+
+    },
+
+    /**
+    * A practical way to create an object containing user selected hotkeys.
+    *
+    * For example: `addKeys( { 'up': Phaser.Keyboard.W, 'down': Phaser.Keyboard.S, 'left': Phaser.Keyboard.A, 'right': Phaser.Keyboard.D } );`
+    *
+    * Would return an object containing the properties `up`, `down`, `left` and `right` that you could poll just like a Phaser.Key object.
+    *
+    * @method Phaser.Keyboard#addKeys
+    * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.Keyboard.W, 'down': Phaser.Keyboard.S }` or `{ 'up': 52, 'down': 53 }`.
+    * @return {object} An object containing user selected properties
+    */
+    addKeys: function (keys) {
+
+        var output = {};
+
+        for (var key in keys)
+        {
+            output[key] = this.addKey(keys[key]);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Removes a Key object from the Keyboard manager.
+    *
+    * @method Phaser.Keyboard#removeKey
+    * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
+    */
+    removeKey: function (keycode) {
+
+        if (this._keys[keycode])
+        {
+            this._keys[keycode] = null;
+
+            this.removeKeyCapture(keycode);
+        }
+
+    },
+
+    /**
+    * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
+    *
+    * @method Phaser.Keyboard#createCursorKeys
+    * @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object.
+    */
+    createCursorKeys: function () {
+
+        return this.addKeys({ 'up': Phaser.Keyboard.UP, 'down': Phaser.Keyboard.DOWN, 'left': Phaser.Keyboard.LEFT, 'right': Phaser.Keyboard.RIGHT });
+
+    },
+
+    /**
+    * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
+    * This is called automatically by Phaser.Input and should not normally be invoked directly.
+    *
+    * @method Phaser.Keyboard#start
+    */
+    start: function () {
+
+        if (this.game.device.cocoonJS)
+        {
+            return;
+        }
+
+        if (this._onKeyDown !== null)
+        {
+            //  Avoid setting multiple listeners
+            return;
+        }
+
+        var _this = this;
+
+        this._onKeyDown = function (event) {
+            return _this.processKeyDown(event);
+        };
+
+        this._onKeyUp = function (event) {
+            return _this.processKeyUp(event);
+        };
+
+        this._onKeyPress = function (event) {
+            return _this.processKeyPress(event);
+        };
+
+        window.addEventListener('keydown', this._onKeyDown, false);
+        window.addEventListener('keyup', this._onKeyUp, false);
+        window.addEventListener('keypress', this._onKeyPress, false);
+
+    },
+
+    /**
+    * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window.
+    *
+    * @method Phaser.Keyboard#stop
+    */
+    stop: function () {
+
+        window.removeEventListener('keydown', this._onKeyDown);
+        window.removeEventListener('keyup', this._onKeyUp);
+        window.removeEventListener('keypress', this._onKeyPress);
+
+        this._onKeyDown = null;
+        this._onKeyUp = null;
+        this._onKeyPress = null;
+
+    },
+
+    /**
+    * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
+    * Also clears all key captures and currently created Key objects.
+    *
+    * @method Phaser.Keyboard#destroy
+    */
+    destroy: function () {
+
+        this.stop();
+
+        this.clearCaptures();
+
+        this._keys.length = 0;
+        this._i = 0;
+
+    },
+
+    /**
+    * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
+    * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
+    * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser.
+    * Pass in either a single keycode or an array/hash of keycodes.
+    *
+    * @method Phaser.Keyboard#addKeyCapture
+    * @param {number|array|object} keycode - Either a single numeric keycode or an array/hash of keycodes: [65, 67, 68].
+    */
+    addKeyCapture: function (keycode) {
+
+        if (typeof keycode === 'object')
+        {
+            for (var key in keycode)
+            {
+                this._capture[keycode[key]] = true;
+            }
+        }
+        else
+        {
+            this._capture[keycode] = true;
+        }
+    },
+
+    /**
+    * Removes an existing key capture.
+    *
+    * @method Phaser.Keyboard#removeKeyCapture
+    * @param {number} keycode
+    */
+    removeKeyCapture: function (keycode) {
+
+        delete this._capture[keycode];
+
+    },
+
+    /**
+    * Clear all set key captures.
+    *
+    * @method Phaser.Keyboard#clearCaptures
+    */
+    clearCaptures: function () {
+
+        this._capture = {};
+
+    },
+
+    /**
+    * Updates all currently defined keys.
+    *
+    * @method Phaser.Keyboard#update
+    */
+    update: function () {
+
+        this._i = this._keys.length;
+
+        while (this._i--)
+        {
+            if (this._keys[this._i])
+            {
+                this._keys[this._i].update();
+            }
+        }
+
+    },
+
+    /**
+    * Process the keydown event.
+    *
+    * @method Phaser.Keyboard#processKeyDown
+    * @param {KeyboardEvent} event
+    * @protected
+    */
+    processKeyDown: function (event) {
+
+        this.event = event;
+
+        if (!this.game.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        //   The event is being captured but another hotkey may need it
+        if (this._capture[event.keyCode])
+        {
+            event.preventDefault();
+        }
+
+        if (!this._keys[event.keyCode])
+        {
+            this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
+        }
+
+        this._keys[event.keyCode].processKeyDown(event);
+
+        this._k = event.keyCode;
+
+        if (this.onDownCallback)
+        {
+            this.onDownCallback.call(this.callbackContext, event);
+        }
+
+    },
+
+    /**
+    * Process the keypress event.
+    *
+    * @method Phaser.Keyboard#processKeyPress
+    * @param {KeyboardEvent} event
+    * @protected
+    */
+    processKeyPress: function (event) {
+
+        this.pressEvent = event;
+
+        if (!this.game.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        if (this.onPressCallback)
+        {
+            this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event);
+        }
+
+    },
+
+    /**
+    * Process the keyup event.
+    *
+    * @method Phaser.Keyboard#processKeyUp
+    * @param {KeyboardEvent} event
+    * @protected
+    */
+    processKeyUp: function (event) {
+
+        this.event = event;
+
+        if (!this.game.input.enabled || !this.enabled)
+        {
+            return;
+        }
+
+        if (this._capture[event.keyCode])
+        {
+            event.preventDefault();
+        }
+
+        if (!this._keys[event.keyCode])
+        {
+            this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
+        }
+
+        this._keys[event.keyCode].processKeyUp(event);
+
+        if (this.onUpCallback)
+        {
+            this.onUpCallback.call(this.callbackContext, event);
+        }
+
+    },
+
+    /**
+    * Resets all Keys.
+    *
+    * @method Phaser.Keyboard#reset
+    * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
+    */
+    reset: function (hard) {
+
+        if (hard === undefined) { hard = true; }
+
+        this.event = null;
+
+        var i = this._keys.length;
+
+        while (i--)
+        {
+            if (this._keys[i])
+            {
+                this._keys[i].reset(hard);
+            }
+        }
+
+    },
+
+    /**
+    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
+    * or was pressed down longer ago than then given duration.
+    * 
+    * @method Phaser.Keyboard#downDuration
+    * @param {number} keycode - The keycode of the key to check, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
+    * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
+    * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found.
+    */
+    downDuration: function (keycode, duration) {
+
+        if (this._keys[keycode])
+        {
+            return this._keys[keycode].downDuration(duration);
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
+    * or was pressed down longer ago than then given duration.
+    * 
+    * @method Phaser.Keyboard#upDuration
+    * @param {number} keycode - The keycode of the key to check, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
+    * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
+    * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found.
+    */
+    upDuration: function (keycode, duration) {
+
+        if (this._keys[keycode])
+        {
+            return this._keys[keycode].upDuration(duration);
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
+    *
+    * @method Phaser.Keyboard#isDown
+    * @param {number} keycode - The keycode of the key to check, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
+    * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found.
+    */
+    isDown: function (keycode) {
+
+        if (this._keys[keycode])
+        {
+            return this._keys[keycode].isDown;
+        }
+        else
+        {
+            return null;
+        }
+
+    }
+
+};
+
+/**
+* Returns the string value of the most recently pressed key.
+* @name Phaser.Keyboard#lastChar
+* @property {string} lastChar - The string value of the most recently pressed key.
+* @readonly
+*/
+Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", {
+
+    get: function () {
+
+        if (this.event.charCode === 32)
+        {
+            return '';
+        }
+        else
+        {
+            return String.fromCharCode(this.pressEvent.charCode);
+        }
+
+    }
+
+});
+
+/**
+* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed.
+* @name Phaser.Keyboard#lastKey
+* @property {Phaser.Key} lastKey - The most recently pressed Key.
+* @readonly
+*/
+Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", {
+
+    get: function () {
+
+        return this._keys[this._k];
+
+    }
+
+});
+
+Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
+
+Phaser.Keyboard.A = "A".charCodeAt(0);
+Phaser.Keyboard.B = "B".charCodeAt(0);
+Phaser.Keyboard.C = "C".charCodeAt(0);
+Phaser.Keyboard.D = "D".charCodeAt(0);
+Phaser.Keyboard.E = "E".charCodeAt(0);
+Phaser.Keyboard.F = "F".charCodeAt(0);
+Phaser.Keyboard.G = "G".charCodeAt(0);
+Phaser.Keyboard.H = "H".charCodeAt(0);
+Phaser.Keyboard.I = "I".charCodeAt(0);
+Phaser.Keyboard.J = "J".charCodeAt(0);
+Phaser.Keyboard.K = "K".charCodeAt(0);
+Phaser.Keyboard.L = "L".charCodeAt(0);
+Phaser.Keyboard.M = "M".charCodeAt(0);
+Phaser.Keyboard.N = "N".charCodeAt(0);
+Phaser.Keyboard.O = "O".charCodeAt(0);
+Phaser.Keyboard.P = "P".charCodeAt(0);
+Phaser.Keyboard.Q = "Q".charCodeAt(0);
+Phaser.Keyboard.R = "R".charCodeAt(0);
+Phaser.Keyboard.S = "S".charCodeAt(0);
+Phaser.Keyboard.T = "T".charCodeAt(0);
+Phaser.Keyboard.U = "U".charCodeAt(0);
+Phaser.Keyboard.V = "V".charCodeAt(0);
+Phaser.Keyboard.W = "W".charCodeAt(0);
+Phaser.Keyboard.X = "X".charCodeAt(0);
+Phaser.Keyboard.Y = "Y".charCodeAt(0);
+Phaser.Keyboard.Z = "Z".charCodeAt(0);
+Phaser.Keyboard.ZERO = "0".charCodeAt(0);
+Phaser.Keyboard.ONE = "1".charCodeAt(0);
+Phaser.Keyboard.TWO = "2".charCodeAt(0);
+Phaser.Keyboard.THREE = "3".charCodeAt(0);
+Phaser.Keyboard.FOUR = "4".charCodeAt(0);
+Phaser.Keyboard.FIVE = "5".charCodeAt(0);
+Phaser.Keyboard.SIX = "6".charCodeAt(0);
+Phaser.Keyboard.SEVEN = "7".charCodeAt(0);
+Phaser.Keyboard.EIGHT = "8".charCodeAt(0);
+Phaser.Keyboard.NINE = "9".charCodeAt(0);
+Phaser.Keyboard.NUMPAD_0 = 96;
+Phaser.Keyboard.NUMPAD_1 = 97;
+Phaser.Keyboard.NUMPAD_2 = 98;
+Phaser.Keyboard.NUMPAD_3 = 99;
+Phaser.Keyboard.NUMPAD_4 = 100;
+Phaser.Keyboard.NUMPAD_5 = 101;
+Phaser.Keyboard.NUMPAD_6 = 102;
+Phaser.Keyboard.NUMPAD_7 = 103;
+Phaser.Keyboard.NUMPAD_8 = 104;
+Phaser.Keyboard.NUMPAD_9 = 105;
+Phaser.Keyboard.NUMPAD_MULTIPLY = 106;
+Phaser.Keyboard.NUMPAD_ADD = 107;
+Phaser.Keyboard.NUMPAD_ENTER = 108;
+Phaser.Keyboard.NUMPAD_SUBTRACT = 109;
+Phaser.Keyboard.NUMPAD_DECIMAL = 110;
+Phaser.Keyboard.NUMPAD_DIVIDE = 111;
+Phaser.Keyboard.F1 = 112;
+Phaser.Keyboard.F2 = 113;
+Phaser.Keyboard.F3 = 114;
+Phaser.Keyboard.F4 = 115;
+Phaser.Keyboard.F5 = 116;
+Phaser.Keyboard.F6 = 117;
+Phaser.Keyboard.F7 = 118;
+Phaser.Keyboard.F8 = 119;
+Phaser.Keyboard.F9 = 120;
+Phaser.Keyboard.F10 = 121;
+Phaser.Keyboard.F11 = 122;
+Phaser.Keyboard.F12 = 123;
+Phaser.Keyboard.F13 = 124;
+Phaser.Keyboard.F14 = 125;
+Phaser.Keyboard.F15 = 126;
+Phaser.Keyboard.COLON = 186;
+Phaser.Keyboard.EQUALS = 187;
+Phaser.Keyboard.COMMA = 188;
+Phaser.Keyboard.UNDERSCORE = 189;
+Phaser.Keyboard.PERIOD = 190;
+Phaser.Keyboard.QUESTION_MARK = 191;
+Phaser.Keyboard.TILDE = 192;
+Phaser.Keyboard.OPEN_BRACKET = 219;
+Phaser.Keyboard.BACKWARD_SLASH = 220;
+Phaser.Keyboard.CLOSED_BRACKET = 221;
+Phaser.Keyboard.QUOTES = 222;
+Phaser.Keyboard.BACKSPACE = 8;
+Phaser.Keyboard.TAB = 9;
+Phaser.Keyboard.CLEAR = 12;
+Phaser.Keyboard.ENTER = 13;
+Phaser.Keyboard.SHIFT = 16;
+Phaser.Keyboard.CONTROL = 17;
+Phaser.Keyboard.ALT = 18;
+Phaser.Keyboard.CAPS_LOCK = 20;
+Phaser.Keyboard.ESC = 27;
+Phaser.Keyboard.SPACEBAR = 32;
+Phaser.Keyboard.PAGE_UP = 33;
+Phaser.Keyboard.PAGE_DOWN = 34;
+Phaser.Keyboard.END = 35;
+Phaser.Keyboard.HOME = 36;
+Phaser.Keyboard.LEFT = 37;
+Phaser.Keyboard.UP = 38;
+Phaser.Keyboard.RIGHT = 39;
+Phaser.Keyboard.DOWN = 40;
+Phaser.Keyboard.PLUS = 43;
+Phaser.Keyboard.MINUS = 44;
+Phaser.Keyboard.INSERT = 45;
+Phaser.Keyboard.DELETE = 46;
+Phaser.Keyboard.HELP = 47;
+Phaser.Keyboard.NUM_LOCK = 144;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+Phaser.Component = function () {};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees.
+*
+* @class
+*/
+Phaser.Component.Angle = function () {};
+
+Phaser.Component.Angle.prototype = {
+
+    /**
+    * The angle property is the rotation of the Game Object in *degrees* from its original orientation.
+    * 
+    * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
+    * 
+    * Values outside this range are added to or subtracted from 360 to obtain a value within the range. 
+    * For example, the statement player.angle = 450 is the same as player.angle = 90.
+    * 
+    * If you wish to work in radians instead of degrees you can use the property `rotation` instead. 
+    * Working in radians is slightly faster as it doesn't have to perform any calculations.
+    *
+    * @property {number} angle
+    */
+    angle: {
+
+        get: function() {
+
+            return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
+
+        },
+
+        set: function(value) {
+
+            this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method.
+*
+* @class
+*/
+Phaser.Component.Animation = function () {};
+
+Phaser.Component.Animation.prototype = {
+
+    /**
+    * Plays an Animation.
+    * 
+    * The animation should have previously been created via `animations.add`.
+    * 
+    * If the animation is already playing calling this again won't do anything.
+    * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`.
+    *
+    * @method
+    * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'.
+    * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
+    * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
+    * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
+    * @return {Phaser.Animation} A reference to playing Animation.
+    */
+    play: function (name, frameRate, loop, killOnComplete) {
+
+        if (this.animations)
+        {
+            return this.animations.play(name, frameRate, loop, killOnComplete);
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera.
+* It is used by the InWorld component.
+*
+* @class
+*/
+Phaser.Component.AutoCull = function () {};
+
+Phaser.Component.AutoCull.prototype = {
+
+    /**
+    * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame.
+    * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`.
+    * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely.
+    * 
+    * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required,
+    * or you have tested performance and find it acceptable.
+    *
+    * @property {boolean} autoCull
+    * @default
+    */
+    autoCull: false,
+
+    /**
+    * Checks if the Game Objects bounds intersect with the Game Camera bounds.
+    * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds.
+    *
+    * @property {boolean} inCamera
+    * @readonly
+    */
+    inCamera: {
+
+        get: function() {
+
+            if (!this.autoCull && !this.checkWorldBounds)
+            {
+                this._bounds.copyFrom(this.getBounds());
+                this._bounds.x += this.game.camera.view.x;
+                this._bounds.y += this.game.camera.view.y;
+            }
+
+            return this.game.world.camera.view.intersects(this._bounds);
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Bounds component contains properties related to the bounds of the Game Object.
+*
+* @class
+*/
+Phaser.Component.Bounds = function () {};
+
+Phaser.Component.Bounds.prototype = {
+
+    /**
+    * The amount the Game Object is visually offset from its x coordinate.
+    * This is the same as `width * anchor.x`.
+    * It will only be > 0 if anchor.x is not equal to zero.
+    *
+    * @property {number} offsetX
+    * @readOnly
+    */
+    offsetX: {
+
+        get: function () {
+
+            return this.anchor.x * this.width;
+
+        }
+
+    },
+
+    /**
+    * The amount the Game Object is visually offset from its y coordinate.
+    * This is the same as `height * anchor.y`.
+    * It will only be > 0 if anchor.y is not equal to zero.
+    *
+    * @property {number} offsetY
+    * @readOnly
+    */
+    offsetY: {
+
+        get: function () {
+
+            return this.anchor.y * this.height;
+
+        }
+
+    },
+
+    /**
+    * The left coordinate of the Game Object.
+    * This is the same as `x - offsetX`.
+    *
+    * @property {number} left
+    * @readOnly
+    */
+    left: {
+
+        get: function () {
+
+            return this.x - this.offsetX;
+
+        }
+
+    },
+
+    /**
+    * The right coordinate of the Game Object.
+    * This is the same as `x + width - offsetX`.
+    *
+    * @property {number} right
+    * @readOnly
+    */
+    right: {
+
+        get: function () {
+
+            return (this.x + this.width) - this.offsetX;
+
+        }
+
+    },
+
+    /**
+    * The y coordinate of the Game Object.
+    * This is the same as `y - offsetY`.
+    *
+    * @property {number} top
+    * @readOnly
+    */
+    top: {
+
+        get: function () {
+
+            return this.y - this.offsetY;
+
+        }
+
+    },
+
+    /**
+    * The sum of the y and height properties.
+    * This is the same as `y + height - offsetY`.
+    *
+    * @property {number} bottom
+    * @readOnly
+    */
+    bottom: {
+
+        get: function () {
+
+            return (this.y + this.height) - this.offsetY;
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The BringToTop Component features quick access to Group sorting related methods.
+*
+* @class
+*/
+Phaser.Component.BringToTop = function () {};
+
+/**
+* Brings this Game Object to the top of its parents display list.
+* Visually this means it will render over the top of any old child in the same Group.
+* 
+* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, 
+* because the World is the root Group from which all Game Objects descend.
+*
+* @method
+* @return {PIXI.DisplayObject} This instance.
+*/
+Phaser.Component.BringToTop.prototype.bringToTop = function() {
+
+    if (this.parent)
+    {
+        this.parent.bringToTop(this);
+    }
+
+    return this;
+
+};
+
+/**
+* Sends this Game Object to the bottom of its parents display list.
+* Visually this means it will render below all other children in the same Group.
+* 
+* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, 
+* because the World is the root Group from which all Game Objects descend.
+*
+* @method
+* @return {PIXI.DisplayObject} This instance.
+*/
+Phaser.Component.BringToTop.prototype.sendToBack = function() {
+
+    if (this.parent)
+    {
+        this.parent.sendToBack(this);
+    }
+
+    return this;
+
+};
+
+/**
+* Moves this Game Object up one place in its parents display list.
+* This call has no effect if the Game Object is already at the top of the display list.
+* 
+* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, 
+* because the World is the root Group from which all Game Objects descend.
+*
+* @method
+* @return {PIXI.DisplayObject} This instance.
+*/
+Phaser.Component.BringToTop.prototype.moveUp = function () {
+
+    if (this.parent)
+    {
+        this.parent.moveUp(this);
+    }
+
+    return this;
+
+};
+
+/**
+* Moves this Game Object down one place in its parents display list.
+* This call has no effect if the Game Object is already at the bottom of the display list.
+* 
+* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, 
+* because the World is the root Group from which all Game Objects descend.
+*
+* @method
+* @return {PIXI.DisplayObject} This instance.
+*/
+Phaser.Component.BringToTop.prototype.moveDown = function () {
+
+    if (this.parent)
+    {
+        this.parent.moveDown(this);
+    }
+
+    return this;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Core Component Features.
+*
+* @class
+*/
+Phaser.Component.Core = function () {};
+
+/**
+* Installs / registers mixin components.
+*
+* The `this` context should be that of the applicable object instance or prototype.
+*
+* @method
+* @protected
+*/
+Phaser.Component.Core.install = function (components) {
+
+    // Always install 'Core' first
+    Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype);
+
+    this.components = {};
+
+    for (var i = 0; i < components.length; i++)
+    {
+        var id = components[i];
+        var replace = false;
+
+        if (id === 'Destroy')
+        {
+            replace = true;
+        }
+
+        Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace);
+
+        this.components[id] = true;
+    }
+
+};
+
+/**
+* Initializes the mixin components.
+*
+* The `this` context should be an instance of the component mixin target.
+*
+* @method
+* @protected
+*/
+Phaser.Component.Core.init = function (game, x, y, key, frame) {
+
+    this.game = game;
+
+    this.key = key;
+
+    this.position.set(x, y);
+    this.world = new Phaser.Point(x, y);
+    this.previousPosition = new Phaser.Point(x, y);
+
+    this.events = new Phaser.Events(this);
+
+    this._bounds = new Phaser.Rectangle();
+
+    if (this.components.PhysicsBody)
+    {
+        // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype.
+        this.body = this.body;
+    }
+
+    if (this.components.Animation)
+    {
+        this.animations = new Phaser.AnimationManager(this);
+    }
+
+    if (this.components.LoadTexture && key !== null)
+    {
+        this.loadTexture(key, frame);
+    }
+
+    if (this.components.FixedToCamera)
+    {
+        this.cameraOffset = new Phaser.Point(x, y);
+    }
+
+};
+
+Phaser.Component.Core.preUpdate = function () {
+
+    if (this.pendingDestroy)
+    {
+        this.destroy();
+        return;
+    }
+
+    this.previousPosition.set(this.world.x, this.world.y);
+    this.previousRotation = this.rotation;
+
+    if (!this.exists || !this.parent.exists)
+    {
+        this.renderOrderID = -1;
+        return false;
+    }
+
+    this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
+
+    if (this.visible)
+    {
+        this.renderOrderID = this.game.stage.currentRenderOrderID++;
+    }
+
+    if (this.texture)
+    {
+        this.texture.requiresReTint = false;
+    }
+
+    if (this.animations)
+    {
+        this.animations.update();
+    }
+
+    if (this.body)
+    {
+        this.body.preUpdate();
+    }
+
+    for (var i = 0; i < this.children.length; i++)
+    {
+        this.children[i].preUpdate();
+    }
+
+    return true;
+
+};
+
+Phaser.Component.Core.prototype = {
+
+    /**
+    * A reference to the currently running Game.
+    * @property {Phaser.Game} game
+    */
+    game: null,
+
+    /**
+    * A user defined name given to this Game Object.
+    * This value isn't ever used internally by Phaser, it is meant as a game level property.
+    * @property {string} name
+    * @default
+    */
+    name: '',
+
+    /**
+    * The components this Game Object has installed.
+    * @property {object} components
+    * @protected
+    */
+    components: {},
+
+    /**
+    * The z depth of this Game Object within its parent Group.
+    * No two objects in a Group can have the same z value.
+    * This value is adjusted automatically whenever the Group hierarchy changes.
+    * @property {number} z
+    */
+    z: 0,
+
+    /**
+    * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this
+    * Game Object, or any of its components.
+    * @see Phaser.Events
+    * @property {Phaser.Events} events
+    */
+    events: undefined,
+
+    /**
+    * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance.
+    * Through it you can create, play, pause and stop animations.
+    * @see Phaser.AnimationManager
+    * @property {Phaser.AnimationManager} animations
+    */
+    animations: undefined,
+
+    /**
+    * The key of the image or texture used by this Game Object during rendering.
+    * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache.
+    * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
+    * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache.
+    * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it.
+    * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key
+    */
+    key: '',
+
+    /**
+    * The world coordinates of this Game Object in pixels.
+    * Depending on where in the display list this Game Object is placed this value can differ from `position`, 
+    * which contains the x/y coordinates relative to the Game Objects parent.
+    * @property {Phaser.Point} world
+    */
+    world: null,
+
+    /**
+    * A debug flag designed for use with `Game.enableStep`.
+    * @property {boolean} debug
+    * @default
+    */
+    debug: false,
+
+    /**
+    * The position the Game Object was located in the previous frame.
+    * @property {Phaser.Point} previousPosition
+    * @readOnly
+    */
+    previousPosition: null,
+
+    /**
+    * The rotation the Game Object was in set to in the previous frame. Value is in radians.
+    * @property {number} previousRotation
+    * @readOnly
+    */
+    previousRotation: 0,
+
+    /**
+    * The render order ID is used internally by the renderer and Input Manager and should not be modified.
+    * This property is mostly used internally by the renderers, but is exposed for the use of plugins.
+    * @property {number} renderOrderID
+    * @readOnly
+    */
+    renderOrderID: 0,
+
+    /**
+    * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update.
+    * This property is mostly used internally by the physics systems, but is exposed for the use of plugins.
+    * @property {boolean} fresh
+    * @readOnly
+    */
+    fresh: true,
+
+    /**
+    * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update.
+    * You can set it directly to allow you to flag an object to be destroyed on its next update.
+    * 
+    * This is extremely useful if you wish to destroy an object from within one of its own callbacks 
+    * such as with Buttons or other Input events.
+    * 
+    * @property {boolean} pendingDestroy
+    */
+    pendingDestroy: false,
+
+    /**
+    * @property {Phaser.Rectangle} _bounds - Internal cache var.
+    * @private
+    */
+    _bounds: null,
+
+    /**
+    * @property {boolean} _exists - Internal cache var.
+    * @private
+    */
+    _exists: true,
+
+    /**
+    * Controls if this Game Object is processed by the core game loop.
+    * If this Game Object has a physics body it also controls if its physics body is updated or not.
+    * When `exists` is set to `false` it will remove its physics body from the physics world if it has one.
+    * It also toggles the `visible` property to false as well.
+    *
+    * Setting `exists` to true will add its physics body back in to the physics world, if it has one.
+    * It will also set the `visible` property to `true`.
+    *
+    * @property {boolean} exists
+    */
+    exists: {
+
+        get: function () {
+
+            return this._exists;
+
+        },
+
+        set: function (value) {
+
+            if (value)
+            {
+                this._exists = true;
+
+                if (this.body && this.body.type === Phaser.Physics.P2JS)
+                {
+                    this.body.addToWorld();
+                }
+
+                this.visible = true;
+            }
+            else
+            {
+                this._exists = false;
+
+                if (this.body && this.body.type === Phaser.Physics.P2JS)
+                {
+                    this.body.removeFromWorld();
+                }
+
+                this.visible = false;
+            }
+
+        }
+
+    },
+
+    /**
+    * Override this method in your own custom objects to handle any update requirements.
+    * It is called immediately after `preUpdate` and before `postUpdate`.
+    * Remember if this Game Object has any children you should call update on those too.
+    *
+    * @method
+    */
+    update: function() {
+
+    },
+
+    /**
+    * Internal method called by the World postUpdate cycle.
+    *
+    * @method
+    * @protected
+    */
+    postUpdate: function() {
+
+        if (this.customRender)
+        {
+            this.key.render();
+        }
+
+        if (this.components.PhysicsBody)
+        {
+            Phaser.Component.PhysicsBody.postUpdate.call(this);
+        }
+
+        if (this.components.FixedToCamera)
+        {
+            Phaser.Component.FixedToCamera.postUpdate.call(this);
+        }
+
+        for (var i = 0; i < this.children.length; i++)
+        {
+            this.children[i].postUpdate();
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, 
+* which can be updated in real-time.
+*
+* @class
+*/
+Phaser.Component.Crop = function () {};
+
+Phaser.Component.Crop.prototype = {
+
+    /**
+    * The Rectangle used to crop the texture this Game Object uses.
+    * Set this property via `crop`. 
+    * If you modify this property directly you must call `updateCrop` in order to have the change take effect.
+    * @property {Phaser.Rectangle} cropRect
+    * @default
+    */
+    cropRect: null,
+
+    /**
+    * @property {Phaser.Rectangle} _crop - Internal cache var.
+    * @private
+    */
+    _crop: null,
+
+    /**
+    * Crop allows you to crop the texture being used to display this Game Object.
+    * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly.
+    *
+    * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method,
+    * or by modifying `cropRect` property directly and then calling `updateCrop`.
+    *
+    * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object 
+    * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties.
+    * 
+    * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, 
+    * in which case the values are duplicated to a local object.
+    *
+    * @method
+    * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle.
+    * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect.
+    */
+    crop: function(rect, copy) {
+
+        if (copy === undefined) { copy = false; }
+
+        if (rect)
+        {
+            if (copy && this.cropRect !== null)
+            {
+                this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height);
+            }
+            else if (copy && this.cropRect === null)
+            {
+                this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height);
+            }
+            else
+            {
+                this.cropRect = rect;
+            }
+
+            this.updateCrop();
+        }
+        else
+        {
+            this._crop = null;
+            this.cropRect = null;
+
+            this.resetFrame();
+        }
+
+    },
+
+    /**
+    * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property,
+    * or the rectangle it references, then you need to update the crop frame by calling this method.
+    *
+    * @method
+    */
+    updateCrop: function() {
+
+        if (!this.cropRect)
+        {
+            return;
+        }
+
+        this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop);
+        this._crop.x += this._frame.x;
+        this._crop.y += this._frame.y;
+
+        var cx = Math.max(this._frame.x, this._crop.x);
+        var cy = Math.max(this._frame.y, this._crop.y);
+        var cw = Math.min(this._frame.right, this._crop.right) - cx;
+        var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy;
+
+        this.texture.crop.x = cx;
+        this.texture.crop.y = cy;
+        this.texture.crop.width = cw;
+        this.texture.crop.height = ch;
+
+        this.texture.frame.width = Math.min(cw, this.cropRect.width);
+        this.texture.frame.height = Math.min(ch, this.cropRect.height);
+
+        this.texture.width = this.texture.frame.width;
+        this.texture.height = this.texture.frame.height;
+
+        this.texture._updateUvs();
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Delta component provides access to delta values between the Game Objects current and previous position.
+*
+* @class
+*/
+Phaser.Component.Delta = function () {};
+
+Phaser.Component.Delta.prototype = {
+
+    /**
+    * Returns the delta x value. The difference between world.x now and in the previous frame.
+    * 
+    * The value will be positive if the Game Object has moved to the right or negative if to the left.
+    *
+    * @property {number} deltaX
+    * @readonly
+    */
+    deltaX: {
+
+        get: function() {
+
+            return this.world.x - this.previousPosition.x;
+
+        }
+
+    },
+
+    /**
+    * Returns the delta y value. The difference between world.y now and in the previous frame.
+    * 
+    * The value will be positive if the Game Object has moved down or negative if up.
+    *
+    * @property {number} deltaY
+    * @readonly
+    */
+    deltaY: {
+
+        get: function() {
+
+            return this.world.y - this.previousPosition.y;
+
+        }
+
+    },
+
+    /**
+    * Returns the delta z value. The difference between rotation now and in the previous frame.
+    *
+    * @property {number} deltaZ - The delta value.
+    * @readonly
+    */
+    deltaZ: {
+
+        get: function() {
+
+            return this.rotation - this.previousRotation;
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Destroy component is responsible for destroying a Game Object.
+*
+* @class
+*/
+Phaser.Component.Destroy = function () {};
+
+Phaser.Component.Destroy.prototype = {
+
+    /**
+    * As a Game Object runs through its destroy method this flag is set to true, 
+    * and can be checked in any sub-systems or plugins it is being destroyed from.
+    * @property {boolean} destroyPhase
+    * @readOnly
+    */
+    destroyPhase: false,
+
+    /**
+    * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present
+    * and nulls its reference to `game`, freeing it up for garbage collection.
+    * 
+    * If this Game Object has the Events component it will also dispatch the `onDestroy` event.
+    *
+    * @method
+    * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well?
+    */
+    destroy: function (destroyChildren) {
+
+        if (this.game === null || this.destroyPhase) { return; }
+
+        if (destroyChildren === undefined) { destroyChildren = true; }
+
+        this.destroyPhase = true;
+
+        if (this.events)
+        {
+            this.events.onDestroy$dispatch(this);
+        }
+
+        if (this.parent)
+        {
+            if (this.parent instanceof Phaser.Group)
+            {
+                this.parent.remove(this);
+            }
+            else
+            {
+                this.parent.removeChild(this);
+            }
+        }
+
+        if (this.input)
+        {
+            this.input.destroy();
+        }
+
+        if (this.animations)
+        {
+            this.animations.destroy();
+        }
+
+        if (this.body)
+        {
+            this.body.destroy();
+        }
+
+        if (this.events)
+        {
+            this.events.destroy();
+        }
+
+        var i = this.children.length;
+
+        if (destroyChildren)
+        {
+            while (i--)
+            {
+                this.children[i].destroy(destroyChildren);
+            }
+        }
+        else
+        {
+            while (i--)
+            {
+                this.removeChild(this.children[i]);
+            }
+        }
+
+        if (this._crop)
+        {
+            this._crop = null;
+        }
+
+        if (this._frame)
+        {
+            this._frame = null;
+        }
+
+        if (Phaser.Video && this.key instanceof Phaser.Video)
+        {
+            this.key.onChangeSource.remove(this.resizeFrame, this);
+        }
+
+        if (Phaser.BitmapText && this._glyphs)
+        {
+            this._glyphs = [];
+        }
+
+        this.alive = false;
+        this.exists = false;
+        this.visible = false;
+
+        this.filters = null;
+        this.mask = null;
+        this.game = null;
+
+        //  In case Pixi is still going to try and render it even though destroyed
+        this.renderable = false;
+
+        //  Pixi level DisplayObject destroy
+        this.transformCallback = null;
+        this.transformCallbackContext = null;
+        this.hitArea = null;
+        this.parent = null;
+        this.stage = null;
+        this.worldTransform = null;
+        this.filterArea = null;
+        this._bounds = null;
+        this._currentBounds = null;
+        this._mask = null;
+
+        this._destroyCachedSprite();
+
+        this.destroyPhase = false;
+        this.pendingDestroy = false;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Events component is a collection of events fired by the parent game object.
+*
+* For example to tell when a Sprite has been added to a new group:
+*
+* `sprite.events.onAddedToGroup.add(yourFunction, this);`
+*
+* Where `yourFunction` is the function you want called when this event occurs.
+*
+* The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true`
+* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}.
+*
+* @class Phaser.Events
+* @constructor
+* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object.
+*/
+Phaser.Events = function (sprite) {
+
+    /**
+    * @property {Phaser.Sprite} parent - The Sprite that owns these events.
+    */
+    this.parent = sprite;
+
+    // The signals are automatically added by the corresponding proxy properties
+
+};
+
+Phaser.Events.prototype = {
+
+    /**
+     * Removes all events.
+     *
+     * @method Phaser.Events#destroy
+     */
+    destroy: function () {
+
+        this._parent = null;
+
+        if (this._onDestroy)           { this._onDestroy.dispose(); }
+        if (this._onAddedToGroup)      { this._onAddedToGroup.dispose(); }
+        if (this._onRemovedFromGroup)  { this._onRemovedFromGroup.dispose(); }
+        if (this._onRemovedFromWorld)  { this._onRemovedFromWorld.dispose(); }
+        if (this._onKilled)            { this._onKilled.dispose(); }
+        if (this._onRevived)           { this._onRevived.dispose(); }
+        if (this._onEnterBounds)       { this._onEnterBounds.dispose(); }
+        if (this._onOutOfBounds)       { this._onOutOfBounds.dispose(); }
+
+        if (this._onInputOver)         { this._onInputOver.dispose(); }
+        if (this._onInputOut)          { this._onInputOut.dispose(); }
+        if (this._onInputDown)         { this._onInputDown.dispose(); }
+        if (this._onInputUp)           { this._onInputUp.dispose(); }
+        if (this._onDragStart)         { this._onDragStart.dispose(); }
+        if (this._onDragUpdate)        { this._onDragUpdate.dispose(); }
+        if (this._onDragStop)          { this._onDragStop.dispose(); }
+
+        if (this._onAnimationStart)    { this._onAnimationStart.dispose(); }
+        if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); }
+        if (this._onAnimationLoop)     { this._onAnimationLoop.dispose(); }
+
+    },
+
+    // The following properties are sentinels that will be replaced with getters
+
+    /**
+    * @property {Phaser.Signal} onAddedToGroup - This signal is dispatched when the parent is added to a new Group.
+    */
+    onAddedToGroup: null,
+
+    /**
+    * @property {Phaser.Signal} onRemovedFromGroup - This signal is dispatched when the parent is removed from a Group.
+    */
+    onRemovedFromGroup: null,
+
+    /**
+    * @property {Phaser.Signal} onRemovedFromWorld - This signal is dispatched if this item or any of its parents are removed from the game world.
+    */
+    onRemovedFromWorld: null,
+
+    /**
+    * @property {Phaser.Signal} onDestroy - This signal is dispatched when the parent is destroyed.
+    */
+    onDestroy: null,
+
+    /**
+    * @property {Phaser.Signal} onKilled - This signal is dispatched when the parent is killed.
+    */
+    onKilled: null,
+
+    /**
+    * @property {Phaser.Signal} onRevived - This signal is dispatched when the parent is revived.
+    */
+    onRevived: null,
+
+    /**
+    * @property {Phaser.Signal} onOutOfBounds - This signal is dispatched when the parent leaves the world bounds (only if Sprite.checkWorldBounds is true).
+    */
+    onOutOfBounds: null,
+
+    /**
+    * @property {Phaser.Signal} onEnterBounds - This signal is dispatched when the parent returns within the world bounds (only if Sprite.checkWorldBounds is true).
+    */
+    onEnterBounds: null,
+
+    /**
+    * @property {Phaser.Signal} onInputOver - This signal is dispatched if the parent is inputEnabled and receives an over event from a Pointer.
+    */
+    onInputOver: null,
+
+    /**
+    * @property {Phaser.Signal} onInputOut - This signal is dispatched if the parent is inputEnabled and receives an out event from a Pointer.
+    */
+    onInputOut: null,
+
+    /**
+    * @property {Phaser.Signal} onInputDown - This signal is dispatched if the parent is inputEnabled and receives a down event from a Pointer.
+    */
+    onInputDown: null,
+
+    /**
+    * @property {Phaser.Signal} onInputUp - This signal is dispatched if the parent is inputEnabled and receives an up event from a Pointer.
+    */
+    onInputUp: null,
+
+    /**
+    * @property {Phaser.Signal} onDragStart - This signal is dispatched if the parent is inputEnabled and receives a drag start event from a Pointer.
+    */
+    onDragStart: null,
+
+    /**
+    * @property {Phaser.Signal} onDragUpdate - This signal is dispatched if the parent is inputEnabled and receives a drag update event from a Pointer.
+    */
+    onDragUpdate: null,
+
+    /**
+    * @property {Phaser.Signal} onDragStop - This signal is dispatched if the parent is inputEnabled and receives a drag stop event from a Pointer.
+    */
+    onDragStop: null,
+
+    /**
+    * @property {Phaser.Signal} onAnimationStart - This signal is dispatched when the parent has an animation that is played.
+    */
+    onAnimationStart: null,
+
+    /**
+    * @property {Phaser.Signal} onAnimationComplete - This signal is dispatched when the parent has an animation that finishes playing.
+    */
+    onAnimationComplete: null,
+
+    /**
+    * @property {Phaser.Signal} onAnimationLoop - This signal is dispatched when the parent has an animation that loops playback.
+    */
+    onAnimationLoop: null
+
+};
+
+Phaser.Events.prototype.constructor = Phaser.Events;
+
+// Create an auto-create proxy getter and dispatch method for all events.
+// The backing property is the same as the event name, prefixed with '_'
+// and the dispatch method is the same as the event name postfixed with '$dispatch'.
+for (var prop in Phaser.Events.prototype)
+{
+    if (!Phaser.Events.prototype.hasOwnProperty(prop) ||
+        prop.indexOf('on') !== 0 ||
+        Phaser.Events.prototype[prop] !== null)
+    {
+        continue;
+    }
+
+    (function (prop, backing) {
+        'use strict';
+
+        // The accessor creates a new Signal; and so it should only be used from user-code.
+        Object.defineProperty(Phaser.Events.prototype, prop, {
+            get: function () {
+                return this[backing] || (this[backing] = new Phaser.Signal());
+            }
+        });
+
+        // The dispatcher will only broadcast on an already-created signal; call this internally.
+        Phaser.Events.prototype[prop + '$dispatch'] = function () {
+            return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null;
+        };
+
+    })(prop, '_' + prop);
+
+}
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless 
+* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world.
+*
+* @class
+*/
+Phaser.Component.FixedToCamera = function () {};
+
+/**
+ * The FixedToCamera component postUpdate handler.
+ * Called automatically by the Game Object.
+ *
+ * @method
+ */
+Phaser.Component.FixedToCamera.postUpdate = function () {
+
+    if (this.fixedToCamera)
+    {
+        this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
+        this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
+    }
+
+};
+
+Phaser.Component.FixedToCamera.prototype = {
+
+    /**
+    * @property {boolean} _fixedToCamera
+    * @private
+    */
+    _fixedToCamera: false,
+
+    /**
+    * A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering.
+    * 
+    * The values are adjusted at the rendering stage, overriding the Game Objects actual world position.
+    * 
+    * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world
+    * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times 
+    * regardless where in the world the camera is.
+    * 
+    * The offsets are stored in the `cameraOffset` property.
+    * 
+    * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list.
+    *
+    * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them.
+    *
+    * @property {boolean} fixedToCamera
+    */
+    fixedToCamera: {
+
+        get: function () {
+
+            return this._fixedToCamera;
+
+        },
+
+        set: function (value) {
+
+            if (value)
+            {
+                this._fixedToCamera = true;
+                this.cameraOffset.set(this.x, this.y);
+            }
+            else
+            {
+                this._fixedToCamera = false;
+            }
+
+        }
+
+    },
+
+    /**
+    * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true.
+    * 
+    * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list.
+    * @property {Phaser.Point} cameraOffset
+    */
+    cameraOffset: new Phaser.Point()
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Health component provides the ability for Game Objects to have a `health` property 
+* that can be damaged and reset through game code.
+* Requires the LifeSpan component.
+*
+* @class
+*/
+Phaser.Component.Health = function () {};
+
+Phaser.Component.Health.prototype = {
+
+    /**
+    * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object.
+    * 
+    * It can be used in combination with the `damage` method or modified directly.
+    * 
+    * @property {number} health
+    * @default
+    */
+    health: 1,
+
+    /**
+    * The Game Objects maximum health value. This works in combination with the `heal` method to ensure
+    * the health value never exceeds the maximum.
+    * 
+    * @property {number} maxHealth
+    * @default
+    */
+    maxHealth: 100,
+
+    /**
+    * Damages the Game Object. This removes the given amount of health from the `health` property.
+    * 
+    * If health is taken below or is equal to zero then the `kill` method is called.
+    *
+    * @member
+    * @param {number} amount - The amount to subtract from the current `health` value.
+    * @return {Phaser.Sprite} This instance.
+    */
+    damage: function(amount) {
+
+        if (this.alive)
+        {
+            this.health -= amount;
+
+            if (this.health <= 0)
+            {
+                this.kill();
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Heal the Game Object. This adds the given amount of health to the `health` property.
+    *
+    * @member
+    * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`.
+    * @return {Phaser.Sprite} This instance.
+    */
+    heal: function(amount) {
+
+        if (this.alive)
+        {
+            this.health += amount;
+
+            if (this.health > this.maxHealth)
+            {
+                this.health = this.maxHealth;
+            }
+        }
+
+        return this;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The InCamera component checks if the Game Object intersects with the Game Camera.
+*
+* @class
+*/
+Phaser.Component.InCamera = function () {};
+
+Phaser.Component.InCamera.prototype = {
+
+    /**
+    * Checks if this Game Objects bounds intersects with the Game Cameras bounds.
+    * 
+    * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds.
+    * 
+    * An object outside the bounds can be considered for camera culling if it has the AutoCull component.
+    *
+    * @property {boolean} inCamera
+    * @readonly
+    */
+    inCamera: {
+
+        get: function() {
+
+            return this.game.world.camera.view.intersects(this._bounds);
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events.
+*
+* @class
+*/
+Phaser.Component.InputEnabled = function () {};
+
+Phaser.Component.InputEnabled.prototype = {
+
+    /**
+    * The Input Handler for this Game Object.
+    * 
+    * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`.
+    * 
+    * After you have done this, this property will be a reference to the Phaser InputHandler.
+    * @property {Phaser.InputHandler|null} input 
+    */
+    input: null,
+
+    /**
+    * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created
+    * for this Game Object and it will then start to process click / touch events and more.
+    * 
+    * You can then access the Input Handler via `this.input`.
+    * 
+    * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`.
+    * 
+    * If you set this property to false it will stop the Input Handler from processing any more input events.
+    *
+    * @property {boolean} inputEnabled
+    */
+    inputEnabled: {
+
+        get: function () {
+
+            return (this.input && this.input.enabled);
+
+        },
+
+        set: function (value) {
+
+            if (value)
+            {
+                if (this.input === null)
+                {
+                    this.input = new Phaser.InputHandler(this);
+                    this.input.start();
+                }
+                else if (this.input && !this.input.enabled)
+                {
+                    this.input.start();
+                }
+            }
+            else
+            {
+                if (this.input && this.input.enabled)
+                {
+                    this.input.stop();
+                }
+            }
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The InWorld component checks if a Game Object is within the Game World Bounds.
+* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds.
+* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well.
+*
+* @class
+*/
+Phaser.Component.InWorld = function () {};
+
+/**
+ * The InWorld component preUpdate handler.
+ * Called automatically by the Game Object.
+ *
+ * @method
+ */
+Phaser.Component.InWorld.preUpdate = function () {
+
+    //  Cache the bounds if we need it
+    if (this.autoCull || this.checkWorldBounds)
+    {
+        this._bounds.copyFrom(this.getBounds());
+
+        this._bounds.x += this.game.camera.view.x;
+        this._bounds.y += this.game.camera.view.y;
+
+        if (this.autoCull)
+        {
+            //  Won't get rendered but will still get its transform updated
+            if (this.game.world.camera.view.intersects(this._bounds))
+            {
+                this.renderable = true;
+                this.game.world.camera.totalInView++;
+            }
+            else
+            {
+                this.renderable = false;
+            }
+        }
+
+        if (this.checkWorldBounds)
+        {
+            //  The Sprite is already out of the world bounds, so let's check to see if it has come back again
+            if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds))
+            {
+                this._outOfBoundsFired = false;
+                this.events.onEnterBounds$dispatch(this);
+            }
+            else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds))
+            {
+                //  The Sprite WAS in the screen, but has now left.
+                this._outOfBoundsFired = true;
+                this.events.onOutOfBounds$dispatch(this);
+
+                if (this.outOfBoundsKill)
+                {
+                    this.kill();
+                    return false;
+                }
+            }
+        }
+    }
+
+    return true;
+
+};
+
+Phaser.Component.InWorld.prototype = {
+
+    /**
+    * If this is set to `true` the Game Object checks if it is within the World bounds each frame. 
+    * 
+    * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event.
+    * 
+    * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event.
+    * 
+    * It also optionally kills the Game Object if `outOfBoundsKill` is `true`.
+    * 
+    * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame.
+    * 
+    * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required,
+    * or you have tested performance and find it acceptable.
+    * 
+    * @property {boolean} checkWorldBounds
+    * @default
+    */
+    checkWorldBounds: false,
+
+    /**
+    * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false.
+    * 
+    * @property {boolean} outOfBoundsKill
+    * @default
+    */
+    outOfBoundsKill: false,
+
+    /**
+    * @property {boolean} _outOfBoundsFired - Internal state var.
+    * @private
+    */
+    _outOfBoundsFired: false,
+
+    /**
+    * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds.
+    *
+    * @property {boolean} inWorld
+    * @readonly
+    */
+    inWorld: {
+
+        get: function () {
+
+            return this.game.world.bounds.intersects(this.getBounds());
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* LifeSpan Component Features.
+*
+* @class
+*/
+Phaser.Component.LifeSpan = function () {};
+
+/**
+ * The LifeSpan component preUpdate handler.
+ * Called automatically by the Game Object.
+ *
+ * @method
+ */
+Phaser.Component.LifeSpan.preUpdate = function () {
+
+    if (this.lifespan > 0)
+    {
+        this.lifespan -= this.game.time.physicsElapsedMS;
+
+        if (this.lifespan <= 0)
+        {
+            this.kill();
+            return false;
+        }
+    }
+
+    return true;
+
+};
+
+Phaser.Component.LifeSpan.prototype = {
+
+    /**
+    * A useful flag to control if the Game Object is alive or dead.
+    * 
+    * This is set automatically by the Health components `damage` method should the object run out of health.
+    * Or you can toggle it via your game code.
+    * 
+    * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates.
+    * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling.
+    * @property {boolean} alive
+    * @default
+    */
+    alive: true,
+
+    /**
+    * The lifespan allows you to give a Game Object a lifespan in milliseconds.
+    * 
+    * Once the Game Object is 'born' you can set this to a positive value.
+    * 
+    * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame.
+    * When it reaches zero it will call the `kill` method.
+    * 
+    * Very handy for particles, bullets, collectibles, or any other short-lived entity.
+    *
+    * @property {number} lifespan
+    * @default
+    */
+    lifespan: 0,
+
+    /**
+    * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process.
+    * 
+    * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true.
+    * 
+    * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal.
+    *
+    * @method
+    * @param {number} [health=1] - The health to give the Game Object. Only set if the GameObject has the Health component.
+    * @return {PIXI.DisplayObject} This instance.
+    */
+    revive: function (health) {
+
+        if (health === undefined) { health = 1; }
+
+        this.alive = true;
+        this.exists = true;
+        this.visible = true;
+ 
+        if (typeof this.health === 'number')
+        {
+            this.health = health;
+        }
+
+        if (this.events)
+        {
+            this.events.onRevived$dispatch(this);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false.
+    * 
+    * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal.
+    * 
+    * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, 
+    * it doesn't destroy the object or free it up from memory.
+    * 
+    * If you don't need this Game Object any more you should call `destroy` instead.
+    *
+    * @method
+    * @return {PIXI.DisplayObject} This instance.
+    */
+    kill: function () {
+
+        this.alive = false;
+        this.exists = false;
+        this.visible = false;
+
+        if (this.events)
+        {
+            this.events.onKilled$dispatch(this);
+        }
+
+        return this;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames.
+*
+* @class
+*/
+Phaser.Component.LoadTexture = function () {};
+
+Phaser.Component.LoadTexture.prototype = {
+
+    /**
+    * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc)
+    * @private
+    */
+    customRender: false,
+
+    /**
+    * @property {Phaser.Rectangle} _frame - Internal cache var.
+    * @private
+    */
+    _frame: null,
+
+    /**
+    * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache.
+    * 
+    * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead.
+    * 
+    * You should only use `loadTexture` if you want to replace the base texture entirely.
+    * 
+    * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU.
+    *
+    * @method
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
+    * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+    * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing.
+    */
+    loadTexture: function (key, frame, stopAnimation) {
+
+        frame = frame || 0;
+
+        if ((stopAnimation || stopAnimation === undefined) && this.animations)
+        {
+            this.animations.stop();
+        }
+
+        this.key = key;
+        this.customRender = false;
+        var cache = this.game.cache;
+
+        var setFrame = true;
+        var smoothed = !this.texture.baseTexture.scaleMode;
+
+        if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture)
+        {
+            this.key = key.key;
+            this.setTexture(key);
+        }
+        else if (Phaser.BitmapData && key instanceof Phaser.BitmapData)
+        {
+            this.customRender = true;
+
+            this.setTexture(key.texture);
+
+            if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA))
+            {
+                setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame);
+            }
+        }
+        else if (Phaser.Video && key instanceof Phaser.Video)
+        {
+            this.customRender = true;
+
+            //  This works from a reference, which probably isn't what we need here
+            var valid = key.texture.valid;
+            this.setTexture(key.texture);
+            this.setFrame(key.texture.frame.clone());
+            key.onChangeSource.add(this.resizeFrame, this);
+            this.texture.valid = valid;
+        }
+        else if (key instanceof PIXI.Texture)
+        {
+            this.setTexture(key);
+        }
+        else
+        {
+            var img = cache.getImage(key, true);
+
+            this.key = img.key;
+            this.setTexture(new PIXI.Texture(img.base));
+
+            setFrame = !this.animations.loadFrameData(img.frameData, frame);
+        }
+        
+        if (setFrame)
+        {
+            this._frame = Phaser.Rectangle.clone(this.texture.frame);
+        }
+
+        if (!smoothed)
+        {
+            this.texture.baseTexture.scaleMode = 1;
+        }
+
+    },
+
+    /**
+    * Sets the texture frame the Game Object uses for rendering.
+    * 
+    * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes.
+    *
+    * @method
+    * @param {Phaser.Frame} frame - The Frame to be used by the texture.
+    */
+    setFrame: function (frame) {
+
+        this._frame = frame;
+
+        this.texture.frame.x = frame.x;
+        this.texture.frame.y = frame.y;
+        this.texture.frame.width = frame.width;
+        this.texture.frame.height = frame.height;
+
+        this.texture.crop.x = frame.x;
+        this.texture.crop.y = frame.y;
+        this.texture.crop.width = frame.width;
+        this.texture.crop.height = frame.height;
+
+        if (frame.trimmed)
+        {
+            if (this.texture.trim)
+            {
+                this.texture.trim.x = frame.spriteSourceSizeX;
+                this.texture.trim.y = frame.spriteSourceSizeY;
+                this.texture.trim.width = frame.sourceSizeW;
+                this.texture.trim.height = frame.sourceSizeH;
+            }
+            else
+            {
+                this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH };
+            }
+
+            this.texture.width = frame.sourceSizeW;
+            this.texture.height = frame.sourceSizeH;
+            this.texture.frame.width = frame.sourceSizeW;
+            this.texture.frame.height = frame.sourceSizeH;
+        }
+        else if (!frame.trimmed && this.texture.trim)
+        {
+            this.texture.trim = null;
+        }
+
+        if (this.cropRect)
+        {
+            this.updateCrop();
+        }
+
+        this.texture.requiresReTint = true;
+        
+        this.texture._updateUvs();
+
+        if (this.tilingTexture)
+        {
+            this.refreshTexture = true;
+        }
+
+    },
+
+    /**
+    * Resizes the Frame dimensions that the Game Object uses for rendering.
+    * 
+    * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData
+    * it can be useful to adjust the dimensions directly in this way.
+    *
+    * @method
+    * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object.
+    * @param {integer} width - The new width of the texture.
+    * @param {integer} height - The new height of the texture.
+    */
+    resizeFrame: function (parent, width, height) {
+
+        this.texture.frame.resize(width, height);
+        this.texture.setFrame(this.texture.frame);
+
+    },
+
+    /**
+    * Resets the texture frame dimensions that the Game Object uses for rendering.
+    *
+    * @method
+    */
+    resetFrame: function () {
+
+        if (this._frame)
+        {
+            this.setFrame(this._frame);
+        }
+
+    },
+
+    /**
+    * Gets or sets the current frame index of the texture being used to render this Game Object.
+    *
+    * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use,
+    * for example: `player.frame = 4`.
+    * 
+    * If the frame index given doesn't exist it will revert to the first frame found in the texture.
+    * 
+    * If you are using a texture atlas then you should use the `frameName` property instead.
+    * 
+    * If you wish to fully replace the texture being used see `loadTexture`.
+    * @property {integer} frame
+    */
+    frame: {
+
+        get: function () {
+            return this.animations.frame;
+        },
+
+        set: function (value) {
+            this.animations.frame = value;
+        }
+
+    },
+
+    /**
+    * Gets or sets the current frame name of the texture being used to render this Game Object.
+    * 
+    * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, 
+    * for example: `player.frameName = "idle"`.
+    *
+    * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning.
+    * 
+    * If you are using a sprite sheet then you should use the `frame` property instead.
+    * 
+    * If you wish to fully replace the texture being used see `loadTexture`.
+    * @property {string} frameName
+    */
+    frameName: {
+
+        get: function () {
+            return this.animations.frameName;
+        },
+
+        set: function (value) {
+            this.animations.frameName = value;
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object.
+*
+* @class
+*/
+Phaser.Component.Overlap = function () {};
+
+Phaser.Component.Overlap.prototype = {
+
+    /**
+    * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, 
+    * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result.
+    * 
+    * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result.
+    * 
+    * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency.
+    * It should be fine for low-volume testing where physics isn't required.
+    *
+    * @method
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against.
+    * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object.
+    */
+    overlap: function (displayObject) {
+
+        return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds());
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The PhysicsBody component manages the Game Objects physics body and physics enabling.
+* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself.
+*
+* @class
+*/
+Phaser.Component.PhysicsBody = function () {};
+
+/**
+ * The PhysicsBody component preUpdate handler.
+ * Called automatically by the Game Object.
+ *
+ * @method
+ */
+Phaser.Component.PhysicsBody.preUpdate = function () {
+
+    if (this.fresh && this.exists)
+    {
+        this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
+        this.worldTransform.tx = this.world.x;
+        this.worldTransform.ty = this.world.y;
+
+        this.previousPosition.set(this.world.x, this.world.y);
+        this.previousRotation = this.rotation;
+
+        if (this.body)
+        {
+            this.body.preUpdate();
+        }
+
+        this.fresh = false;
+
+        return false;
+    }
+
+    this.previousPosition.set(this.world.x, this.world.y);
+    this.previousRotation = this.rotation;
+
+    if (!this._exists || !this.parent.exists)
+    {
+        this.renderOrderID = -1;
+        return false;
+    }
+
+    return true;
+
+};
+
+/**
+ * The PhysicsBody component postUpdate handler.
+ * Called automatically by the Game Object.
+ *
+ * @method
+ */
+Phaser.Component.PhysicsBody.postUpdate = function () {
+
+    if (this.exists && this.body)
+    {
+        this.body.postUpdate();
+    }
+
+};
+
+Phaser.Component.PhysicsBody.prototype = {
+
+    /**
+    * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated 
+    * properties and methods via it.
+    * 
+    * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`.
+    * 
+    * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object
+    * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`.
+    * 
+    * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group.
+    *
+    * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, 
+    * so the physics body is centered on the Game Object.
+    * 
+    * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics.
+    *
+    * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
+    * @default
+    */
+    body: null,
+
+    /**
+    * The position of the Game Object on the x axis relative to the local coordinates of the parent.
+    *
+    * @property {number} x
+    */
+    x: {
+
+        get: function () {
+
+            return this.position.x;
+
+        },
+
+        set: function (value) {
+
+            this.position.x = value;
+
+            if (this.body && !this.body.dirty)
+            {
+                this.body._reset = true;
+            }
+
+        }
+
+    },
+
+    /**
+    * The position of the Game Object on the y axis relative to the local coordinates of the parent.
+    *
+    * @property {number} y
+    */
+    y: {
+
+        get: function () {
+
+            return this.position.y;
+
+        },
+
+        set: function (value) {
+
+            this.position.y = value;
+
+            if (this.body && !this.body.dirty)
+            {
+                this.body._reset = true;
+            }
+
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Reset component allows a Game Object to be reset and repositioned to a new location.
+*
+* @class
+*/
+Phaser.Component.Reset = function () {};
+
+/**
+* Resets the Game Object.
+* 
+* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, 
+* `visible` and `renderable` to true.
+*
+* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value.
+*
+* If this Game Object has a Physics Body it will reset the Body.
+*
+* @method
+* @param {number} x - The x coordinate (in world space) to position the Game Object at.
+* @param {number} y - The y coordinate (in world space) to position the Game Object at.
+* @param {number} [health=1] - The health to give the Game Object if it has the Health component.
+* @return {PIXI.DisplayObject} This instance.
+*/
+Phaser.Component.Reset.prototype.reset = function (x, y, health) {
+
+    if (health === undefined) { health = 1; }
+
+    this.world.set(x, y);
+    this.position.set(x, y);
+
+    this.fresh = true;
+    this.exists = true;
+    this.visible = true;
+    this.renderable = true;
+
+    if (this.components.InWorld)
+    {
+        this._outOfBoundsFired = false;
+    }
+
+    if (this.components.LifeSpan)
+    {
+        this.alive = true;
+        this.health = health;
+    }
+
+    if (this.components.PhysicsBody)
+    {
+        if (this.body)
+        {
+            this.body.reset(x, y, false, false);
+        }
+    }
+
+    return this;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent.
+*
+* @class
+*/
+Phaser.Component.ScaleMinMax = function () {};
+
+Phaser.Component.ScaleMinMax.prototype = {
+
+    /**
+    * The callback that will apply any scale limiting to the worldTransform.
+    * @property {function} transformCallback
+    */
+    transformCallback: this.checkTransform,
+
+    /**
+    * The context under which `transformCallback` is called.
+    * @property {object} transformCallbackContext
+    */
+    transformCallbackContext: this,
+
+    /**
+    * The minimum scale this Game Object will scale down to.
+    * 
+    * It allows you to prevent a parent from scaling this Game Object lower than the given value.
+    * 
+    * Set it to `null` to remove the limit.
+    * @property {Phaser.Point} scaleMin
+    */
+    scaleMin: null,
+
+    /**
+    * The maximum scale this Game Object will scale up to. 
+    * 
+    * It allows you to prevent a parent from scaling this Game Object higher than the given value.
+    * 
+    * Set it to `null` to remove the limit.
+    * @property {Phaser.Point} scaleMax
+    */
+    scaleMax: null,
+
+    /**
+     * Adjust scaling limits, if set, to this Game Object.
+     *
+     * @method
+     * @private
+     * @param {PIXI.Matrix} wt - The updated worldTransform matrix.
+     */
+    checkTransform: function (wt) {
+
+        if (this.scaleMin)
+        {
+            if (wt.a < this.scaleMin.x)
+            {
+                wt.a = this.scaleMin.x;
+            }
+
+            if (wt.d < this.scaleMin.y)
+            {
+                wt.d = this.scaleMin.y;
+            }
+        }
+
+        if (this.scaleMax)
+        {
+            if (wt.a > this.scaleMax.x)
+            {
+                wt.a = this.scaleMax.x;
+            }
+
+            if (wt.d > this.scaleMax.y)
+            {
+                wt.d = this.scaleMax.y;
+            }
+        }
+
+    },
+
+    /**
+     * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent.
+     * 
+     * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored 
+     * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to.
+     * 
+     * By setting these values you can carefully control how Game Objects deal with responsive scaling.
+     * 
+     * If only one parameter is given then that value will be used for both scaleMin and scaleMax:
+     * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1
+     *
+     * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y:
+     * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2
+     *
+     * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, 
+     * or pass `null` for the `maxX` and `maxY` parameters.
+     * 
+     * Call `setScaleMinMax(null)` to clear all previously set values.
+     *
+     * @method
+     * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to.
+     * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to.
+     * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to.
+     * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to.
+     */
+    setScaleMinMax: function (minX, minY, maxX, maxY) {
+
+        if (minY === undefined)
+        {
+            //  1 parameter, set all to it
+            minY = maxX = maxY = minX;
+        }
+        else if (maxX === undefined)
+        {
+            //  2 parameters, the first is min, the second max
+            maxX = maxY = minY;
+            minY = minX;
+        }
+
+        if (minX === null)
+        {
+            this.scaleMin = null;
+        }
+        else
+        {
+            if (this.scaleMin)
+            {
+                this.scaleMin.set(minX, minY);
+            }
+            else
+            {
+                this.scaleMin = new Phaser.Point(minX, minY);
+            }
+        }
+
+        if (maxX === null)
+        {
+            this.scaleMax = null;
+        }
+        else
+        {
+            if (this.scaleMax)
+            {
+                this.scaleMax.set(maxX, maxY);
+            }
+            else
+            {
+                this.scaleMax = new Phaser.Point(maxX, maxY);
+            }
+        }
+
+    }
+
+};
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture.
+*
+* @class
+*/
+Phaser.Component.Smoothed = function () {};
+
+Phaser.Component.Smoothed.prototype = {
+
+    /**
+    * Enable or disable texture smoothing for this Game Object.
+    * 
+    * It only takes effect if the Game Object is using an image based texture.
+    * 
+    * Smoothing is enabled by default.
+    *
+    * @property {boolean} smoothed
+    */
+    smoothed: {
+
+        get: function () {
+
+            return !this.texture.baseTexture.scaleMode;
+
+        },
+
+        set: function (value) {
+
+            if (value)
+            {
+                if (this.texture)
+                {
+                    this.texture.baseTexture.scaleMode = 0;
+                }
+            }
+            else
+            {
+                if (this.texture)
+                {
+                    this.texture.baseTexture.scaleMode = 1;
+                }
+            }
+        }
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The GameObjectFactory is a quick way to create many common game objects
+* using {@linkcode Phaser.Game#add `game.add`}.
+*
+* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group.
+*
+* @class Phaser.GameObjectFactory
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.GameObjectFactory = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    * @protected
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.World} world - A reference to the game world.
+    * @protected
+    */
+    this.world = this.game.world;
+
+};
+
+Phaser.GameObjectFactory.prototype = {
+
+    /**
+    * Adds an existing display object to the game world.
+    * 
+    * @method Phaser.GameObjectFactory#existing
+    * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object.
+    * @return {any} The child that was added to the World.
+    */
+    existing: function (object) {
+
+        return this.world.add(object);
+
+    },
+
+    /**
+    * Create a new `Image` object.
+    * 
+    * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
+    * 
+    * It can still rotate, scale, crop and receive input events. 
+    * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
+    *
+    * @method Phaser.GameObjectFactory#image
+    * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
+    * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
+    * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @returns {Phaser.Image} The newly created Image object.
+    */
+    image: function (x, y, key, frame, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.Image(this.game, x, y, key, frame));
+
+    },
+
+    /**
+    * Create a new Sprite with specific position and sprite sheet key.
+    *
+    * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered.
+    * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
+    * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
+    *
+    * @method Phaser.GameObjectFactory#sprite
+    * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
+    * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
+    * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @returns {Phaser.Sprite} The newly created Sprite object.
+    */
+    sprite: function (x, y, key, frame, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.create(x, y, key, frame);
+
+    },
+
+    /**
+    * Create a new Creature Animation object.
+    *
+    * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios.
+    * 
+    * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/).
+    * 
+    * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games.
+    *
+    * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them
+    * loaded before your Phaser game boots.
+    * 
+    * See the Phaser custom build process for more details.
+    *
+    * @method Phaser.GameObjectFactory#creature
+    * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in.
+    * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in.
+    * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @returns {Phaser.Creature} The newly created Sprite object.
+    */
+    creature: function (x, y, key, mesh, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        var obj = new Phaser.Creature(this.game, x, y, key, mesh);
+
+        group.add(obj);
+
+        return obj;
+
+    },
+
+    /**
+    * Create a tween on a specific object.
+    * 
+    * The object can be any JavaScript object or Phaser object such as Sprite.
+    *
+    * @method Phaser.GameObjectFactory#tween
+    * @param {object} object - Object the tween will be run on.
+    * @return {Phaser.Tween} The newly created Phaser.Tween object.
+    */
+    tween: function (object) {
+
+        return this.game.tweens.create(object);
+
+    },
+
+    /**
+    * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
+    *
+    * @method Phaser.GameObjectFactory#group
+    * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
+    * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
+    * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
+    * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
+    * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
+    * @return {Phaser.Group} The newly created Group.
+    */
+    group: function (parent, name, addToStage, enableBody, physicsBodyType) {
+
+        return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
+
+    },
+
+    /**
+    * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
+    * 
+    * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
+    * are automatically given a physics body.
+    *
+    * @method Phaser.GameObjectFactory#physicsGroup
+    * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
+    * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
+    * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
+    * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
+    * @return {Phaser.Group} The newly created Group.
+    */
+    physicsGroup: function (physicsBodyType, parent, name, addToStage) {
+
+        return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
+
+    },
+
+    /**
+    * A SpriteBatch is a really fast version of a Phaser Group built solely for speed.
+    * Use when you need a lot of sprites or particles all sharing the same texture.
+    * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference.
+    *
+    * @method Phaser.GameObjectFactory#spriteBatch
+    * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world.
+    * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging.
+    * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent.
+    * @return {Phaser.SpriteBatch} The newly created Sprite Batch.
+    */
+    spriteBatch: function (parent, name, addToStage) {
+
+        if (parent === undefined) { parent = null; }
+        if (name === undefined) { name = 'group'; }
+        if (addToStage === undefined) { addToStage = false; }
+
+        return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
+
+    },
+
+    /**
+    * Creates a new Sound object.
+    *
+    * @method Phaser.GameObjectFactory#audio
+    * @param {string} key - The Game.cache key of the sound that this object will use.
+    * @param {number} [volume=1] - The volume at which the sound will be played.
+    * @param {boolean} [loop=false] - Whether or not the sound will loop.
+    * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
+    * @return {Phaser.Sound} The newly created sound object.
+    */
+    audio: function (key, volume, loop, connect) {
+
+        return this.game.sound.add(key, volume, loop, connect);
+
+    },
+
+    /**
+    * Creates a new Sound object.
+    *
+    * @method Phaser.GameObjectFactory#sound
+    * @param {string} key - The Game.cache key of the sound that this object will use.
+    * @param {number} [volume=1] - The volume at which the sound will be played.
+    * @param {boolean} [loop=false] - Whether or not the sound will loop.
+    * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
+    * @return {Phaser.Sound} The newly created sound object.
+    */
+    sound: function (key, volume, loop, connect) {
+
+        return this.game.sound.add(key, volume, loop, connect);
+
+    },
+
+    /**
+     * Creates a new AudioSprite object.
+     *
+     * @method Phaser.GameObjectFactory#audioSprite
+     * @param {string} key - The Game.cache key of the sound that this object will use.
+     * @return {Phaser.AudioSprite} The newly created AudioSprite object.
+     */
+    audioSprite: function (key) {
+
+        return this.game.sound.addSprite(key);
+
+    },
+
+    /**
+    * Creates a new TileSprite object.
+    *
+    * @method Phaser.GameObjectFactory#tileSprite
+    * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in.
+    * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in.
+    * @param {number} width - The width of the TileSprite.
+    * @param {number} height - The height of the TileSprite.
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
+    * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.TileSprite} The newly created TileSprite object.
+    */
+    tileSprite: function (x, y, width, height, key, frame, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
+
+    },
+
+    /**
+    * Creates a new Rope object.
+    *
+    * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js
+    *
+    * @method Phaser.GameObjectFactory#rope
+    * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in.
+    * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in.
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
+    * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
+    * @param {Array} points - An array of {Phaser.Point}.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.Rope} The newly created Rope object.
+    */
+    rope: function (x, y, key, frame, points, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.Rope(this.game, x, y, key, frame, points));
+
+    },
+
+    /**
+    * Creates a new Text object.
+    *
+    * @method Phaser.GameObjectFactory#text
+    * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in.
+    * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in.
+    * @param {string} [text=''] - The text string that will be displayed.
+    * @param {object} [style] - The style object containing style attributes like font, font size , etc.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.Text} The newly created text object.
+    */
+    text: function (x, y, text, style, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.Text(this.game, x, y, text, style));
+
+    },
+
+    /**
+    * Creates a new Button object.
+    *
+    * @method Phaser.GameObjectFactory#button
+    * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in.
+    * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in.
+    * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button.
+    * @param {function} [callback] - The function to call when this button is pressed
+    * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this')
+    * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.Button} The newly created Button object.
+    */
+    button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
+
+    },
+
+    /**
+    * Creates a new Graphics object.
+    *
+    * @method Phaser.GameObjectFactory#graphics
+    * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in.
+    * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.Graphics} The newly created graphics object.
+    */
+    graphics: function (x, y, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.Graphics(this.game, x, y));
+
+    },
+
+    /**
+    * Create a new Emitter.
+    *
+    * A particle emitter can be used for one-time explosions or for
+    * continuous effects like rain and fire. All it really does is launch Particle objects out
+    * at set intervals, and fixes their positions and velocities accordingly.
+    *
+    * @method Phaser.GameObjectFactory#emitter
+    * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
+    * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
+    * @param {number} [maxParticles=50] - The total number of particles in this emitter.
+    * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object.
+    */
+    emitter: function (x, y, maxParticles) {
+
+        return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
+
+    },
+
+    /**
+    * Create a new RetroFont object.
+    *
+    * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
+    * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
+    * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
+    * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
+    * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
+    * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
+    *
+    * @method Phaser.GameObjectFactory#retroFont
+    * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
+    * @param {number} characterWidth - The width of each character in the font set.
+    * @param {number} characterHeight - The height of each character in the font set.
+    * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
+    * @param {number} charsPerRow - The number of characters per row in the font set.
+    * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
+    * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
+    * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
+    * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
+    * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
+    */
+    retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
+
+        return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
+
+    },
+
+    /**
+    * Create a new BitmapText object.
+    *
+    * BitmapText objects work by taking a texture file and an XML file that describes the font structure.
+    * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to 
+    * match the font structure.
+    * 
+    * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability 
+    * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by 
+    * processing the font texture in an image editor first, applying fills and any other effects required.
+    *
+    * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
+    *
+    * To create a BitmapText data files you can use:
+    *
+    * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
+    * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
+    * Littera (Web-based, free): http://kvazars.com/littera/
+    *
+    * @method Phaser.GameObjectFactory#bitmapText
+    * @param {number} x - X coordinate to display the BitmapText object at.
+    * @param {number} y - Y coordinate to display the BitmapText object at.
+    * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
+    * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
+    * @param {number} [size=32] - The size the font will be rendered at in pixels.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.BitmapText} The newly created bitmapText object.
+    */
+    bitmapText: function (x, y, font, text, size, group) {
+
+        if (group === undefined) { group = this.world; }
+
+        return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
+
+    },
+
+    /**
+    * Creates a new Phaser.Tilemap object.
+    *
+    * The map can either be populated with data from a Tiled JSON file or from a CSV file.
+    * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
+    * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
+    * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
+    * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
+    *
+    * @method Phaser.GameObjectFactory#tilemap
+    * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
+    * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+    * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+    * @return {Phaser.Tilemap} The newly created tilemap object.
+    */
+    tilemap: function (key, tileWidth, tileHeight, width, height) {
+
+        return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
+
+    },
+
+    /**
+    * A dynamic initially blank canvas to which images can be drawn.
+    *
+    * @method Phaser.GameObjectFactory#renderTexture
+    * @param {number} [width=100] - the width of the RenderTexture.
+    * @param {number} [height=100] - the height of the RenderTexture.
+    * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
+    * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
+    * @return {Phaser.RenderTexture} The newly created RenderTexture object.
+    */
+    renderTexture: function (width, height, key, addToCache) {
+
+        if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
+        if (addToCache === undefined) { addToCache = false; }
+
+        var texture = new Phaser.RenderTexture(this.game, width, height, key);
+
+        if (addToCache)
+        {
+            this.game.cache.addRenderTexture(key, texture);
+        }
+
+        return texture;
+
+    },
+
+    /**
+    * Create a Video object.
+    *
+    * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture.
+    *
+    * @method Phaser.GameObjectFactory#video
+    * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture.
+    * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null)
+    * @return {Phaser.Video} The newly created Video object.
+    */
+    video: function (key, url) {
+
+        return new Phaser.Video(this.game, key, url);
+
+    },
+
+    /**
+    * Create a BitmapData object.
+    *
+    * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
+    *
+    * @method Phaser.GameObjectFactory#bitmapData
+    * @param {number} [width=256] - The width of the BitmapData in pixels.
+    * @param {number} [height=256] - The height of the BitmapData in pixels.
+    * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
+    * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
+    * @return {Phaser.BitmapData} The newly created BitmapData object.
+    */
+    bitmapData: function (width, height, key, addToCache) {
+
+        if (addToCache === undefined) { addToCache = false; }
+        if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
+
+        var texture = new Phaser.BitmapData(this.game, key, width, height);
+
+        if (addToCache)
+        {
+            this.game.cache.addBitmapData(key, texture);
+        }
+
+        return texture;
+
+    },
+
+    /**
+    * A WebGL shader/filter that can be applied to Sprites.
+    *
+    * @method Phaser.GameObjectFactory#filter
+    * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
+    * @param {any} - Whatever parameters are needed to be passed to the filter init function.
+    * @return {Phaser.Filter} The newly created Phaser.Filter object.
+    */
+    filter: function (filter) {
+
+        var args = Array.prototype.splice.call(arguments, 1);
+
+        var filter = new Phaser.Filter[filter](this.game);
+
+        filter.init.apply(filter, args);
+
+        return filter;
+
+    },
+
+    /**
+    * Add a new Plugin into the PluginManager.
+    *
+    * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager.
+    *
+    * @method Phaser.GameObjectFactory#plugin
+    * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
+    * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method.
+    * @return {Phaser.Plugin} The Plugin that was added to the manager.
+    */
+    plugin: function (plugin) {
+
+        return this.game.plugins.add(plugin);
+
+    }
+
+};
+
+Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world.
+* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}.
+*
+* @class Phaser.GameObjectCreator
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.GameObjectCreator = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    * @protected
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.World} world - A reference to the game world.
+    * @protected
+    */
+    this.world = this.game.world;
+
+};
+
+Phaser.GameObjectCreator.prototype = {
+
+    /**
+    * Create a new Image object.
+    *
+    * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
+    * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
+    *
+    * @method Phaser.GameObjectCreator#image
+    * @param {number} x - X position of the image.
+    * @param {number} y - Y position of the image.
+    * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+    * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
+    * @returns {Phaser.Image} the newly created sprite object.
+    */
+    image: function (x, y, key, frame) {
+
+        return new Phaser.Image(this.game, x, y, key, frame);
+
+    },
+
+    /**
+    * Create a new Sprite with specific position and sprite sheet key.
+    *
+    * @method Phaser.GameObjectCreator#sprite
+    * @param {number} x - X position of the new sprite.
+    * @param {number} y - Y position of the new sprite.
+    * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+    * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
+    * @returns {Phaser.Sprite} the newly created sprite object.
+    */
+    sprite: function (x, y, key, frame) {
+
+        return new Phaser.Sprite(this.game, x, y, key, frame);
+
+    },
+
+    /**
+    * Create a tween object for a specific object.
+    *
+    * The object can be any JavaScript object or Phaser object such as Sprite.
+    *
+    * @method Phaser.GameObjectCreator#tween
+    * @param {object} obj - Object the tween will be run on.
+    * @return {Phaser.Tween} The Tween object.
+    */
+    tween: function (obj) {
+
+        return new Phaser.Tween(obj, this.game, this.game.tweens);
+
+    },
+
+    /**
+    * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
+    *
+    * @method Phaser.GameObjectCreator#group
+    * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
+    * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
+    * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
+    * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
+    * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
+    * @return {Phaser.Group} The newly created Group.
+    */
+    group: function (parent, name, addToStage, enableBody, physicsBodyType) {
+
+        return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
+
+    },
+
+    /**
+    * Create a new SpriteBatch.
+    *
+    * @method Phaser.GameObjectCreator#spriteBatch
+    * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
+    * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
+    * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
+    * @return {Phaser.SpriteBatch} The newly created group.
+    */
+    spriteBatch: function (parent, name, addToStage) {
+
+        if (name === undefined) { name = 'group'; }
+        if (addToStage === undefined) { addToStage = false; }
+
+        return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
+
+    },
+
+    /**
+    * Creates a new Sound object.
+    *
+    * @method Phaser.GameObjectCreator#audio
+    * @param {string} key - The Game.cache key of the sound that this object will use.
+    * @param {number} [volume=1] - The volume at which the sound will be played.
+    * @param {boolean} [loop=false] - Whether or not the sound will loop.
+    * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
+    * @return {Phaser.Sound} The newly created text object.
+    */
+    audio: function (key, volume, loop, connect) {
+
+        return this.game.sound.add(key, volume, loop, connect);
+
+    },
+
+    /**
+     * Creates a new AudioSprite object.
+     *
+     * @method Phaser.GameObjectCreator#audioSprite
+     * @param {string} key - The Game.cache key of the sound that this object will use.
+     * @return {Phaser.AudioSprite} The newly created AudioSprite object.
+     */
+    audioSprite: function (key) {
+
+        return this.game.sound.addSprite(key);
+
+    },
+
+    /**
+    * Creates a new Sound object.
+    *
+    * @method Phaser.GameObjectCreator#sound
+    * @param {string} key - The Game.cache key of the sound that this object will use.
+    * @param {number} [volume=1] - The volume at which the sound will be played.
+    * @param {boolean} [loop=false] - Whether or not the sound will loop.
+    * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
+    * @return {Phaser.Sound} The newly created text object.
+    */
+    sound: function (key, volume, loop, connect) {
+
+        return this.game.sound.add(key, volume, loop, connect);
+
+    },
+
+    /**
+    * Creates a new TileSprite object.
+    *
+    * @method Phaser.GameObjectCreator#tileSprite
+    * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
+    * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
+    * @param {number} width - The width of the TileSprite.
+    * @param {number} height - The height of the TileSprite.
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+    * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+    * @return {Phaser.TileSprite} The newly created tileSprite object.
+    */
+    tileSprite: function (x, y, width, height, key, frame) {
+
+        return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
+
+    },
+
+    /**
+    * Creates a new Rope object.
+    *
+    * @method Phaser.GameObjectCreator#rope
+    * @param {number} x - The x coordinate (in world space) to position the Rope at.
+    * @param {number} y - The y coordinate (in world space) to position the Rope at.
+    * @param {number} width - The width of the Rope.
+    * @param {number} height - The height of the Rope.
+    * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+    * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+    * @return {Phaser.Rope} The newly created rope object.
+    */
+    rope: function (x, y, key, frame, points) {
+
+        return new Phaser.Rope(this.game, x, y, key, frame, points);
+
+    },
+
+    /**
+    * Creates a new Text object.
+    *
+    * @method Phaser.GameObjectCreator#text
+    * @param {number} x - X position of the new text object.
+    * @param {number} y - Y position of the new text object.
+    * @param {string} text - The actual text that will be written.
+    * @param {object} style - The style object containing style attributes like font, font size , etc.
+    * @return {Phaser.Text} The newly created text object.
+    */
+    text: function (x, y, text, style) {
+
+        return new Phaser.Text(this.game, x, y, text, style);
+
+    },
+
+    /**
+    * Creates a new Button object.
+    *
+    * @method Phaser.GameObjectCreator#button
+    * @param {number} [x] X position of the new button object.
+    * @param {number} [y] Y position of the new button object.
+    * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
+    * @param {function} [callback] The function to call when this button is pressed
+    * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
+    * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
+    * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
+    * @return {Phaser.Button} The newly created button object.
+    */
+    button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
+
+        return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
+
+    },
+
+    /**
+    * Creates a new Graphics object.
+    *
+    * @method Phaser.GameObjectCreator#graphics
+    * @param {number} [x=0] - X position of the new graphics object.
+    * @param {number} [y=0] - Y position of the new graphics object.
+    * @return {Phaser.Graphics} The newly created graphics object.
+    */
+    graphics: function (x, y) {
+
+        return new Phaser.Graphics(this.game, x, y);
+
+    },
+
+    /**
+    * Creat a new Emitter.
+    *
+    * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
+    * continuous effects like rain and fire. All it really does is launch Particle objects out
+    * at set intervals, and fixes their positions and velocities accorindgly.
+    *
+    * @method Phaser.GameObjectCreator#emitter
+    * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
+    * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
+    * @param {number} [maxParticles=50] - The total number of particles in this emitter.
+    * @return {Phaser.Emitter} The newly created emitter object.
+    */
+    emitter: function (x, y, maxParticles) {
+
+        return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
+
+    },
+
+    /**
+    * Create a new RetroFont object.
+    *
+    * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
+    * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
+    * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
+    * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
+    * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
+    * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
+    *
+    * @method Phaser.GameObjectCreator#retroFont
+    * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
+    * @param {number} characterWidth - The width of each character in the font set.
+    * @param {number} characterHeight - The height of each character in the font set.
+    * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
+    * @param {number} charsPerRow - The number of characters per row in the font set.
+    * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
+    * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
+    * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
+    * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
+    * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
+    */
+    retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
+
+        return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
+
+    },
+
+    /**
+    * Create a new BitmapText object.
+    *
+    * BitmapText objects work by taking a texture file and an XML file that describes the font structure.
+    * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to 
+    * match the font structure.
+    * 
+    * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability 
+    * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by 
+    * processing the font texture in an image editor first, applying fills and any other effects required.
+    *
+    * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
+    *
+    * To create a BitmapText data files you can use:
+    *
+    * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
+    * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
+    * Littera (Web-based, free): http://kvazars.com/littera/
+    *
+    * @method Phaser.GameObjectCreator#bitmapText
+    * @param {number} x - X coordinate to display the BitmapText object at.
+    * @param {number} y - Y coordinate to display the BitmapText object at.
+    * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
+    * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
+    * @param {number} [size=32] - The size the font will be rendered at in pixels.
+    * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text.
+    * @return {Phaser.BitmapText} The newly created bitmapText object.
+    */
+    bitmapText: function (x, y, font, text, size, align) {
+
+        return new Phaser.BitmapText(this.game, x, y, font, text, size, align);
+
+    },
+
+    /**
+    * Creates a new Phaser.Tilemap object.
+    *
+    * The map can either be populated with data from a Tiled JSON file or from a CSV file.
+    * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
+    * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
+    * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
+    * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
+    *
+    * @method Phaser.GameObjectCreator#tilemap
+    * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
+    * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+    * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+    */
+    tilemap: function (key, tileWidth, tileHeight, width, height) {
+
+        return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
+
+    },
+
+    /**
+    * A dynamic initially blank canvas to which images can be drawn.
+    *
+    * @method Phaser.GameObjectCreator#renderTexture
+    * @param {number} [width=100] - the width of the RenderTexture.
+    * @param {number} [height=100] - the height of the RenderTexture.
+    * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
+    * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
+    * @return {Phaser.RenderTexture} The newly created RenderTexture object.
+    */
+    renderTexture: function (width, height, key, addToCache) {
+
+        if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
+        if (addToCache === undefined) { addToCache = false; }
+
+        var texture = new Phaser.RenderTexture(this.game, width, height, key);
+
+        if (addToCache)
+        {
+            this.game.cache.addRenderTexture(key, texture);
+        }
+
+        return texture;
+
+    },
+
+    /**
+    * Create a BitmpaData object.
+    *
+    * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
+    *
+    * @method Phaser.GameObjectCreator#bitmapData
+    * @param {number} [width=256] - The width of the BitmapData in pixels.
+    * @param {number} [height=256] - The height of the BitmapData in pixels.
+    * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
+    * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
+    * @return {Phaser.BitmapData} The newly created BitmapData object.
+    */
+    bitmapData: function (width, height, key, addToCache) {
+
+        if (addToCache === undefined) { addToCache = false; }
+        if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
+
+        var texture = new Phaser.BitmapData(this.game, key, width, height);
+
+        if (addToCache)
+        {
+            this.game.cache.addBitmapData(key, texture);
+        }
+
+        return texture;
+
+    },
+
+    /**
+    * A WebGL shader/filter that can be applied to Sprites.
+    *
+    * @method Phaser.GameObjectCreator#filter
+    * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
+    * @param {any} - Whatever parameters are needed to be passed to the filter init function.
+    * @return {Phaser.Filter} The newly created Phaser.Filter object.
+    */
+    filter: function (filter) {
+
+        var args = Array.prototype.splice.call(arguments, 1);
+
+        var filter = new Phaser.Filter[filter](this.game);
+
+        filter.init.apply(filter, args);
+
+        return filter;
+
+    }
+
+};
+
+Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Sprites are the lifeblood of your game, used for nearly everything visual.
+*
+* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
+* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
+* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
+*
+* @class Phaser.Sprite
+* @constructor
+* @extends PIXI.Sprite
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.Animation
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.BringToTop
+* @extends Phaser.Component.Crop
+* @extends Phaser.Component.Delta
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.Health
+* @extends Phaser.Component.InCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.LoadTexture
+* @extends Phaser.Component.Overlap
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @extends Phaser.Component.ScaleMinMax
+* @extends Phaser.Component.Smoothed
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - The x coordinate (in world space) to position the Sprite at.
+* @param {number} y - The y coordinate (in world space) to position the Sprite at.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+*/
+Phaser.Sprite = function (game, x, y, key, frame) {
+
+    x = x || 0;
+    y = y || 0;
+    key = key || null;
+    frame = frame || null;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.SPRITE;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
+
+    Phaser.Component.Core.init.call(this, game, x, y, key, frame);
+
+};
+
+Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype);
+Phaser.Sprite.prototype.constructor = Phaser.Sprite;
+
+Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [
+    'Angle',
+    'Animation',
+    'AutoCull',
+    'Bounds',
+    'BringToTop',
+    'Crop',
+    'Delta',
+    'Destroy',
+    'FixedToCamera',
+    'Health',
+    'InCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'LoadTexture',
+    'Overlap',
+    'PhysicsBody',
+    'Reset',
+    'ScaleMinMax',
+    'Smoothed'
+]);
+
+Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method
+* @memberof Phaser.Sprite
+* @return {boolean} True if the Sprite was rendered, otherwise false.
+*/
+Phaser.Sprite.prototype.preUpdate = function() {
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
+* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
+*
+* @class Phaser.Image
+* @extends PIXI.Sprite
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.Animation
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.BringToTop
+* @extends Phaser.Component.Crop
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.LoadTexture
+* @extends Phaser.Component.Overlap
+* @extends Phaser.Component.Reset
+* @extends Phaser.Component.Smoothed
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
+* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
+* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+*/
+Phaser.Image = function (game, x, y, key, frame) {
+
+    x = x || 0;
+    y = y || 0;
+    key = key || null;
+    frame = frame || null;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.IMAGE;
+
+    PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
+
+    Phaser.Component.Core.init.call(this, game, x, y, key, frame);
+
+};
+
+Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
+Phaser.Image.prototype.constructor = Phaser.Image;
+
+Phaser.Component.Core.install.call(Phaser.Image.prototype, [
+    'Angle',
+    'Animation',
+    'AutoCull',
+    'Bounds',
+    'BringToTop',
+    'Crop',
+    'Destroy',
+    'FixedToCamera',
+    'InputEnabled',
+    'LifeSpan',
+    'LoadTexture',
+    'Overlap',
+    'Reset',
+    'Smoothed'
+]);
+
+Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method Phaser.Image#preUpdate
+* @memberof Phaser.Image
+*/
+Phaser.Image.prototype.preUpdate = function() {
+
+    if (!this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself.
+* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source.
+* 
+* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites.
+*
+* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background
+* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition`
+* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will 
+* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to
+* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs.
+*
+* An important note about texture dimensions:
+*
+* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be
+* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etch pixels width by height). If the texture isn't a power of two
+* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and
+* bottom of your frame. To avoid this ensure your textures are perfect powers of two.
+* 
+* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However
+* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive
+* additional padding to enforce it to be so.
+*
+* @class Phaser.TileSprite
+* @constructor
+* @extends PIXI.TilingSprite
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.Animation
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.BringToTop
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.Health
+* @extends Phaser.Component.InCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.LoadTexture
+* @extends Phaser.Component.Overlap
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @extends Phaser.Component.Smoothed
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
+* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
+* @param {number} width - The width of the TileSprite.
+* @param {number} height - The height of the TileSprite.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a RenderTexture, PIXI.Texture or BitmapData.
+* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+*/
+Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
+
+    x = x || 0;
+    y = y || 0;
+    width = width || 256;
+    height = height || 256;
+    key = key || null;
+    frame = frame || null;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.TILESPRITE;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    /**
+    * @property {Phaser.Point} _scroll - Internal cache var.
+    * @private
+    */
+    this._scroll = new Phaser.Point();
+
+    var def = game.cache.getImage('__default', true);
+
+    PIXI.TilingSprite.call(this, new PIXI.Texture(def.base), width, height);
+
+    Phaser.Component.Core.init.call(this, game, x, y, key, frame);
+
+};
+
+Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
+Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
+
+Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [
+    'Angle',
+    'Animation',
+    'AutoCull',
+    'Bounds',
+    'BringToTop',
+    'Destroy',
+    'FixedToCamera',
+    'Health',
+    'InCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'LoadTexture',
+    'Overlap',
+    'PhysicsBody',
+    'Reset',
+    'Smoothed'
+]);
+
+Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method Phaser.TileSprite#preUpdate
+* @memberof Phaser.TileSprite
+*/
+Phaser.TileSprite.prototype.preUpdate = function() {
+
+    if (this._scroll.x !== 0)
+    {
+        this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
+    }
+
+    if (this._scroll.y !== 0)
+    {
+        this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
+    }
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
+* The scroll speed is specified in pixels per second.
+* A negative x value will scroll to the left. A positive x value will scroll to the right.
+* A negative y value will scroll up. A positive y value will scroll down.
+*
+* @method Phaser.TileSprite#autoScroll
+* @memberof Phaser.TileSprite
+* @param {number} x - Horizontal scroll speed in pixels per second.
+* @param {number} y - Vertical scroll speed in pixels per second.
+*/
+Phaser.TileSprite.prototype.autoScroll = function(x, y) {
+
+    this._scroll.set(x, y);
+
+};
+
+/**
+* Stops an automatically scrolling TileSprite.
+*
+* @method Phaser.TileSprite#stopScroll
+* @memberof Phaser.TileSprite
+*/
+Phaser.TileSprite.prototype.stopScroll = function() {
+
+    this._scroll.set(0, 0);
+
+};
+
+/**
+* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
+* and nulls its reference to game, freeing it up for garbage collection.
+*
+* @method Phaser.TileSprite#destroy
+* @memberof Phaser.TileSprite
+* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
+*/
+Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
+
+    Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
+
+    PIXI.TilingSprite.prototype.destroy.call(this);
+
+};
+
+/**
+* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
+* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
+* If the TileSprite has a physics body that too is reset.
+*
+* @method Phaser.TileSprite#reset
+* @memberof Phaser.TileSprite
+* @param {number} x - The x coordinate (in world space) to position the Sprite at.
+* @param {number} y - The y coordinate (in world space) to position the Sprite at.
+* @return (Phaser.TileSprite) This instance.
+*/
+Phaser.TileSprite.prototype.reset = function(x, y) {
+
+    Phaser.Component.Reset.prototype.reset.call(this, x, y);
+
+    this.tilePosition.x = 0;
+    this.tilePosition.y = 0;
+
+    return this;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd, Richard Davey
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Rope is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
+* Please note that Ropes, as with normal Sprites, have no input handler or physics bodies by default. Both need enabling.
+* Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js
+*
+* @class Phaser.Rope
+* @constructor
+* @extends PIXI.Rope
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.Animation
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.BringToTop
+* @extends Phaser.Component.Crop
+* @extends Phaser.Component.Delta
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.LoadTexture
+* @extends Phaser.Component.Overlap
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @extends Phaser.Component.ScaleMinMax
+* @extends Phaser.Component.Smoothed
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - The x coordinate (in world space) to position the Rope at.
+* @param {number} y - The y coordinate (in world space) to position the Rope at.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+* @param {Array} points - An array of {Phaser.Point}.
+*/
+Phaser.Rope = function (game, x, y, key, frame, points) {
+
+    this.points = [];
+    this.points = points;
+    this._hasUpdateAnimation = false;
+    this._updateAnimationCallback = null;
+    x = x || 0;
+    y = y || 0;
+    key = key || null;
+    frame = frame || null;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.ROPE;
+
+    /**
+    * @property {Phaser.Point} _scroll - Internal cache var.
+    * @private
+    */
+    this._scroll = new Phaser.Point();
+
+    PIXI.Rope.call(this, PIXI.TextureCache['__default'], this.points);
+
+    Phaser.Component.Core.init.call(this, game, x, y, key, frame);
+
+};
+
+Phaser.Rope.prototype = Object.create(PIXI.Rope.prototype);
+Phaser.Rope.prototype.constructor = Phaser.Rope;
+
+Phaser.Component.Core.install.call(Phaser.Rope.prototype, [
+    'Angle',
+    'Animation',
+    'AutoCull',
+    'Bounds',
+    'BringToTop',
+    'Crop',
+    'Delta',
+    'Destroy',
+    'FixedToCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'LoadTexture',
+    'Overlap',
+    'PhysicsBody',
+    'Reset',
+    'ScaleMinMax',
+    'Smoothed'
+]);
+
+Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method Phaser.Rope#preUpdate
+* @memberof Phaser.Rope
+*/
+Phaser.Rope.prototype.preUpdate = function() {
+
+    if (this._scroll.x !== 0)
+    {
+        this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
+    }
+
+    if (this._scroll.y !== 0)
+    {
+        this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
+    }
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Override and use this function in your own custom objects to handle any update requirements you may have.
+*
+* @method Phaser.Rope#update
+* @memberof Phaser.Rope
+*/
+Phaser.Rope.prototype.update = function() {
+
+    if (this._hasUpdateAnimation)
+    {
+        this.updateAnimation.call(this);
+    }
+
+};
+
+/**
+* Resets the Rope. This places the Rope at the given x/y world coordinates, resets the tilePosition and then
+* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
+* If the Rope has a physics body that too is reset.
+*
+* @method Phaser.Rope#reset
+* @memberof Phaser.Rope
+* @param {number} x - The x coordinate (in world space) to position the Sprite at.
+* @param {number} y - The y coordinate (in world space) to position the Sprite at.
+* @return (Phaser.Rope) This instance.
+*/
+Phaser.Rope.prototype.reset = function(x, y) {
+
+    Phaser.Component.Reset.prototype.reset.call(this, x, y);
+
+    this.tilePosition.x = 0;
+    this.tilePosition.y = 0;
+
+    return this;
+
+};
+
+/**
+* A Rope will call it's updateAnimation function on each update loop if it has one
+*
+* @name Phaser.Rope#updateAnimation
+* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it.
+*/
+Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", {
+
+    get: function () {
+
+        return this._updateAnimation;
+
+    },
+
+    set: function (value) {
+
+        if (value && typeof value === 'function')
+        {
+            this._hasUpdateAnimation = true;
+            this._updateAnimation = value;
+        }
+        else
+        {
+            this._hasUpdateAnimation = false;
+            this._updateAnimation = null;
+        }
+
+    }
+
+});
+
+/**
+* The segments that make up the rope body as an array of Phaser.Rectangles
+*
+* @name Phaser.Rope#segments
+* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope
+*/
+Object.defineProperty(Phaser.Rope.prototype, "segments", {
+
+    get: function() {
+
+        var segments = [];
+        var index, x1, y1, x2, y2, width, height, rect;
+
+        for (var i = 0; i < this.points.length; i++)
+        {
+            index = i * 4;
+
+            x1 = this.vertices[index] * this.scale.x;
+            y1 = this.vertices[index + 1] * this.scale.y;
+            x2 = this.vertices[index + 4] * this.scale.x;
+            y2 = this.vertices[index + 3] * this.scale.y;
+
+            width = Phaser.Math.difference(x1, x2);
+            height = Phaser.Math.difference(y1, y2);
+
+            x1 += this.world.x;
+            y1 += this.world.y;
+            rect = new Phaser.Rectangle(x1, y1, width, height);
+            segments.push(rect);
+        }
+
+        return segments;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically.
+*
+* The four states a Button responds to are:
+*
+* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
+* * 'Out' - when the Pointer that was previously over the Button moves out of it.
+* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
+* * 'Up' - when the Pointer that was pressed down on the Button is released again.
+*
+* A different texture/frame and activation sound can be specified for any of the states.
+*
+* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor.
+*
+* @class Phaser.Button
+* @constructor
+* @extends Phaser.Image
+* @param {Phaser.Game} game Current game instance.
+* @param {number} [x=0] - X position of the Button.
+* @param {number} [y=0] - Y position of the Button.
+* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button.
+* @param {function} [callback] - The function to call when this Button is pressed.
+* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
+* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state.
+* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state.
+* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state.
+* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state.
+*/
+Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
+
+    x = x || 0;
+    y = y || 0;
+    key = key || null;
+    callback = callback || null;
+    callbackContext = callbackContext || this;
+
+    Phaser.Image.call(this, game, x, y, key, outFrame);
+
+    /**
+    * The Phaser Object Type.
+    * @property {number} type
+    * @readonly
+    */
+    this.type = Phaser.BUTTON;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    /**
+    * The name or ID of the Over state frame.
+    * @property {string|integer} onOverFrame
+    * @private
+    */
+    this._onOverFrame = null;
+
+    /**
+    * The name or ID of the Out state frame.
+    * @property {string|integer} onOutFrame
+    * @private
+    */
+    this._onOutFrame = null;
+
+    /**
+    * The name or ID of the Down state frame.
+    * @property {string|integer} onDownFrame
+    * @private
+    */
+    this._onDownFrame = null;
+
+    /**
+    * The name or ID of the Up state frame.
+    * @property {string|integer} onUpFrame
+    * @private
+    */
+    this._onUpFrame = null;
+
+    /**
+    * The Sound to be played when this Buttons Over state is activated.
+    * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound
+    * @readonly
+    */
+    this.onOverSound = null;
+
+    /**
+    * The Sound to be played when this Buttons Out state is activated.
+    * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound
+    * @readonly
+    */
+    this.onOutSound = null;
+
+    /**
+    * The Sound to be played when this Buttons Down state is activated.
+    * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound
+    * @readonly
+    */
+    this.onDownSound = null;
+
+    /**
+    * The Sound to be played when this Buttons Up state is activated.
+    * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound
+    * @readonly
+    */
+    this.onUpSound = null;
+
+    /**
+    * The Sound Marker used in conjunction with the onOverSound.
+    * @property {string} onOverSoundMarker
+    * @readonly
+    */
+    this.onOverSoundMarker = '';
+
+    /**
+    * The Sound Marker used in conjunction with the onOutSound.
+    * @property {string} onOutSoundMarker
+    * @readonly
+    */
+    this.onOutSoundMarker = '';
+
+    /**
+    * The Sound Marker used in conjunction with the onDownSound.
+    * @property {string} onDownSoundMarker
+    * @readonly
+    */
+    this.onDownSoundMarker = '';
+
+    /**
+    * The Sound Marker used in conjunction with the onUpSound.
+    * @property {string} onUpSoundMarker
+    * @readonly
+    */
+    this.onUpSoundMarker = '';
+
+    /**
+    * The Signal (or event) dispatched when this Button is in an Over state.
+    * @property {Phaser.Signal} onInputOver
+    */
+    this.onInputOver = new Phaser.Signal();
+
+    /**
+    * The Signal (or event) dispatched when this Button is in an Out state.
+    * @property {Phaser.Signal} onInputOut
+    */
+    this.onInputOut = new Phaser.Signal();
+
+    /**
+    * The Signal (or event) dispatched when this Button is in an Down state.
+    * @property {Phaser.Signal} onInputDown
+    */
+    this.onInputDown = new Phaser.Signal();
+
+    /**
+    * The Signal (or event) dispatched when this Button is in an Up state.
+    * @property {Phaser.Signal} onInputUp
+    */
+    this.onInputUp = new Phaser.Signal();
+
+    /**
+    * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer.
+    * The frame will still be changed as applicable.
+    * @property {boolean} onOverMouseOnly
+    * @default
+    */
+    this.onOverMouseOnly = false;
+    
+    /**
+    * When true the the texture frame will not be automatically switched on up/down/over/out events.
+    * @property {boolean} freezeFrames
+    * @default
+    */
+    this.freezeFrames = false;
+
+    /**
+    * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up".
+    * @property {boolean} forceOut
+    * @default
+    */
+    this.forceOut = false;
+
+    this.inputEnabled = true;
+
+    this.input.start(0, true);
+
+    this.input.useHandCursor = true;
+
+    this.setFrames(overFrame, outFrame, downFrame, upFrame);
+
+    if (callback !== null)
+    {
+        this.onInputUp.add(callback, callbackContext);
+    }
+
+    //  Redirect the input events to here so we can handle animation updates, etc
+    this.events.onInputOver.add(this.onInputOverHandler, this);
+    this.events.onInputOut.add(this.onInputOutHandler, this);
+    this.events.onInputDown.add(this.onInputDownHandler, this);
+    this.events.onInputUp.add(this.onInputUpHandler, this);
+
+    this.events.onRemovedFromWorld.add(this.removedFromWorld, this);
+
+};
+
+Phaser.Button.prototype = Object.create(Phaser.Image.prototype);
+Phaser.Button.prototype.constructor = Phaser.Button;
+
+//  State constants; local only. These are tied to property names in Phaser.Button.
+var STATE_OVER = 'Over';
+var STATE_OUT = 'Out';
+var STATE_DOWN = 'Down';
+var STATE_UP = 'Up';
+
+/**
+* Clears all of the frames set on this Button.
+*
+* @method Phaser.Button#clearFrames
+*/
+Phaser.Button.prototype.clearFrames = function () {
+
+    this.setFrames(null, null, null, null);
+
+};
+
+/**
+* Called when this Button is removed from the World.
+*
+* @method Phaser.Button#removedFromWorld
+* @protected
+*/
+Phaser.Button.prototype.removedFromWorld = function () {
+
+    this.inputEnabled = false;
+
+};
+
+/**
+* Set the frame name/ID for the given state.
+*
+* @method Phaser.Button#setStateFrame
+* @private
+* @param {object} state - See `STATE_*`
+* @param {number|string} frame - The number or string representing the frame.
+* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true.
+*/
+Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately)
+{
+    var frameKey = '_on' + state + 'Frame';
+
+    if (frame !== null) // not null or undefined
+    {
+        this[frameKey] = frame;
+
+        if (switchImmediately)
+        {
+            this.changeStateFrame(state);
+        }
+    }
+    else
+    {
+        this[frameKey] = null;
+    }
+
+};
+
+/**
+* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen".
+*
+* @method Phaser.Button#changeStateFrame
+* @private
+* @param {object} state - See `STATE_*`
+* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had.
+*/
+Phaser.Button.prototype.changeStateFrame = function (state) {
+
+    if (this.freezeFrames)
+    {
+        return false;
+    }
+
+    var frameKey = '_on' + state + 'Frame';
+    var frame = this[frameKey];
+
+    if (typeof frame === 'string')
+    {
+        this.frameName = frame;
+        return true;
+    }
+    else if (typeof frame === 'number')
+    {
+        this.frame = frame;
+        return true;
+    }
+    else
+    {
+        return false;
+    }
+
+};
+
+/**
+* Used to manually set the frames that will be used for the different states of the Button.
+*
+* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor.
+*
+* @method Phaser.Button#setFrames
+* @public
+* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state.
+* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state.
+* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state.
+* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state.
+*/
+Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) {
+
+    this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver());
+    this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver());
+    this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown());
+    this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp());
+
+};
+
+/**
+* Set the sound/marker for the given state.
+*
+* @method Phaser.Button#setStateSound
+* @private
+* @param {object} state - See `STATE_*`
+* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound.
+* @param {string} [marker=''] - Sound marker.
+*/
+Phaser.Button.prototype.setStateSound = function (state, sound, marker) {
+
+    var soundKey = 'on' + state + 'Sound';
+    var markerKey = 'on' + state + 'SoundMarker';
+
+    if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite)
+    {
+        this[soundKey] = sound;
+        this[markerKey] = typeof marker === 'string' ? marker : '';
+    }
+    else
+    {
+        this[soundKey] = null;
+        this[markerKey] = '';
+    }
+
+};
+
+/**
+* Play the sound for the given state, _if_ the state has a sound assigned.
+*
+* @method Phaser.Button#playStateSound
+* @private
+* @param {object} state - See `STATE_*`
+* @return {boolean} True only if a sound was played.
+*/
+Phaser.Button.prototype.playStateSound = function (state) {
+
+    var soundKey = 'on' + state + 'Sound';
+    var sound = this[soundKey];
+
+    if (sound)
+    {
+        var markerKey = 'on' + state + 'SoundMarker';
+        var marker = this[markerKey];
+
+        sound.play(marker);
+        return true;
+    }
+    else
+    {
+        return false;
+    }
+
+};
+
+/**
+* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object.
+* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
+*
+* Call this function with no parameters to reset all sounds on this Button.
+*
+* @method Phaser.Button#setSounds
+* @public
+* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound.
+* @param {string} [overMarker] - Over Button Sound Marker.
+* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound.
+* @param {string} [downMarker] - Down Button Sound Marker.
+* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound.
+* @param {string} [outMarker] - Out Button Sound Marker.
+* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound.
+* @param {string} [upMarker] - Up Button Sound Marker.
+*/
+Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
+
+    this.setStateSound(STATE_OVER, overSound, overMarker);
+    this.setStateSound(STATE_OUT, outSound, outMarker);
+    this.setStateSound(STATE_DOWN, downSound, downMarker);
+    this.setStateSound(STATE_UP, upSound, upMarker);
+
+};
+
+/**
+* The Sound to be played when a Pointer moves over this Button.
+*
+* @method Phaser.Button#setOverSound
+* @public
+* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
+* @param {string} [marker] - A Sound Marker that will be used in the playback.
+*/
+Phaser.Button.prototype.setOverSound = function (sound, marker) {
+
+    this.setStateSound(STATE_OVER, sound, marker);
+
+};
+
+/**
+* The Sound to be played when a Pointer moves out of this Button.
+*
+* @method Phaser.Button#setOutSound
+* @public
+* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
+* @param {string} [marker] - A Sound Marker that will be used in the playback.
+*/
+Phaser.Button.prototype.setOutSound = function (sound, marker) {
+
+    this.setStateSound(STATE_OUT, sound, marker);
+
+};
+
+/**
+* The Sound to be played when a Pointer presses down on this Button.
+*
+* @method Phaser.Button#setDownSound
+* @public
+* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
+* @param {string} [marker] - A Sound Marker that will be used in the playback.
+*/
+Phaser.Button.prototype.setDownSound = function (sound, marker) {
+
+    this.setStateSound(STATE_DOWN, sound, marker);
+
+};
+
+/**
+* The Sound to be played when a Pointer has pressed down and is released from this Button.
+*
+* @method Phaser.Button#setUpSound
+* @public
+* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
+* @param {string} [marker] - A Sound Marker that will be used in the playback.
+*/
+Phaser.Button.prototype.setUpSound = function (sound, marker) {
+
+    this.setStateSound(STATE_UP, sound, marker);
+
+};
+
+/**
+* Internal function that handles input events.
+*
+* @method Phaser.Button#onInputOverHandler
+* @protected
+* @param {Phaser.Button} sprite - The Button that the event occurred on.
+* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
+*/
+Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) {
+
+    //  If the Pointer was only just released then we don't fire an over event
+    if (pointer.justReleased())
+    {
+        return;
+    }
+
+    this.changeStateFrame(STATE_OVER);
+
+    if (this.onOverMouseOnly && !pointer.isMouse)
+    {
+        return;
+    }
+
+    this.playStateSound(STATE_OVER);
+
+    if (this.onInputOver)
+    {
+        this.onInputOver.dispatch(this, pointer);
+    }
+
+};
+
+/**
+* Internal function that handles input events.
+*
+* @method Phaser.Button#onInputOutHandler
+* @protected
+* @param {Phaser.Button} sprite - The Button that the event occurred on.
+* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
+*/
+Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) {
+
+    this.changeStateFrame(STATE_OUT);
+
+    this.playStateSound(STATE_OUT);
+
+    if (this.onInputOut)
+    {
+        this.onInputOut.dispatch(this, pointer);
+    }
+};
+
+/**
+* Internal function that handles input events.
+*
+* @method Phaser.Button#onInputDownHandler
+* @protected
+* @param {Phaser.Button} sprite - The Button that the event occurred on.
+* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
+*/
+Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) {
+
+    this.changeStateFrame(STATE_DOWN);
+
+    this.playStateSound(STATE_DOWN);
+
+    if (this.onInputDown)
+    {
+        this.onInputDown.dispatch(this, pointer);
+    }
+};
+
+/**
+* Internal function that handles input events.
+*
+* @method Phaser.Button#onInputUpHandler
+* @protected
+* @param {Phaser.Button} sprite - The Button that the event occurred on.
+* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
+*/
+Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) {
+
+    this.playStateSound(STATE_UP);
+
+    //  Input dispatched early, before state change (but after sound)
+    if (this.onInputUp)
+    {
+        this.onInputUp.dispatch(this, pointer, isOver);
+    }
+
+    if (this.freezeFrames)
+    {
+        return;
+    }
+
+    if (this.forceOut)
+    {
+        this.changeStateFrame(STATE_OUT);
+    }
+    else
+    {
+        var changedUp = this.changeStateFrame(STATE_UP);
+        if (!changedUp)
+        {
+            //  No Up frame to show..
+            if (isOver)
+            {
+                this.changeStateFrame(STATE_OVER);
+            }
+            else
+            {
+                this.changeStateFrame(STATE_OUT);
+            }
+        }
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles.
+* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over
+* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled
+* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices.
+*
+* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds.
+*
+* @class Phaser.SpriteBatch
+* @extends Phaser.Group
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world.
+* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
+* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
+*/
+Phaser.SpriteBatch = function (game, parent, name, addToStage) {
+
+    if (parent === undefined || parent === null) { parent = game.world; }
+
+    PIXI.SpriteBatch.call(this);
+
+    Phaser.Group.call(this, game, parent, name, addToStage);
+
+    /**
+    * @property {number} type - Internal Phaser Type value.
+    * @protected
+    */
+    this.type = Phaser.SPRITEBATCH;
+
+};
+
+Phaser.SpriteBatch.prototype = Phaser.Utils.extend(true, Phaser.SpriteBatch.prototype, Phaser.Group.prototype, PIXI.SpriteBatch.prototype);
+
+Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter.
+* 
+* @class Phaser.Particle
+* @constructor
+* @extends Phaser.Sprite
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - The x coordinate (in world space) to position the Particle at.
+* @param {number} y - The y coordinate (in world space) to position the Particle at.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+*/
+Phaser.Particle = function (game, x, y, key, frame) {
+
+    Phaser.Sprite.call(this, game, x, y, key, frame);
+
+    /**
+    * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData.
+    * @protected
+    */
+    this.autoScale = false;
+
+    /**
+    * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle.
+    * @protected
+    */
+    this.scaleData = null;
+
+    /**
+    * @property {number} _s - Internal cache var for tracking auto scale.
+    * @private
+    */
+    this._s = 0;
+
+    /**
+    * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData.
+    * @protected
+    */
+    this.autoAlpha = false;
+
+    /**
+    * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle.
+    * @protected
+    */
+    this.alphaData = null;
+
+    /**
+    * @property {number} _a - Internal cache var for tracking auto alpha.
+    * @private
+    */
+    this._a = 0;
+
+};
+
+Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype);
+Phaser.Particle.prototype.constructor = Phaser.Particle;
+
+/**
+* Updates the Particle scale or alpha if autoScale and autoAlpha are set.
+*
+* @method Phaser.Particle#update
+* @memberof Phaser.Particle
+*/
+Phaser.Particle.prototype.update = function() {
+
+    if (this.autoScale)
+    {
+        this._s--;
+
+        if (this._s)
+        {
+            this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
+        }
+        else
+        {
+            this.autoScale = false;
+        }
+    }
+
+    if (this.autoAlpha)
+    {
+        this._a--;
+
+        if (this._a)
+        {
+            this.alpha = this.alphaData[this._a].v;
+        }
+        else
+        {
+            this.autoAlpha = false;
+        }
+    }
+
+};
+
+/**
+* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required.
+*
+* @method Phaser.Particle#onEmit
+* @memberof Phaser.Particle
+*/
+Phaser.Particle.prototype.onEmit = function() {
+};
+
+/**
+* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter.
+*
+* @method Phaser.Particle#setAlphaData
+* @memberof Phaser.Particle
+*/
+Phaser.Particle.prototype.setAlphaData = function(data) {
+
+    this.alphaData = data;
+    this._a = data.length - 1;
+    this.alpha = this.alphaData[this._a].v;
+    this.autoAlpha = true;
+
+};
+
+/**
+* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter.
+*
+* @method Phaser.Particle#setScaleData
+* @memberof Phaser.Particle
+*/
+Phaser.Particle.prototype.setScaleData = function(data) {
+
+    this.scaleData = data;
+    this._s = data.length - 1;
+    this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
+    this.autoScale = true;
+
+};
+
+/**
+* Resets the Particle. This places the Particle at the given x/y world coordinates and then
+* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
+* If the Particle has a physics body that too is reset.
+*
+* @method Phaser.Particle#reset
+* @memberof Phaser.Particle
+* @param {number} x - The x coordinate (in world space) to position the Particle at.
+* @param {number} y - The y coordinate (in world space) to position the Particle at.
+* @param {number} [health=1] - The health to give the Particle.
+* @return (Phaser.Particle) This instance.
+*/
+Phaser.Particle.prototype.reset = function(x, y, health) {
+
+    Phaser.Component.Reset.prototype.reset.call(this, x, y, health);
+
+    this.alpha = 1;
+    this.scale.set(1);
+
+    this.autoScale = false;
+    this.autoAlpha = false;
+
+    return this;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
+* A single BitmapData can be used as the texture for one or many Images/Sprites. 
+* So if you need to dynamically create a Sprite texture then they are a good choice.
+*
+* @class Phaser.BitmapData
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {string} key - Internal Phaser reference key for the BitmapData.
+* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value.
+* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value.
+*/
+Phaser.BitmapData = function (game, key, width, height) {
+
+    if (width === undefined || width === 0) { width = 256; }
+    if (height === undefined || height === 0) { height = 256; }
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {string} key - The key of the BitmapData in the Cache, if stored there.
+    */
+    this.key = key;
+
+    /**
+    * @property {number} width - The width of the BitmapData in pixels.
+    */
+    this.width = width;
+
+    /**
+    * @property {number} height - The height of the BitmapData in pixels.
+    */
+    this.height = height;
+
+    /**
+    * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
+    * @default
+    */
+    this.canvas = Phaser.Canvas.create(width, height, '', true);
+
+    /**
+    * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
+    * @default
+    */
+    this.context = this.canvas.getContext('2d', { alpha: true });
+
+    /**
+    * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context.
+    */
+    this.ctx = this.context;
+
+    /**
+    * @property {ImageData} imageData - The context image data.
+    */
+    this.imageData = this.context.getImageData(0, 0, width, height);
+
+    /**
+    * A Uint8ClampedArray view into BitmapData.buffer.
+    * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions)
+    * @property {Uint8ClampedArray} data
+    */
+    this.data = null;
+
+    if (this.imageData)
+    {
+        this.data = this.imageData.data;
+    }
+
+    /**
+    * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer.
+    */
+    this.pixels = null;
+
+    /**
+    * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData.
+    */
+    if (this.data)
+    {
+        if (this.imageData.data.buffer)
+        {
+            this.buffer = this.imageData.data.buffer;
+            this.pixels = new Uint32Array(this.buffer);
+        }
+        else
+        {
+            if (window['ArrayBuffer'])
+            {
+                this.buffer = new ArrayBuffer(this.imageData.data.length);
+                this.pixels = new Uint32Array(this.buffer);
+            }
+            else
+            {
+                this.pixels = this.imageData.data;
+            }
+        }
+    }
+
+    /**
+    * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
+    * @default
+    */
+    this.baseTexture = new PIXI.BaseTexture(this.canvas);
+
+    /**
+    * @property {PIXI.Texture} texture - The PIXI.Texture.
+    * @default
+    */
+    this.texture = new PIXI.Texture(this.baseTexture);
+
+    /**
+    * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
+    * @default
+    */
+    this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'bitmapData');
+
+    this.texture.frame = this.textureFrame;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @default
+    */
+    this.type = Phaser.BITMAPDATA;
+
+    /**
+    * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true.
+    */
+    this.disableTextureUpload = false;
+
+    /**
+    * @property {boolean} dirty - If dirty this BitmapData will be re-rendered.
+    */
+    this.dirty = false;
+
+    //  Aliases
+    this.cls = this.clear;
+
+    /**
+    * @property {number} _image - Internal cache var.
+    * @private
+    */
+    this._image = null;
+
+    /**
+    * @property {Phaser.Point} _pos - Internal cache var.
+    * @private
+    */
+    this._pos = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} _size - Internal cache var.
+    * @private
+    */
+    this._size = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} _scale - Internal cache var.
+    * @private
+    */
+    this._scale = new Phaser.Point();
+
+    /**
+    * @property {number} _rotate - Internal cache var.
+    * @private
+    */
+    this._rotate = 0;
+
+    /**
+    * @property {object} _alpha - Internal cache var.
+    * @private
+    */
+    this._alpha = { prev: 1, current: 1 };
+
+    /**
+    * @property {Phaser.Point} _anchor - Internal cache var.
+    * @private
+    */
+    this._anchor = new Phaser.Point();
+
+    /**
+    * @property {number} _tempR - Internal cache var.
+    * @private
+    */
+    this._tempR = 0;
+
+    /**
+    * @property {number} _tempG - Internal cache var.
+    * @private
+    */
+    this._tempG = 0;
+
+    /**
+    * @property {number} _tempB - Internal cache var.
+    * @private
+    */
+    this._tempB = 0;
+
+    /**
+    * @property {Phaser.Circle} _circle - Internal cache var.
+    * @private
+    */
+    this._circle = new Phaser.Circle();
+
+    /**
+    * @property {HTMLCanvasElement} _swapCanvas - A swap canvas.
+    * @private
+    */
+    this._swapCanvas = Phaser.Canvas.create(width, height, '', true);
+
+};
+
+Phaser.BitmapData.prototype = {
+
+    /**
+    * Shifts the contents of this BitmapData by the distances given.
+    * 
+    * The image will wrap-around the edges on all sides.
+    *
+    * @method Phaser.BitmapData#move
+    * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right.
+    * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    move: function (x, y) {
+
+        if (x !== 0)
+        {
+            this.moveH(x);
+        }
+
+        if (y !== 0)
+        {
+            this.moveV(y);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Shifts the contents of this BitmapData horizontally.
+    * 
+    * The image will wrap-around the sides.
+    *
+    * @method Phaser.BitmapData#moveH
+    * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    moveH: function (distance) {
+
+        var c = this._swapCanvas;
+        var ctx = c.getContext('2d');
+        var h = this.height;
+        var src = this.canvas;
+
+        ctx.clearRect(0, 0, this.width, this.height);
+
+        if (distance < 0)
+        {
+            distance = Math.abs(distance);
+
+            //  Moving to the left
+            var w = this.width - distance;
+
+            //  Left-hand chunk
+            ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h);
+
+            //  Rest of the image
+            ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h);
+        }
+        else
+        {
+            //  Moving to the right
+            var w = this.width - distance;
+
+            //  Right-hand chunk
+            ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h);
+
+            //  Rest of the image
+            ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h);
+        }
+
+        this.clear();
+
+        return this.copy(this._swapCanvas);
+
+    },
+
+    /**
+    * Shifts the contents of this BitmapData vertically.
+    * 
+    * The image will wrap-around the sides.
+    *
+    * @method Phaser.BitmapData#moveV
+    * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    moveV: function (distance) {
+
+        var c = this._swapCanvas;
+        var ctx = c.getContext('2d');
+        var w = this.width;
+        var src = this.canvas;
+
+        ctx.clearRect(0, 0, this.width, this.height);
+
+        if (distance < 0)
+        {
+            distance = Math.abs(distance);
+
+            //  Moving up
+            var h = this.height - distance;
+
+            //  Top chunk
+            ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance);
+
+            //  Rest of the image
+            ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h);
+        }
+        else
+        {
+            //  Moving down
+            var h = this.height - distance;
+
+            //  Bottom chunk
+            ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance);
+
+            //  Rest of the image
+            ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h);
+        }
+
+        this.clear();
+
+        return this.copy(this._swapCanvas);
+
+    },
+
+    /**
+    * Updates the given objects so that they use this BitmapData as their texture.
+    * This will replace any texture they will currently have set.
+    *
+    * @method Phaser.BitmapData#add
+    * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    add: function (object) {
+
+        if (Array.isArray(object))
+        {
+            for (var i = 0; i < object.length; i++)
+            {
+                if (object[i]['loadTexture'])
+                {
+                    object[i].loadTexture(this);
+                }
+            }
+        }
+        else
+        {
+            object.loadTexture(this);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing.
+    * The source game object is not modified by this operation.
+    * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing.
+    * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string.
+    *
+    * @method Phaser.BitmapData#load
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    load: function (source) {
+
+        if (typeof source === 'string')
+        {
+            source = this.game.cache.getImage(source);
+        }
+
+        if (source)
+        {
+            this.resize(source.width, source.height);
+            this.cls();
+        }
+        else
+        {
+            return;
+        }
+
+        this.draw(source);
+
+        this.update();
+
+        return this;
+
+    },
+
+    /**
+    * Clears the BitmapData context using a clearRect.
+    *
+    * @method Phaser.BitmapData#cls
+    */
+
+    /**
+    * Clears the BitmapData context using a clearRect.
+    *
+    * You can optionally define the area to clear.
+    * If the arguments are left empty it will clear the entire canvas.
+    *
+    * @method Phaser.BitmapData#clear
+    * @param {number} [x=0] - The x coordinate of the top-left of the area to clear.
+    * @param {number} [y=0] - The y coordinate of the top-left of the area to clear.
+    * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width.
+    * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    clear: function (x, y, width, height) {
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+        if (width === undefined) { width = this.width; }
+        if (height === undefined) { height = this.height; }
+
+        this.context.clearRect(x, y, width, height);
+
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * Fills the BitmapData with the given color.
+    *
+    * @method Phaser.BitmapData#fill
+    * @param {number} r - The red color value, between 0 and 0xFF (255).
+    * @param {number} g - The green color value, between 0 and 0xFF (255).
+    * @param {number} b - The blue color value, between 0 and 0xFF (255).
+    * @param {number} [a=1] - The alpha color value, between 0 and 1.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    fill: function (r, g, b, a) {
+
+        if (a === undefined) { a = 1; }
+
+        this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
+        this.context.fillRect(0, 0, this.width, this.height);
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * Creates a new Image element by converting this BitmapDatas canvas into a dataURL.
+    *
+    * The image is then stored in the image Cache using the key given.
+    *
+    * Finally a PIXI.Texture is created based on the image and returned.
+    *
+    * You can apply the texture to a sprite or any other supporting object by using either the
+    * key or the texture. First call generateTexture:
+    *
+    * `var texture = bitmapdata.generateTexture('ball');`
+    *
+    * Then you can either apply the texture to a sprite:
+    * 
+    * `game.add.sprite(0, 0, texture);`
+    *
+    * or by using the string based key:
+    *
+    * `game.add.sprite(0, 0, 'ball');`
+    *
+    * @method Phaser.BitmapData#generateTexture
+    * @param {string} key - The key which will be used to store the image in the Cache.
+    * @return {PIXI.Texture} The newly generated texture.
+    */
+    generateTexture: function (key) {
+
+        var image = new Image();
+
+        image.src = this.canvas.toDataURL("image/png");
+
+        var obj = this.game.cache.addImage(key, '', image);
+
+        return new PIXI.Texture(obj.base);
+
+    },
+
+    /**
+    * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer.
+    *
+    * @method Phaser.BitmapData#resize
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    resize: function (width, height) {
+
+        if (width !== this.width || height !== this.height)
+        {
+            this.width = width;
+            this.height = height;
+
+            this.canvas.width = width;
+            this.canvas.height = height;
+
+            this._swapCanvas.width = width;
+            this._swapCanvas.height = height;
+
+            this.baseTexture.width = width;
+            this.baseTexture.height = height;
+
+            this.textureFrame.width = width;
+            this.textureFrame.height = height;
+
+            this.texture.width = width;
+            this.texture.height = height;
+
+            this.texture.crop.width = width;
+            this.texture.crop.height = height;
+
+            this.update();
+            this.dirty = true;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * This re-creates the BitmapData.imageData from the current context.
+    * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
+    * If not given the dimensions defaults to the full size of the context.
+    *
+    * @method Phaser.BitmapData#update
+    * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
+    * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
+    * @param {number} [width=1] - The width of the image data area.
+    * @param {number} [height=1] - The height of the image data area.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    update: function (x, y, width, height) {
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+        if (width === undefined) { width = Math.max(1, this.width); }
+        if (height === undefined) { height = Math.max(1, this.height); }
+
+        this.imageData = this.context.getImageData(x, y, width, height);
+        this.data = this.imageData.data;
+
+        if (this.imageData.data.buffer)
+        {
+            this.buffer = this.imageData.data.buffer;
+            this.pixels = new Uint32Array(this.buffer);
+        }
+        else
+        {
+            if (window['ArrayBuffer'])
+            {
+                this.buffer = new ArrayBuffer(this.imageData.data.length);
+                this.pixels = new Uint32Array(this.buffer);
+            }
+            else
+            {
+                this.pixels = this.imageData.data;
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback.
+    * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`.
+    * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha.
+    * The `color` property is an Int32 of the full color. Note the endianess of this will change per system.
+    * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others.
+    * The callback will also be sent the pixels x and y coordinates respectively.
+    * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object.
+    * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it.
+    *
+    * @method Phaser.BitmapData#processPixelRGB
+    * @param {function} callback - The callback that will be sent each pixel color object to be processed.
+    * @param {object} callbackContext - The context under which the callback will be called.
+    * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
+    * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
+    * @param {number} [width] - The width of the region to process.
+    * @param {number} [height] - The height of the region to process.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    processPixelRGB: function (callback, callbackContext, x, y, width, height) {
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+        if (width === undefined) { width = this.width; }
+        if (height === undefined) { height = this.height; }
+
+        var w = x + width;
+        var h = y + height;
+        var pixel = Phaser.Color.createColor();
+        var result = { r: 0, g: 0, b: 0, a: 0 };
+        var dirty = false;
+
+        for (var ty = y; ty < h; ty++)
+        {
+            for (var tx = x; tx < w; tx++)
+            {
+                Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel);
+
+                result = callback.call(callbackContext, pixel, tx, ty);
+
+                if (result !== false && result !== null && result !== undefined)
+                {
+                    this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false);
+                    dirty = true;
+                }
+            }
+        }
+
+        if (dirty)
+        {
+            this.context.putImageData(this.imageData, 0, 0);
+            this.dirty = true;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates.
+    * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped.
+    * Note that the format of the color received will be different depending on if the system is big or little endian.
+    * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead.
+    * The callback will also be sent the pixels x and y coordinates respectively.
+    *
+    * @method Phaser.BitmapData#processPixel
+    * @param {function} callback - The callback that will be sent each pixel color to be processed.
+    * @param {object} callbackContext - The context under which the callback will be called.
+    * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
+    * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
+    * @param {number} [width] - The width of the region to process.
+    * @param {number} [height] - The height of the region to process.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    processPixel: function (callback, callbackContext, x, y, width, height) {
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+        if (width === undefined) { width = this.width; }
+        if (height === undefined) { height = this.height; }
+
+        var w = x + width;
+        var h = y + height;
+        var pixel = 0;
+        var result = 0;
+        var dirty = false;
+
+        for (var ty = y; ty < h; ty++)
+        {
+            for (var tx = x; tx < w; tx++)
+            {
+                pixel = this.getPixel32(tx, ty);
+                result = callback.call(callbackContext, pixel, tx, ty);
+
+                if (result !== pixel)
+                {
+                    this.pixels[ty * this.width + tx] = result;
+                    dirty = true;
+                }
+            }
+        }
+
+        if (dirty)
+        {
+            this.context.putImageData(this.imageData, 0, 0);
+            this.dirty = true;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values.
+    * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. 
+    *
+    * @method Phaser.BitmapData#replaceRGB
+    * @param {number} r1 - The red color value to be replaced. Between 0 and 255.
+    * @param {number} g1 - The green color value to be replaced. Between 0 and 255.
+    * @param {number} b1 - The blue color value to be replaced. Between 0 and 255.
+    * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255.
+    * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255.
+    * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255.
+    * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255.
+    * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255.
+    * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) {
+
+        var sx = 0;
+        var sy = 0;
+        var w = this.width;
+        var h = this.height;
+        var source = Phaser.Color.packPixel(r1, g1, b1, a1);
+
+        if (region !== undefined && region instanceof Phaser.Rectangle)
+        {
+            sx = region.x;
+            sy = region.y;
+            w = region.width;
+            h = region.height;
+        }
+
+        for (var y = 0; y < h; y++)
+        {
+            for (var x = 0; x < w; x++)
+            {
+                if (this.getPixel32(sx + x, sy + y) === source)
+                {
+                    this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false);
+                }
+            }
+        }
+
+        this.context.putImageData(this.imageData, 0, 0);
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
+    *
+    * @method Phaser.BitmapData#setHSL
+    * @param {number} [h=null] - The hue, in the range 0 - 1.
+    * @param {number} [s=null] - The saturation, in the range 0 - 1.
+    * @param {number} [l=null] - The lightness, in the range 0 - 1.
+    * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    setHSL: function (h, s, l, region) {
+
+        if (h === undefined || h === null) { h = false; }
+        if (s === undefined || s === null) { s = false; }
+        if (l === undefined || l === null) { l = false; }
+
+        if (!h && !s && !l)
+        {
+            return;
+        }
+
+        if (region === undefined)
+        {
+            region = new Phaser.Rectangle(0, 0, this.width, this.height);
+        }
+
+        var pixel = Phaser.Color.createColor();
+
+        for (var y = region.y; y < region.bottom; y++)
+        {
+            for (var x = region.x; x < region.right; x++)
+            {
+                Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
+
+                if (h)
+                {
+                    pixel.h = h;
+                }
+
+                if (s)
+                {
+                    pixel.s = s;
+                }
+
+                if (l)
+                {
+                    pixel.l = l;
+                }
+
+                Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
+                this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
+            }
+        }
+
+        this.context.putImageData(this.imageData, 0, 0);
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
+    * Shifting will add the given value onto the current h, s and l values, not replace them.
+    * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1.
+    *
+    * @method Phaser.BitmapData#shiftHSL
+    * @param {number} [h=null] - The amount to shift the hue by.
+    * @param {number} [s=null] - The amount to shift the saturation by.
+    * @param {number} [l=null] - The amount to shift the lightness by.
+    * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    shiftHSL: function (h, s, l, region) {
+
+        if (h === undefined || h === null) { h = false; }
+        if (s === undefined || s === null) { s = false; }
+        if (l === undefined || l === null) { l = false; }
+
+        if (!h && !s && !l)
+        {
+            return;
+        }
+
+        if (region === undefined)
+        {
+            region = new Phaser.Rectangle(0, 0, this.width, this.height);
+        }
+
+        var pixel = Phaser.Color.createColor();
+
+        for (var y = region.y; y < region.bottom; y++)
+        {
+            for (var x = region.x; x < region.right; x++)
+            {
+                Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
+
+                if (h)
+                {
+                    pixel.h = this.game.math.wrap(pixel.h + h, 0, 1);
+                }
+
+                if (s)
+                {
+                    pixel.s = this.game.math.limitValue(pixel.s + s, 0, 1);
+                }
+
+                if (l)
+                {
+                    pixel.l = this.game.math.limitValue(pixel.l + l, 0, 1);
+                }
+
+                Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
+                this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
+            }
+        }
+
+        this.context.putImageData(this.imageData, 0, 0);
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * Sets the color of the given pixel to the specified red, green, blue and alpha values.
+    *
+    * @method Phaser.BitmapData#setPixel32
+    * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} red - The red color value, between 0 and 0xFF (255).
+    * @param {number} green - The green color value, between 0 and 0xFF (255).
+    * @param {number} blue - The blue color value, between 0 and 0xFF (255).
+    * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
+    * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    setPixel32: function (x, y, red, green, blue, alpha, immediate) {
+
+        if (immediate === undefined) { immediate = true; }
+
+        if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
+        {
+            if (Phaser.Device.LITTLE_ENDIAN)
+            {
+                this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
+            }
+            else
+            {
+                this.pixels[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
+            }
+
+            if (immediate)
+            {
+                this.context.putImageData(this.imageData, 0, 0);
+                this.dirty = true;
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Sets the color of the given pixel to the specified red, green and blue values.
+    *
+    * @method Phaser.BitmapData#setPixel
+    * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} red - The red color value, between 0 and 0xFF (255).
+    * @param {number} green - The green color value, between 0 and 0xFF (255).
+    * @param {number} blue - The blue color value, between 0 and 0xFF (255).
+    * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
+    * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    setPixel: function (x, y, red, green, blue, immediate) {
+
+        return this.setPixel32(x, y, red, green, blue, 255, immediate);
+
+    },
+
+    /**
+    * Get the color of a specific pixel in the context into a color object.
+    * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
+    * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
+    *
+    * @method Phaser.BitmapData#getPixel
+    * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
+    * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
+    */
+    getPixel: function (x, y, out) {
+
+        if (!out)
+        {
+            out = Phaser.Color.createColor();
+        }
+
+        var index = ~~(x + (y * this.width));
+
+        index *= 4;
+
+        out.r = this.data[index];
+        out.g = this.data[++index];
+        out.b = this.data[++index];
+        out.a = this.data[++index];
+
+        return out;
+
+    },
+
+    /**
+    * Get the color of a specific pixel including its alpha value.
+    * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
+    * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
+    * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA.
+    *
+    * @method Phaser.BitmapData#getPixel32
+    * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @return {number} A native color value integer (format: 0xAARRGGBB)
+    */
+    getPixel32: function (x, y) {
+
+        if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
+        {
+            return this.pixels[y * this.width + x];
+        }
+
+    },
+
+    /**
+    * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties.
+    * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
+    * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
+    *
+    * @method Phaser.BitmapData#getPixelRGB
+    * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
+    * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
+    * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
+    * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
+    * @return {object} An object with the red, green and blue values set in the r, g and b properties.
+    */
+    getPixelRGB: function (x, y, out, hsl, hsv) {
+
+        return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv);
+
+    },
+
+    /**
+    * Gets all the pixels from the region specified by the given Rectangle object.
+    *
+    * @method Phaser.BitmapData#getPixels
+    * @param {Phaser.Rectangle} rect - The Rectangle region to get.
+    * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property.
+    */
+    getPixels: function (rect) {
+
+        return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
+
+    },
+
+    /**
+    * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0).
+    * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties.
+    * 
+    * The direction parameter controls from which direction it should start the scan:
+    * 
+    * 0 = top to bottom
+    * 1 = bottom to top
+    * 2 = left to right
+    * 3 = right to left
+    *
+    * @method Phaser.BitmapData#getFirstPixel
+    * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left.
+    * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties.
+    */
+    getFirstPixel: function (direction) {
+
+        if (direction === undefined) { direction = 0; }
+
+        var pixel = Phaser.Color.createColor();
+
+        var x = 0;
+        var y = 0;
+        var v = 1;
+        var scan = false;
+
+        if (direction === 1)
+        {
+            v = -1;
+            y = this.height;
+        }
+        else if (direction === 3)
+        {
+            v = -1;
+            x = this.width;
+        }
+
+        do {
+
+            Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel);
+
+            if (direction === 0 || direction === 1)
+            {
+                //  Top to Bottom / Bottom to Top
+                x++;
+
+                if (x === this.width)
+                {
+                    x = 0;
+                    y += v;
+
+                    if (y >= this.height || y <= 0)
+                    {
+                        scan = true;
+                    }
+                }
+            }
+            else if (direction === 2 || direction === 3)
+            {
+                //  Left to Right / Right to Left
+                y++;
+
+                if (y === this.height)
+                {
+                    y = 0;
+                    x += v;
+
+                    if (x >= this.width || x <= 0)
+                    {
+                        scan = true;
+                    }
+                }
+            }
+        }
+        while (pixel.a === 0 && !scan);
+
+        pixel.x = x;
+        pixel.y = y;
+
+        return pixel;
+
+    },
+
+    /**
+    * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels.
+    * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels.
+    *
+    * @method Phaser.BitmapData#getBounds
+    * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created.
+    * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData.
+    */
+    getBounds: function (rect) {
+
+        if (rect === undefined) { rect = new Phaser.Rectangle(); }
+
+        rect.x = this.getFirstPixel(2).x;
+
+        //  If we hit this, there's no point scanning any more, the image is empty
+        if (rect.x === this.width)
+        {
+            return rect.setTo(0, 0, 0, 0);
+        }
+
+        rect.y = this.getFirstPixel(0).y;
+        rect.width = (this.getFirstPixel(3).x - rect.x) + 1;
+        rect.height = (this.getFirstPixel(1).y - rect.y) + 1;
+
+        return rect;
+
+    },
+
+    /**
+    * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it.
+    *
+    * @method Phaser.BitmapData#addToWorld
+    * @param {number} [x=0] - The x coordinate to place the Image at.
+    * @param {number} [y=0] - The y coordinate to place the Image at.
+    * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
+    * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
+    * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
+    * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
+    * @return {Phaser.Image} The newly added Image object.
+    */
+    addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) {
+
+        scaleX = scaleX || 1;
+        scaleY = scaleY || 1;
+
+        var image = this.game.add.image(x, y, this);
+
+        image.anchor.set(anchorX, anchorY);
+        image.scale.set(scaleX, scaleY);
+
+        return image;
+
+    },
+
+    /**
+     * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself.
+     * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn.
+     * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters.
+     * Note that the source image can also be this BitmapData, which can create some interesting effects.
+     * 
+     * This method has a lot of parameters for maximum control.
+     * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all.
+     *
+     * @method Phaser.BitmapData#copy
+     * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself.
+     * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image.
+     * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image.
+     * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width.
+     * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height.
+     * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`.
+     * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`.
+     * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter.
+     * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter.
+     * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters.
+     * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
+     * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
+     * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on.
+     * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on.
+     * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque.
+     * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
+     * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
+     * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+     */
+    copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) {
+
+        if (source === undefined || source === null) { source = this; }
+
+        this._image = source;
+
+        if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text)
+        {
+            //  Copy over sprite values
+            this._pos.set(source.texture.crop.x, source.texture.crop.y);
+            this._size.set(source.texture.crop.width, source.texture.crop.height);
+            this._scale.set(source.scale.x, source.scale.y);
+            this._anchor.set(source.anchor.x, source.anchor.y);
+            this._rotate = source.rotation;
+            this._alpha.current = source.alpha;
+            this._image = source.texture.baseTexture.source;
+
+            if (tx === undefined || tx === null) { tx = source.x; }
+            if (ty === undefined || ty === null) { ty = source.y; }
+
+            if (source.texture.trim)
+            {
+                //  Offset the translation coordinates by the trim amount
+                tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width;
+                ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height;
+            }
+
+            if (source.tint !== 0xFFFFFF)
+            {
+                if (source.cachedTint !== source.tint)
+                {
+                    source.cachedTint = source.tint;
+                    source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint);
+                }
+
+                this._image = source.tintedTexture;
+            }
+        }
+        else
+        {
+            //  Reset
+            this._pos.set(0);
+            this._scale.set(1);
+            this._anchor.set(0);
+            this._rotate = 0;
+            this._alpha.current = 1;
+
+            if (source instanceof Phaser.BitmapData)
+            {
+                this._image = source.canvas;
+            }
+            else if (typeof source === 'string')
+            {
+                source = this.game.cache.getImage(source);
+
+                if (source === null)
+                {
+                    return;
+                }
+                else
+                {
+                    this._image = source;
+                }
+            }
+
+            this._size.set(this._image.width, this._image.height);
+        }
+
+        //  The source region to copy from
+        if (x === undefined || x === null) { x = 0; }
+        if (y === undefined || y === null) { y = 0; }
+
+        //  If they set a width/height then we override the frame values with them
+        if (width)
+        {
+            this._size.x = width;
+        }
+
+        if (height)
+        {
+            this._size.y = height;
+        }
+
+        //  The destination region to copy to
+        if (tx === undefined || tx === null) { tx = x; }
+        if (ty === undefined || ty === null) { ty = y; }
+        if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; }
+        if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; }
+
+        //  Rotation - if set this will override any potential Sprite value
+        if (typeof rotate === 'number')
+        {
+            this._rotate = rotate;
+        }
+
+        //  Anchor - if set this will override any potential Sprite value
+        if (typeof anchorX === 'number')
+        {
+            this._anchor.x = anchorX;
+        }
+
+        if (typeof anchorY === 'number')
+        {
+            this._anchor.y = anchorY;
+        }
+
+        //  Scaling - if set this will override any potential Sprite value
+        if (typeof scaleX === 'number')
+        {
+            this._scale.x = scaleX;
+        }
+
+        if (typeof scaleY === 'number')
+        {
+            this._scale.y = scaleY;
+        }
+
+        //  Effects
+        if (typeof alpha === 'number')
+        {
+            this._alpha.current = alpha;
+        }
+
+        if (blendMode === undefined) { blendMode = null; }
+        if (roundPx === undefined) { roundPx = false; }
+
+        if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0)
+        {
+            //  Why bother wasting CPU cycles drawing something you can't see?
+            return;
+        }
+
+        this._alpha.prev = this.context.globalAlpha;
+
+        this.context.save();
+
+        this.context.globalAlpha = this._alpha.current;
+
+        if (blendMode)
+        {
+            this.context.globalCompositeOperation = blendMode;
+        }
+
+        if (roundPx)
+        {
+            tx |= 0;
+            ty |= 0;
+        }
+
+        this.context.translate(tx, ty);
+
+        this.context.scale(this._scale.x, this._scale.y);
+
+        this.context.rotate(this._rotate);
+
+        this.context.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight);
+
+        this.context.restore();
+
+        this.context.globalAlpha = this._alpha.prev;
+
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location.
+    *
+    * @method Phaser.BitmapData#copyRect
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache.
+    * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image.
+    * @param {number} x - The destination x coordinate to copy the image to.
+    * @param {number} y - The destination y coordinate to copy the image to.
+    * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque.
+    * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
+    * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    copyRect: function (source, area, x, y, alpha, blendMode, roundPx) {
+
+        return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx);
+
+    },
+
+    /**
+    * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified.
+    * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling.
+    * When drawing it will take into account the Sprites rotation, scale and alpha values.
+    *
+    * @method Phaser.BitmapData#draw
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} source - The Sprite, Image or Text object to draw onto this BitmapData.
+    * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`.
+    * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`.
+    * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`.
+    * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`.
+    * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
+    * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    draw: function (source, x, y, width, height, blendMode, roundPx) {
+
+        //  By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here
+        return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx);
+
+    },
+
+    /**
+    * Draws the immediate children of a Phaser.Group to this BitmapData.
+    * Children are only drawn if they have their `exists` property set to `true`.
+    * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be drawn.
+    * When drawing it will take into account the child's rotation, scale and alpha values.
+    * No iteration takes place. Groups nested inside other Groups will not be iterated through.
+    *
+    * @method Phaser.BitmapData#drawGroup
+    * @param {Phaser.Group} group - The Group to draw onto this BitmapData.
+    * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
+    * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    drawGroup: function (group, blendMode, roundPx) {
+
+        if (group.total > 0)
+        {
+            group.forEachExists(this.copy, this, null, null, null, null, null, null, null, null, null, null, null, null, null, null, blendMode, roundPx);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it.
+    * You can cancel an existing shadow by calling this method and passing no parameters.
+    * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage.
+    *
+    * @method Phaser.BitmapData#shadow
+    * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset.
+    * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow.
+    * @param {number} [x=10] - The horizontal offset of the shadow in pixels.
+    * @param {number} [y=10] - The vertical offset of the shadow in pixels.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    shadow: function (color, blur, x, y) {
+
+        if (color === undefined || color === null)
+        {
+            this.context.shadowColor = 'rgba(0,0,0,0)';
+        }
+        else
+        {
+            this.context.shadowColor = color;
+            this.context.shadowBlur = blur || 5;
+            this.context.shadowOffsetX = x || 10;
+            this.context.shadowOffsetY = y || 10;
+        }
+
+    },
+
+    /**
+    * Draws the image onto this BitmapData using an image as an alpha mask.
+    *
+    * @method Phaser.BitmapData#alphaMask
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself.
+    * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask.
+    * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size.
+    * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    alphaMask: function (source, mask, sourceRect, maskRect) {
+
+        if (maskRect === undefined || maskRect === null)
+        {
+            this.draw(mask).blendSourceAtop();
+        }
+        else
+        {
+            this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop();
+        }
+
+        if (sourceRect === undefined || sourceRect === null)
+        {
+            this.draw(source).blendReset();
+        }
+        else
+        {
+            this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset();
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData.
+    * The original BitmapData remains unchanged.
+    * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true.
+    * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid:
+    * `picture.extract(mask, r, g, b)`
+    * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color.
+    * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint
+    * the color during extraction.
+    *
+    * @method Phaser.BitmapData#extract
+    * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to.
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at.
+    * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied?
+    * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255.
+    * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255.
+    * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255.
+    * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on.
+    */
+    extract: function (destination, r, g, b, a, resize, r2, g2, b2) {
+
+        if (a === undefined) { a = 255; }
+        if (resize === undefined) { resize = false; }
+        if (r2 === undefined) { r2 = r; }
+        if (g2 === undefined) { g2 = g; }
+        if (b2 === undefined) { b2 = b; }
+
+        if (resize)
+        {
+            destination.resize(this.width, this.height);
+        }
+
+        this.processPixelRGB(
+            function (pixel, x, y)
+            {
+                if (pixel.r === r && pixel.g === g && pixel.b === b)
+                {
+                    destination.setPixel32(x, y, r2, g2, b2, a, false);
+                }
+                return false;
+            },
+            this);
+
+        destination.context.putImageData(destination.imageData, 0, 0);
+        destination.dirty = true;
+
+        return destination;
+
+    },
+
+    /**
+    * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size.
+    *
+    * @method Phaser.BitmapData#rect
+    * @param {number} x - The x coordinate of the top-left of the Rectangle.
+    * @param {number} y - The y coordinate of the top-left of the Rectangle.
+    * @param {number} width - The width of the Rectangle.
+    * @param {number} height - The height of the Rectangle.
+    * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    rect: function (x, y, width, height, fillStyle) {
+
+        if (typeof fillStyle !== 'undefined')
+        {
+            this.context.fillStyle = fillStyle;
+        }
+
+        this.context.fillRect(x, y, width, height);
+
+        return this;
+
+    },
+
+    /**
+    * Draws text to the BitmapData in the given font and color.
+    * The default font is 14px Courier, so useful for quickly drawing debug text.
+    * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method.
+    *
+    * @method Phaser.BitmapData#text
+    * @param {string} text - The text to write to the BitmapData.
+    * @param {number} x - The x coordinate of the top-left of the text string.
+    * @param {number} y - The y coordinate of the top-left of the text string.
+    * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can.
+    * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in.
+    * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1)
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    text: function (text, x, y, font, color, shadow) {
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+        if (font === undefined) { font = '14px Courier'; }
+        if (color === undefined) { color = 'rgb(255,255,255)'; }
+        if (shadow === undefined) { shadow = true; }
+
+        var prevFont = this.context.font;
+
+        this.context.font = font;
+
+        if (shadow)
+        {
+            this.context.fillStyle = 'rgb(0,0,0)';
+            this.context.fillText(text, x + 1, y + 1);
+        }
+        
+        this.context.fillStyle = color;
+        this.context.fillText(text, x, y);
+
+        this.context.font = prevFont;
+
+    },
+
+    /**
+    * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size.
+    *
+    * @method Phaser.BitmapData#circle
+    * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle.
+    * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle.
+    * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter.
+    * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    circle: function (x, y, radius, fillStyle) {
+
+        if (typeof fillStyle !== 'undefined')
+        {
+            this.context.fillStyle = fillStyle;
+        }
+
+        this.context.beginPath();
+        this.context.arc(x, y, radius, 0, Math.PI * 2, false);
+        this.context.closePath();
+
+        this.context.fill();
+
+        return this;
+
+    },
+
+    /**
+    * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line.
+    *
+    * @method Phaser.BitmapData#textureLine
+    * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line.
+    * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image.
+    * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`.
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    textureLine: function (line, image, repeat) {
+
+        if (repeat === undefined) { repeat = 'repeat-x'; }
+
+        if (typeof image === 'string')
+        {
+            image = this.game.cache.getImage(image);
+
+            if (!image)
+            {
+                return;
+            }
+        }
+
+        var width = line.length;
+
+        if (repeat === 'no-repeat' && width > image.width)
+        {
+            width = image.width;
+        }
+
+        this.context.fillStyle = this.context.createPattern(image, repeat);
+
+        this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height);
+
+        this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos);
+
+        this.context.save();
+        this.context.translate(this._pos.x, this._pos.y);
+        this.context.rotate(line.angle);
+        this.context.fillRect(0, 0, width, image.height);
+        this.context.restore();
+
+        this.dirty = true;
+
+        return this;
+
+    },
+
+    /**
+    * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
+    * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function.
+    * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`.
+    *
+    * @method Phaser.BitmapData#render
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    render: function () {
+
+        if (!this.disableTextureUpload && this.dirty)
+        {
+            this.baseTexture.dirty();
+            this.dirty = false;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Resets the blend mode (effectively sets it to 'source-over')
+    *
+    * @method Phaser.BitmapData#blendReset
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendReset: function () {
+
+        this.context.globalCompositeOperation = 'source-over';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'source-over'
+    *
+    * @method Phaser.BitmapData#blendSourceOver
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendSourceOver: function () {
+
+        this.context.globalCompositeOperation = 'source-over';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'source-in'
+    *
+    * @method Phaser.BitmapData#blendSourceIn
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendSourceIn: function () {
+
+        this.context.globalCompositeOperation = 'source-in';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'source-out'
+    *
+    * @method Phaser.BitmapData#blendSourceOut
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendSourceOut: function () {
+
+        this.context.globalCompositeOperation = 'source-out';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'source-atop'
+    *
+    * @method Phaser.BitmapData#blendSourceAtop
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendSourceAtop: function () {
+
+        this.context.globalCompositeOperation = 'source-atop';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'destination-over'
+    *
+    * @method Phaser.BitmapData#blendDestinationOver
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendDestinationOver: function () {
+
+        this.context.globalCompositeOperation = 'destination-over';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'destination-in'
+    *
+    * @method Phaser.BitmapData#blendDestinationIn
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendDestinationIn: function () {
+
+        this.context.globalCompositeOperation = 'destination-in';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'destination-out'
+    *
+    * @method Phaser.BitmapData#blendDestinationOut
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendDestinationOut: function () {
+
+        this.context.globalCompositeOperation = 'destination-out';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'destination-atop'
+    *
+    * @method Phaser.BitmapData#blendDestinationAtop
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendDestinationAtop: function () {
+
+        this.context.globalCompositeOperation = 'destination-atop';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'xor'
+    *
+    * @method Phaser.BitmapData#blendXor
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendXor: function () {
+
+        this.context.globalCompositeOperation = 'xor';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'lighter'
+    *
+    * @method Phaser.BitmapData#blendAdd
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendAdd: function () {
+
+        this.context.globalCompositeOperation = 'lighter';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'multiply'
+    *
+    * @method Phaser.BitmapData#blendMultiply
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendMultiply: function () {
+
+        this.context.globalCompositeOperation = 'multiply';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'screen'
+    *
+    * @method Phaser.BitmapData#blendScreen
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendScreen: function () {
+
+        this.context.globalCompositeOperation = 'screen';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'overlay'
+    *
+    * @method Phaser.BitmapData#blendOverlay
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendOverlay: function () {
+
+        this.context.globalCompositeOperation = 'overlay';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'darken'
+    *
+    * @method Phaser.BitmapData#blendDarken
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendDarken: function () {
+
+        this.context.globalCompositeOperation = 'darken';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'lighten'
+    *
+    * @method Phaser.BitmapData#blendLighten
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendLighten: function () {
+
+        this.context.globalCompositeOperation = 'lighten';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'color-dodge'
+    *
+    * @method Phaser.BitmapData#blendColorDodge
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendColorDodge: function () {
+
+        this.context.globalCompositeOperation = 'color-dodge';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'color-burn'
+    *
+    * @method Phaser.BitmapData#blendColorBurn
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendColorBurn: function () {
+
+        this.context.globalCompositeOperation = 'color-burn';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'hard-light'
+    *
+    * @method Phaser.BitmapData#blendHardLight
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendHardLight: function () {
+
+        this.context.globalCompositeOperation = 'hard-light';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'soft-light'
+    *
+    * @method Phaser.BitmapData#blendSoftLight
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendSoftLight: function () {
+
+        this.context.globalCompositeOperation = 'soft-light';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'difference'
+    *
+    * @method Phaser.BitmapData#blendDifference
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendDifference: function () {
+
+        this.context.globalCompositeOperation = 'difference';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'exclusion'
+    *
+    * @method Phaser.BitmapData#blendExclusion
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendExclusion: function () {
+
+        this.context.globalCompositeOperation = 'exclusion';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'hue'
+    *
+    * @method Phaser.BitmapData#blendHue
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendHue: function () {
+
+        this.context.globalCompositeOperation = 'hue';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'saturation'
+    *
+    * @method Phaser.BitmapData#blendSaturation
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendSaturation: function () {
+
+        this.context.globalCompositeOperation = 'saturation';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'color'
+    *
+    * @method Phaser.BitmapData#blendColor
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendColor: function () {
+
+        this.context.globalCompositeOperation = 'color';
+        return this;
+
+    },
+
+    /**
+    * Sets the blend mode to 'luminosity'
+    *
+    * @method Phaser.BitmapData#blendLuminosity
+    * @return {Phaser.BitmapData} This BitmapData object for method chaining.
+    */
+    blendLuminosity: function () {
+
+        this.context.globalCompositeOperation = 'luminosity';
+        return this;
+
+    }
+
+};
+
+/**
+* @memberof Phaser.BitmapData
+* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value.
+*/
+Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", {
+
+    get: function () {
+
+        Phaser.Canvas.getSmoothingEnabled(this.context);
+
+    },
+
+    set: function (value) {
+
+        Phaser.Canvas.setSmoothingEnabled(this.context, value);
+
+    }
+
+});
+
+/**
+ * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform.
+ *
+ * @method Phaser.BitmapData.getTransform
+ * @param {number} translateX - The x translate value.
+ * @param {number} translateY - The y translate value.
+ * @param {number} scaleX - The scale x value.
+ * @param {number} scaleY - The scale y value.
+ * @param {number} skewX - The skew x value.
+ * @param {number} skewY - The skew y value.
+ * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms.
+ */
+Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) {
+
+    if (typeof translateX !== 'number') { translateX = 0; }
+    if (typeof translateY !== 'number') { translateY = 0; }
+    if (typeof scaleX !== 'number') { scaleX = 1; }
+    if (typeof scaleY !== 'number') { scaleY = 1; }
+    if (typeof skewX !== 'number') { skewX = 0; }
+    if (typeof skewY !== 'number') { skewY = 0; }
+
+    return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY };
+
+};
+
+Phaser.BitmapData.prototype.constructor = Phaser.BitmapData;
+
+/**
+ * @author Mat Groves http://matgroves.com/ @Doormat23
+ */
+
+/**
+ * The Graphics class contains methods used to draw primitive shapes such as lines, circles and rectangles to the display, and color and fill them.
+ * 
+ * @class Graphics
+ * @extends DisplayObjectContainer
+ * @constructor
+ */
+PIXI.Graphics = function()
+{
+    PIXI.DisplayObjectContainer.call(this);
+
+    this.renderable = true;
+
+    /**
+     * The alpha value used when filling the Graphics object.
+     *
+     * @property fillAlpha
+     * @type Number
+     */
+    this.fillAlpha = 1;
+
+    /**
+     * The width (thickness) of any lines drawn.
+     *
+     * @property lineWidth
+     * @type Number
+     */
+    this.lineWidth = 0;
+
+    /**
+     * The color of any lines drawn.
+     *
+     * @property lineColor
+     * @type String
+     * @default 0
+     */
+    this.lineColor = 0;
+
+    /**
+     * Graphics data
+     *
+     * @property graphicsData
+     * @type Array
+     * @private
+     */
+    this.graphicsData = [];
+
+    /**
+     * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint.
+     *
+     * @property tint
+     * @type Number
+     * @default 0xFFFFFF
+     */
+    this.tint = 0xFFFFFF;
+
+    /**
+     * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode.
+     *
+     * @property blendMode
+     * @type Number
+     * @default PIXI.blendModes.NORMAL;
+     */
+    this.blendMode = PIXI.blendModes.NORMAL;
+    
+    /**
+     * Current path
+     *
+     * @property currentPath
+     * @type Object
+     * @private
+     */
+    this.currentPath = null;
+    
+    /**
+     * Array containing some WebGL-related properties used by the WebGL renderer.
+     *
+     * @property _webGL
+     * @type Array
+     * @private
+     */
+    this._webGL = [];
+
+    /**
+     * Whether this shape is being used as a mask.
+     *
+     * @property isMask
+     * @type Boolean
+     */
+    this.isMask = false;
+
+    /**
+     * The bounds' padding used for bounds calculation.
+     *
+     * @property boundsPadding
+     * @type Number
+     */
+    this.boundsPadding = 0;
+
+    this._localBounds = new PIXI.Rectangle(0,0,1,1);
+
+    /**
+     * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated.
+     * 
+     * @property dirty
+     * @type Boolean
+     * @private
+     */
+    this.dirty = true;
+
+    /**
+     * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated.
+     * 
+     * @property webGLDirty
+     * @type Boolean
+     * @private
+     */
+    this.webGLDirty = false;
+
+    /**
+     * Used to detect if the cached sprite object needs to be updated.
+     * 
+     * @property cachedSpriteDirty
+     * @type Boolean
+     * @private
+     */
+    this.cachedSpriteDirty = false;
+
+};
+
+// constructor
+PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
+PIXI.Graphics.prototype.constructor = PIXI.Graphics;
+
+/**
+ * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
+ *
+ * @method lineStyle
+ * @param lineWidth {Number} width of the line to draw, will update the objects stored style
+ * @param color {Number} color of the line to draw, will update the objects stored style
+ * @param alpha {Number} alpha of the line to draw, will update the objects stored style
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha)
+{
+    this.lineWidth = lineWidth || 0;
+    this.lineColor = color || 0;
+    this.lineAlpha = (alpha === undefined) ? 1 : alpha;
+
+    if (this.currentPath)
+    {
+        if (this.currentPath.shape.points.length)
+        {
+            // halfway through a line? start a new one!
+            this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2)));
+        }
+        else
+        {
+            // otherwise its empty so lets just set the line properties
+            this.currentPath.lineWidth = this.lineWidth;
+            this.currentPath.lineColor = this.lineColor;
+            this.currentPath.lineAlpha = this.lineAlpha;
+        }
+    }
+
+    return this;
+};
+
+/**
+ * Moves the current drawing position to x, y.
+ *
+ * @method moveTo
+ * @param x {Number} the X coordinate to move to
+ * @param y {Number} the Y coordinate to move to
+ * @return {Graphics}
+  */
+PIXI.Graphics.prototype.moveTo = function(x, y)
+{
+    this.drawShape(new PIXI.Polygon([x, y]));
+
+    return this;
+};
+
+/**
+ * Draws a line using the current line style from the current drawing position to (x, y);
+ * The current drawing position is then set to (x, y).
+ *
+ * @method lineTo
+ * @param x {Number} the X coordinate to draw to
+ * @param y {Number} the Y coordinate to draw to
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.lineTo = function(x, y)
+{
+    if (!this.currentPath)
+    {
+        this.moveTo(0, 0);
+    }
+
+    this.currentPath.shape.points.push(x, y);
+    this.dirty = true;
+
+    return this;
+};
+
+/**
+ * Calculate the points for a quadratic bezier curve and then draws it.
+ * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
+ *
+ * @method quadraticCurveTo
+ * @param cpX {Number} Control point x
+ * @param cpY {Number} Control point y
+ * @param toX {Number} Destination point x
+ * @param toY {Number} Destination point y
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.quadraticCurveTo = function(cpX, cpY, toX, toY)
+{
+    if (this.currentPath)
+    {
+        if (this.currentPath.shape.points.length === 0)
+        {
+            this.currentPath.shape.points = [0, 0];
+        }
+    }
+    else
+    {
+        this.moveTo(0,0);
+    }
+
+    var xa,
+        ya,
+        n = 20,
+        points = this.currentPath.shape.points;
+
+    if (points.length === 0)
+    {
+        this.moveTo(0, 0);
+    }
+
+    var fromX = points[points.length - 2];
+    var fromY = points[points.length - 1];
+    var j = 0;
+    for (var i = 1; i <= n; ++i)
+    {
+        j = i / n;
+
+        xa = fromX + ( (cpX - fromX) * j );
+        ya = fromY + ( (cpY - fromY) * j );
+
+        points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ),
+                     ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) );
+    }
+
+    this.dirty = true;
+
+    return this;
+};
+
+/**
+ * Calculate the points for a bezier curve and then draws it.
+ *
+ * @method bezierCurveTo
+ * @param cpX {Number} Control point x
+ * @param cpY {Number} Control point y
+ * @param cpX2 {Number} Second Control point x
+ * @param cpY2 {Number} Second Control point y
+ * @param toX {Number} Destination point x
+ * @param toY {Number} Destination point y
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.bezierCurveTo = function(cpX, cpY, cpX2, cpY2, toX, toY)
+{
+    if (this.currentPath)
+    {
+        if (this.currentPath.shape.points.length === 0)
+        {
+            this.currentPath.shape.points = [0, 0];
+        }
+    }
+    else
+    {
+        this.moveTo(0,0);
+    }
+
+    var n = 20,
+        dt,
+        dt2,
+        dt3,
+        t2,
+        t3,
+        points = this.currentPath.shape.points;
+
+    var fromX = points[points.length-2];
+    var fromY = points[points.length-1];
+    var j = 0;
+
+    for (var i = 1; i <= n; ++i)
+    {
+        j = i / n;
+
+        dt = (1 - j);
+        dt2 = dt * dt;
+        dt3 = dt2 * dt;
+
+        t2 = j * j;
+        t3 = t2 * j;
+        
+        points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX,
+                     dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY);
+    }
+    
+    this.dirty = true;
+
+    return this;
+};
+
+/*
+ * The arcTo() method creates an arc/curve between two tangents on the canvas.
+ * 
+ * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
+ *
+ * @method arcTo
+ * @param x1 {Number} The x-coordinate of the beginning of the arc
+ * @param y1 {Number} The y-coordinate of the beginning of the arc
+ * @param x2 {Number} The x-coordinate of the end of the arc
+ * @param y2 {Number} The y-coordinate of the end of the arc
+ * @param radius {Number} The radius of the arc
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.arcTo = function(x1, y1, x2, y2, radius)
+{
+    if (this.currentPath)
+    {
+        if (this.currentPath.shape.points.length === 0)
+        {
+            this.currentPath.shape.points.push(x1, y1);
+        }
+    }
+    else
+    {
+        this.moveTo(x1, y1);
+    }
+
+    var points = this.currentPath.shape.points,
+        fromX = points[points.length-2],
+        fromY = points[points.length-1],
+        a1 = fromY - y1,
+        b1 = fromX - x1,
+        a2 = y2   - y1,
+        b2 = x2   - x1,
+        mm = Math.abs(a1 * b2 - b1 * a2);
+
+    if (mm < 1.0e-8 || radius === 0)
+    {
+        if (points[points.length-2] !== x1 || points[points.length-1] !== y1)
+        {
+            points.push(x1, y1);
+        }
+    }
+    else
+    {
+        var dd = a1 * a1 + b1 * b1,
+            cc = a2 * a2 + b2 * b2,
+            tt = a1 * a2 + b1 * b2,
+            k1 = radius * Math.sqrt(dd) / mm,
+            k2 = radius * Math.sqrt(cc) / mm,
+            j1 = k1 * tt / dd,
+            j2 = k2 * tt / cc,
+            cx = k1 * b2 + k2 * b1,
+            cy = k1 * a2 + k2 * a1,
+            px = b1 * (k2 + j1),
+            py = a1 * (k2 + j1),
+            qx = b2 * (k1 + j2),
+            qy = a2 * (k1 + j2),
+            startAngle = Math.atan2(py - cy, px - cx),
+            endAngle   = Math.atan2(qy - cy, qx - cx);
+
+        this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1);
+    }
+
+    this.dirty = true;
+
+    return this;
+};
+
+/**
+ * The arc method creates an arc/curve (used to create circles, or parts of circles).
+ *
+ * @method arc
+ * @param cx {Number} The x-coordinate of the center of the circle
+ * @param cy {Number} The y-coordinate of the center of the circle
+ * @param radius {Number} The radius of the circle
+ * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
+ * @param endAngle {Number} The ending angle, in radians
+ * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise)
+{
+    //  If we do this we can never draw a full circle
+    if (startAngle === endAngle)
+    {
+        return this;
+    }
+
+    if (anticlockwise === undefined) { anticlockwise = false; }
+
+    if (!anticlockwise && endAngle <= startAngle)
+    {
+        endAngle += Math.PI * 2;
+    }
+    else if (anticlockwise && startAngle <= endAngle)
+    {
+        startAngle += Math.PI * 2;
+    }
+
+    var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle);
+    var segs =  Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40;
+
+    //  Sweep check - moved here because we don't want to do the moveTo below if the arc fails
+    if (sweep === 0)
+    {
+        return this;
+    }
+
+    var startX = cx + Math.cos(startAngle) * radius;
+    var startY = cy + Math.sin(startAngle) * radius;
+
+    if (anticlockwise && this.filling)
+    {
+        this.moveTo(cx, cy);
+    }
+    else
+    {
+        this.moveTo(startX, startY);
+    }
+
+    //  currentPath will always exist after calling a moveTo
+    var points = this.currentPath.shape.points;
+
+    var theta = sweep / (segs * 2);
+    var theta2 = theta * 2;
+
+    var cTheta = Math.cos(theta);
+    var sTheta = Math.sin(theta);
+    
+    var segMinus = segs - 1;
+
+    var remainder = (segMinus % 1) / segMinus;
+
+    for (var i = 0; i <= segMinus; i++)
+    {
+        var real =  i + remainder * i;
+    
+        var angle = ((theta) + startAngle + (theta2 * real));
+
+        var c = Math.cos(angle);
+        var s = -Math.sin(angle);
+
+        points.push(( (cTheta *  c) + (sTheta * s) ) * radius + cx,
+                    ( (cTheta * -s) + (sTheta * c) ) * radius + cy);
+    }
+
+    this.dirty = true;
+
+    return this;
+};
+
+/**
+ * Specifies a simple one-color fill that subsequent calls to other Graphics methods
+ * (such as lineTo() or drawCircle()) use when drawing.
+ *
+ * @method beginFill
+ * @param color {Number} the color of the fill
+ * @param alpha {Number} the alpha of the fill
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.beginFill = function(color, alpha)
+{
+    this.filling = true;
+    this.fillColor = color || 0;
+    this.fillAlpha = (alpha === undefined) ? 1 : alpha;
+
+    if (this.currentPath)
+    {
+        if (this.currentPath.shape.points.length <= 2)
+        {
+            this.currentPath.fill = this.filling;
+            this.currentPath.fillColor = this.fillColor;
+            this.currentPath.fillAlpha = this.fillAlpha;
+        }
+    }
+
+    return this;
+};
+
+/**
+ * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
+ *
+ * @method endFill
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.endFill = function()
+{
+    this.filling = false;
+    this.fillColor = null;
+    this.fillAlpha = 1;
+
+    return this;
+};
+
+/**
+ * @method drawRect
+ *
+ * @param x {Number} The X coord of the top-left of the rectangle
+ * @param y {Number} The Y coord of the top-left of the rectangle
+ * @param width {Number} The width of the rectangle
+ * @param height {Number} The height of the rectangle
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.drawRect = function(x, y, width, height)
+{
+    this.drawShape(new PIXI.Rectangle(x, y, width, height));
+
+    return this;
+};
+
+/**
+ * @method drawRoundedRect
+ * @param x {Number} The X coord of the top-left of the rectangle
+ * @param y {Number} The Y coord of the top-left of the rectangle
+ * @param width {Number} The width of the rectangle
+ * @param height {Number} The height of the rectangle
+ * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9.
+ */
+PIXI.Graphics.prototype.drawRoundedRect = function(x, y, width, height, radius)
+{
+    this.drawShape(new PIXI.RoundedRectangle(x, y, width, height, radius));
+
+    return this;
+};
+
+/**
+ * Draws a circle.
+ *
+ * @method drawCircle
+ * @param x {Number} The X coordinate of the center of the circle
+ * @param y {Number} The Y coordinate of the center of the circle
+ * @param diameter {Number} The diameter of the circle
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.drawCircle = function(x, y, diameter)
+{
+    this.drawShape(new PIXI.Circle(x, y, diameter));
+
+    return this;
+};
+
+/**
+ * Draws an ellipse.
+ *
+ * @method drawEllipse
+ * @param x {Number} The X coordinate of the center of the ellipse
+ * @param y {Number} The Y coordinate of the center of the ellipse
+ * @param width {Number} The half width of the ellipse
+ * @param height {Number} The half height of the ellipse
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.drawEllipse = function(x, y, width, height)
+{
+    this.drawShape(new PIXI.Ellipse(x, y, width, height));
+
+    return this;
+};
+
+/**
+ * Draws a polygon using the given path.
+ *
+ * @method drawPolygon
+ * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object.
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.drawPolygon = function(path)
+{
+    if (path instanceof Phaser.Polygon || path instanceof PIXI.Polygon)
+    {
+        path = path.points;
+    }
+
+    // prevents an argument assignment deopt
+    // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
+    var points = path;
+
+    if (!Array.isArray(points))
+    {
+        // prevents an argument leak deopt
+        // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
+        points = new Array(arguments.length);
+
+        for (var i = 0; i < points.length; ++i)
+        {
+            points[i] = arguments[i];
+        }
+    }
+
+    this.drawShape(new Phaser.Polygon(points));
+
+    return this;
+};
+
+/**
+ * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
+ *
+ * @method clear
+ * @return {Graphics}
+ */
+PIXI.Graphics.prototype.clear = function()
+{
+    this.lineWidth = 0;
+    this.filling = false;
+
+    this.dirty = true;
+    this.clearDirty = true;
+    this.graphicsData = [];
+
+    return this;
+};
+
+/**
+ * Useful function that returns a texture of the graphics object that can then be used to create sprites
+ * This can be quite useful if your geometry is complicated and needs to be reused multiple times.
+ *
+ * @method generateTexture
+ * @param resolution {Number} The resolution of the texture being generated
+ * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
+ * @return {Texture} a texture of the graphics object
+ */
+PIXI.Graphics.prototype.generateTexture = function(resolution, scaleMode)
+{
+    resolution = resolution || 1;
+
+    var bounds = this.getBounds();
+   
+    var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution);
+    
+    var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode);
+    texture.baseTexture.resolution = resolution;
+
+    canvasBuffer.context.scale(resolution, resolution);
+
+    canvasBuffer.context.translate(-bounds.x,-bounds.y);
+    
+    PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context);
+
+    return texture;
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method _renderWebGL
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.Graphics.prototype._renderWebGL = function(renderSession)
+{
+    // if the sprite is not visible or the alpha is 0 then no need to render this element
+    if (this.visible === false || this.alpha === 0 || this.isMask === true) return;
+
+    if (this._cacheAsBitmap)
+    {
+        if (this.dirty || this.cachedSpriteDirty)
+        {
+            this._generateCachedSprite();
+   
+            // we will also need to update the texture on the gpu too!
+            this.updateCachedSpriteTexture();
+
+            this.cachedSpriteDirty = false;
+            this.dirty = false;
+        }
+
+        this._cachedSprite.worldAlpha = this.worldAlpha;
+
+        PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
+
+        return;
+    }
+    else
+    {
+        renderSession.spriteBatch.stop();
+        renderSession.blendModeManager.setBlendMode(this.blendMode);
+
+        if (this._mask) renderSession.maskManager.pushMask(this._mask, renderSession);
+        if (this._filters) renderSession.filterManager.pushFilter(this._filterBlock);
+      
+        // check blend mode
+        if (this.blendMode !== renderSession.spriteBatch.currentBlendMode)
+        {
+            renderSession.spriteBatch.currentBlendMode = this.blendMode;
+            var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode];
+            renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
+        }
+        
+        // check if the webgl graphic needs to be updated
+        if (this.webGLDirty)
+        {
+            this.dirty = true;
+            this.webGLDirty = false;
+        }
+        
+        PIXI.WebGLGraphics.renderGraphics(this, renderSession);
+        
+        // only render if it has children!
+        if (this.children.length)
+        {
+            renderSession.spriteBatch.start();
+
+            // simple render children!
+            for (var i = 0; i < this.children.length; i++)
+            {
+                this.children[i]._renderWebGL(renderSession);
+            }
+
+            renderSession.spriteBatch.stop();
+        }
+
+        if (this._filters) renderSession.filterManager.popFilter();
+        if (this._mask) renderSession.maskManager.popMask(this.mask, renderSession);
+          
+        renderSession.drawCount++;
+
+        renderSession.spriteBatch.start();
+    }
+};
+
+/**
+* Renders the object using the Canvas renderer
+*
+* @method _renderCanvas
+* @param renderSession {RenderSession} 
+* @private
+*/
+PIXI.Graphics.prototype._renderCanvas = function(renderSession)
+{
+    // if the sprite is not visible or the alpha is 0 then no need to render this element
+    if (this.visible === false || this.alpha === 0 || this.isMask === true) return;
+
+    // if the tint has changed, set the graphics object to dirty.
+    if (this._prevTint !== this.tint) {
+        this.dirty = true;
+        this._prevTint = this.tint;
+    }
+
+    if (this._cacheAsBitmap)
+    {
+        if (this.dirty || this.cachedSpriteDirty)
+        {
+            this._generateCachedSprite();
+   
+            // we will also need to update the texture
+            this.updateCachedSpriteTexture();
+
+            this.cachedSpriteDirty = false;
+            this.dirty = false;
+        }
+
+        this._cachedSprite.alpha = this.alpha;
+        PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
+
+        return;
+    }
+    else
+    {
+        var context = renderSession.context;
+        var transform = this.worldTransform;
+        
+        if (this.blendMode !== renderSession.currentBlendMode)
+        {
+            renderSession.currentBlendMode = this.blendMode;
+            context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
+        }
+
+        if (this._mask)
+        {
+            renderSession.maskManager.pushMask(this._mask, renderSession);
+        }
+
+        var resolution = renderSession.resolution;
+
+        context.setTransform(transform.a * resolution,
+                             transform.b * resolution,
+                             transform.c * resolution,
+                             transform.d * resolution,
+                             transform.tx * resolution,
+                             transform.ty * resolution);
+
+        PIXI.CanvasGraphics.renderGraphics(this, context);
+
+         // simple render children!
+        for (var i = 0; i < this.children.length; i++)
+        {
+            this.children[i]._renderCanvas(renderSession);
+        }
+
+        if (this._mask)
+        {
+            renderSession.maskManager.popMask(renderSession);
+        }
+    }
+};
+
+/**
+ * Retrieves the bounds of the graphic shape as a rectangle object
+ *
+ * @method getBounds
+ * @return {Rectangle} the rectangular bounding area
+ */
+PIXI.Graphics.prototype.getBounds = function(matrix)
+{
+    if(!this._currentBounds)
+    {
+
+        // return an empty object if the item is a mask!
+        if (!this.renderable)
+        {
+            return PIXI.EmptyRectangle;
+        }
+
+    if (this.dirty)
+    {
+        this.updateLocalBounds();
+        this.webGLDirty = true;
+        this.cachedSpriteDirty = true;
+        this.dirty = false;
+    }
+
+    var bounds = this._localBounds;
+
+    var w0 = bounds.x;
+    var w1 = bounds.width + bounds.x;
+
+    var h0 = bounds.y;
+    var h1 = bounds.height + bounds.y;
+
+    var worldTransform = matrix || this.worldTransform;
+
+    var a = worldTransform.a;
+    var b = worldTransform.b;
+    var c = worldTransform.c;
+    var d = worldTransform.d;
+    var tx = worldTransform.tx;
+    var ty = worldTransform.ty;
+
+    var x1 = a * w1 + c * h1 + tx;
+    var y1 = d * h1 + b * w1 + ty;
+
+    var x2 = a * w0 + c * h1 + tx;
+    var y2 = d * h1 + b * w0 + ty;
+
+    var x3 = a * w0 + c * h0 + tx;
+    var y3 = d * h0 + b * w0 + ty;
+
+    var x4 =  a * w1 + c * h0 + tx;
+    var y4 =  d * h0 + b * w1 + ty;
+
+    var maxX = x1;
+    var maxY = y1;
+
+    var minX = x1;
+    var minY = y1;
+
+    minX = x2 < minX ? x2 : minX;
+    minX = x3 < minX ? x3 : minX;
+    minX = x4 < minX ? x4 : minX;
+
+    minY = y2 < minY ? y2 : minY;
+    minY = y3 < minY ? y3 : minY;
+    minY = y4 < minY ? y4 : minY;
+
+    maxX = x2 > maxX ? x2 : maxX;
+    maxX = x3 > maxX ? x3 : maxX;
+    maxX = x4 > maxX ? x4 : maxX;
+
+    maxY = y2 > maxY ? y2 : maxY;
+    maxY = y3 > maxY ? y3 : maxY;
+    maxY = y4 > maxY ? y4 : maxY;
+
+    this._bounds.x = minX;
+    this._bounds.width = maxX - minX;
+
+    this._bounds.y = minY;
+    this._bounds.height = maxY - minY;
+
+        this._currentBounds = this._bounds;
+    }
+
+    return this._currentBounds;
+};
+
+/**
+* Tests if a point is inside this graphics object
+*
+* @param point {Point} the point to test
+* @return {boolean} the result of the test
+*/
+PIXI.Graphics.prototype.containsPoint = function( point )
+{
+    this.worldTransform.applyInverse(point,  tempPoint);
+
+    var graphicsData = this.graphicsData;
+
+    for (var i = 0; i < graphicsData.length; i++)
+    {
+        var data = graphicsData[i];
+
+        if (!data.fill)
+        {
+            continue;
+        }
+
+        // only deal with fills..
+        if (data.shape)
+        {
+            if ( data.shape.contains( tempPoint.x, tempPoint.y ) )
+            {
+                return true;
+            }
+        }
+    }
+
+    return false;
+};
+
+/**
+ * Update the bounds of the object
+ *
+ * @method updateLocalBounds
+ */
+PIXI.Graphics.prototype.updateLocalBounds = function()
+{
+    var minX = Infinity;
+    var maxX = -Infinity;
+
+    var minY = Infinity;
+    var maxY = -Infinity;
+
+    if (this.graphicsData.length)
+    {
+        var shape, points, x, y, w, h;
+
+        for (var i = 0; i < this.graphicsData.length; i++)
+        {
+            var data = this.graphicsData[i];
+            var type = data.type;
+            var lineWidth = data.lineWidth;
+            shape = data.shape;
+
+            if (type === PIXI.Graphics.RECT || type === PIXI.Graphics.RREC)
+            {
+                x = shape.x - lineWidth / 2;
+                y = shape.y - lineWidth / 2;
+                w = shape.width + lineWidth;
+                h = shape.height + lineWidth;
+
+                minX = x < minX ? x : minX;
+                maxX = x + w > maxX ? x + w : maxX;
+
+                minY = y < minY ? y : minY;
+                maxY = y + h > maxY ? y + h : maxY;
+            }
+            else if (type === PIXI.Graphics.CIRC)
+            {
+                x = shape.x;
+                y = shape.y;
+                w = shape.radius + lineWidth / 2;
+                h = shape.radius + lineWidth / 2;
+
+                minX = x - w < minX ? x - w : minX;
+                maxX = x + w > maxX ? x + w : maxX;
+
+                minY = y - h < minY ? y - h : minY;
+                maxY = y + h > maxY ? y + h : maxY;
+            }
+            else if (type === PIXI.Graphics.ELIP)
+            {
+                x = shape.x;
+                y = shape.y;
+                w = shape.width + lineWidth / 2;
+                h = shape.height + lineWidth / 2;
+
+                minX = x - w < minX ? x - w : minX;
+                maxX = x + w > maxX ? x + w : maxX;
+
+                minY = y - h < minY ? y - h : minY;
+                maxY = y + h > maxY ? y + h : maxY;
+            }
+            else
+            {
+                // POLY - assumes points are sequential, not Point objects
+                points = shape.points;
+
+                for (var j = 0; j < points.length; j++)
+                {
+                    if (points[j] instanceof Phaser.Point)
+                    {
+                        x = points[j].x;
+                        y = points[j].y;
+                    }
+                    else
+                    {
+                        x = points[j];
+                        y = points[j + 1];
+
+                        if (j < points.length - 1)
+                        {
+                            j++;
+                        }
+                    }
+
+                    minX = x - lineWidth < minX ? x - lineWidth : minX;
+                    maxX = x + lineWidth > maxX ? x + lineWidth : maxX;
+
+                    minY = y - lineWidth < minY ? y - lineWidth : minY;
+                    maxY = y + lineWidth > maxY ? y + lineWidth : maxY;
+                }
+            }
+        }
+    }
+    else
+    {
+        minX = 0;
+        maxX = 0;
+        minY = 0;
+        maxY = 0;
+    }
+
+    var padding = this.boundsPadding;
+    
+    this._localBounds.x = minX - padding;
+    this._localBounds.width = (maxX - minX) + padding * 2;
+
+    this._localBounds.y = minY - padding;
+    this._localBounds.height = (maxY - minY) + padding * 2;
+};
+
+/**
+ * Generates the cached sprite when the sprite has cacheAsBitmap = true
+ *
+ * @method _generateCachedSprite
+ * @private
+ */
+PIXI.Graphics.prototype._generateCachedSprite = function()
+{
+    var bounds = this.getLocalBounds();
+
+    if (!this._cachedSprite)
+    {
+        var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
+        var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
+        
+        this._cachedSprite = new PIXI.Sprite(texture);
+        this._cachedSprite.buffer = canvasBuffer;
+
+        this._cachedSprite.worldTransform = this.worldTransform;
+    }
+    else
+    {
+        this._cachedSprite.buffer.resize(bounds.width, bounds.height);
+    }
+
+    // leverage the anchor to account for the offset of the element
+    this._cachedSprite.anchor.x = -(bounds.x / bounds.width);
+    this._cachedSprite.anchor.y = -(bounds.y / bounds.height);
+
+    // this._cachedSprite.buffer.context.save();
+    this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y);
+    
+    // make sure we set the alpha of the graphics to 1 for the render.. 
+    this.worldAlpha = 1;
+
+    // now render the graphic..
+    PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context);
+    this._cachedSprite.alpha = this.alpha;
+};
+
+/**
+ * Updates texture size based on canvas size
+ *
+ * @method updateCachedSpriteTexture
+ * @private
+ */
+PIXI.Graphics.prototype.updateCachedSpriteTexture = function()
+{
+    var cachedSprite = this._cachedSprite;
+    var texture = cachedSprite.texture;
+    var canvas = cachedSprite.buffer.canvas;
+
+    texture.baseTexture.width = canvas.width;
+    texture.baseTexture.height = canvas.height;
+    texture.crop.width = texture.frame.width = canvas.width;
+    texture.crop.height = texture.frame.height = canvas.height;
+
+    cachedSprite._width = canvas.width;
+    cachedSprite._height = canvas.height;
+
+    // update the dirty base textures
+    texture.baseTexture.dirty();
+};
+
+/**
+ * Destroys a previous cached sprite.
+ *
+ * @method destroyCachedSprite
+ */
+PIXI.Graphics.prototype.destroyCachedSprite = function()
+{
+    this._cachedSprite.texture.destroy(true);
+    this._cachedSprite = null;
+};
+
+/**
+ * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
+ *
+ * @method drawShape
+ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw.
+ * @return {GraphicsData} The generated GraphicsData object.
+ */
+PIXI.Graphics.prototype.drawShape = function(shape)
+{
+    if (this.currentPath)
+    {
+        // check current path!
+        if (this.currentPath.shape.points.length <= 2)
+        {
+            this.graphicsData.pop();
+        }
+    }
+
+    this.currentPath = null;
+
+    //  Handle mixed-type polygons
+    if (shape instanceof Phaser.Polygon)
+    {
+        shape = shape.clone();
+        shape.flatten();
+    }
+
+    var data = new PIXI.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape);
+    
+    this.graphicsData.push(data);
+
+    if (data.type === PIXI.Graphics.POLY)
+    {
+        data.shape.closed = this.filling;
+        this.currentPath = data;
+    }
+
+    this.dirty = true;
+
+    return data;
+};
+
+/**
+ * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
+ * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory.
+ * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas.
+ * This is not recommended if you are constantly redrawing the graphics element.
+ *
+ * @property cacheAsBitmap
+ * @type Boolean
+ * @default false
+ * @private
+ */
+Object.defineProperty(PIXI.Graphics.prototype, "cacheAsBitmap", {
+
+    get: function() {
+        return  this._cacheAsBitmap;
+    },
+
+    set: function(value) {
+
+        this._cacheAsBitmap = value;
+
+        if (this._cacheAsBitmap)
+        {
+            this._generateCachedSprite();
+        }
+        else
+        {
+            this.destroyCachedSprite();
+            this.dirty = true;
+        }
+
+    }
+});
+
+/**
+ * A GraphicsData object.
+ * 
+ * @class GraphicsData
+ * @constructor
+PIXI.GraphicsData = function(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape)
+{
+    this.lineWidth = lineWidth;
+    this.lineColor = lineColor;
+    this.lineAlpha = lineAlpha;
+    this._lineTint = lineColor;
+
+    this.fillColor = fillColor;
+    this.fillAlpha = fillAlpha;
+    this._fillTint = fillColor;
+    this.fill = fill;
+
+    this.shape = shape;
+    this.type = shape.type;
+};
+ */
+
+/**
+ * A GraphicsData object.
+ *
+ * @class
+ * @memberof PIXI
+ * @param lineWidth {number} the width of the line to draw
+ * @param lineColor {number} the color of the line to draw
+ * @param lineAlpha {number} the alpha of the line to draw
+ * @param fillColor {number} the color of the fill
+ * @param fillAlpha {number} the alpha of the fill
+ * @param fill      {boolean} whether or not the shape is filled with a colour
+ * @param shape     {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw.
+ */
+
+PIXI.GraphicsData = function(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) {
+
+    /*
+     * @member {number} the width of the line to draw
+     */
+    this.lineWidth = lineWidth;
+
+    /*
+     * @member {number} the color of the line to draw
+     */
+    this.lineColor = lineColor;
+
+    /*
+     * @member {number} the alpha of the line to draw
+     */
+    this.lineAlpha = lineAlpha;
+
+    /*
+     * @member {number} cached tint of the line to draw
+     */
+    this._lineTint = lineColor;
+
+    /*
+     * @member {number} the color of the fill
+     */
+    this.fillColor = fillColor;
+
+    /*
+     * @member {number} the alpha of the fill
+     */
+    this.fillAlpha = fillAlpha;
+
+    /*
+     * @member {number} cached tint of the fill
+     */
+    this._fillTint = fillColor;
+
+    /*
+     * @member {boolean} whether or not the shape is filled with a color
+     */
+    this.fill = fill;
+
+    /*
+     * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw.
+     */
+    this.shape = shape;
+
+    /*
+     * @member {number} The type of the shape, see the Const.Shapes file for all the existing types,
+     */
+    this.type = shape.type;
+
+};
+
+PIXI.GraphicsData.prototype.constructor = PIXI.GraphicsData;
+
+/**
+ * Creates a new GraphicsData object with the same values as this one.
+ *
+ * @return {GraphicsData}
+ */
+PIXI.GraphicsData.prototype.clone = function() {
+
+    return new GraphicsData(
+        this.lineWidth,
+        this.lineColor,
+        this.lineAlpha,
+        this.fillColor,
+        this.fillAlpha,
+        this.fill,
+        this.shape
+    );
+
+};
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a new `Graphics` object.
+*
+* @class Phaser.Graphics
+* @constructor
+* @extends PIXI.Graphics
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @param {Phaser.Game} game - Current game instance.
+* @param {number} [x=0] - X position of the new graphics object.
+* @param {number} [y=0] - Y position of the new graphics object.
+*/
+Phaser.Graphics = function (game, x, y) {
+
+    if (x === undefined) { x = 0; }
+    if (y === undefined) { y = 0; }
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @default
+    */
+    this.type = Phaser.GRAPHICS;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    PIXI.Graphics.call(this);
+
+    Phaser.Component.Core.init.call(this, game, x, y, '', null);
+
+};
+
+Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
+Phaser.Graphics.prototype.constructor = Phaser.Graphics;
+
+Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [
+    'Angle',
+    'AutoCull',
+    'Bounds',
+    'Destroy',
+    'FixedToCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'PhysicsBody',
+    'Reset'
+]);
+
+Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+* 
+* @method
+* @memberof Phaser.Graphics
+*/
+Phaser.Graphics.prototype.preUpdate = function () {
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Destroy this Graphics instance.
+*
+* @method Phaser.Graphics.prototype.destroy
+* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
+*/
+Phaser.Graphics.prototype.destroy = function(destroyChildren) {
+
+    this.clear();
+
+    Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
+
+};
+
+/*
+* Draws a single {Phaser.Polygon} triangle from a {Phaser.Point} array
+*
+* @method Phaser.Graphics.prototype.drawTriangle
+* @param {Array<Phaser.Point>} points - An array of Phaser.Points that make up the three vertices of this triangle
+* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
+*/
+Phaser.Graphics.prototype.drawTriangle = function(points, cull) {
+
+    if (cull === undefined) { cull = false; }
+
+    var triangle = new Phaser.Polygon(points);
+
+    if (cull)
+    {
+        var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
+        var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
+        var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
+        var faceNormal = cb.cross(ab);
+
+        if (cameraToFace.dot(faceNormal) > 0)
+        {
+            this.drawPolygon(triangle);
+        }
+    }
+    else
+    {
+        this.drawPolygon(triangle);
+    }
+
+};
+
+/*
+* Draws {Phaser.Polygon} triangles 
+*
+* @method Phaser.Graphics.prototype.drawTriangles
+* @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
+* @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
+* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
+*/
+Phaser.Graphics.prototype.drawTriangles = function(vertices, indices, cull) {
+
+    if (cull === undefined) { cull = false; }
+
+    var point1 = new Phaser.Point();
+    var point2 = new Phaser.Point();
+    var point3 = new Phaser.Point();
+    var points = [];
+    var i;
+
+    if (!indices)
+    {
+        if (vertices[0] instanceof Phaser.Point)
+        {
+            for (i = 0; i < vertices.length / 3; i++)
+            {
+                this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
+            }
+        }
+        else
+        {
+            for (i = 0; i < vertices.length / 6; i++)
+            {
+                point1.x = vertices[i * 6 + 0];
+                point1.y = vertices[i * 6 + 1];
+                point2.x = vertices[i * 6 + 2];
+                point2.y = vertices[i * 6 + 3];
+                point3.x = vertices[i * 6 + 4];
+                point3.y = vertices[i * 6 + 5];
+                this.drawTriangle([point1, point2, point3], cull);
+            }
+        }
+    }
+    else
+    {
+        if (vertices[0] instanceof Phaser.Point)
+        {
+            for (i = 0; i < indices.length /3; i++)
+            {
+                points.push(vertices[indices[i * 3 ]]);
+                points.push(vertices[indices[i * 3 + 1]]);
+                points.push(vertices[indices[i * 3 + 2]]);
+
+                if (points.length === 3)
+                {
+                    this.drawTriangle(points, cull);
+                    points = [];
+                }
+            }
+        }
+        else
+        {
+            for (i = 0; i < indices.length; i++)
+            {
+                point1.x = vertices[indices[i] * 2];
+                point1.y = vertices[indices[i] * 2 + 1];
+                points.push(point1.copyTo({}));
+
+                if (points.length === 3)
+                {
+                    this.drawTriangle(points, cull);
+                    points = [];
+                }
+            }
+        }
+    }
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and
+* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time.
+* 
+* @class Phaser.RenderTexture
+* @constructor
+* @extends PIXI.RenderTexture
+* @param {Phaser.Game} game - Current game instance.
+* @param {string} key - Internal Phaser reference key for the render texture.
+* @param {number} [width=100] - The width of the render texture.
+* @param {number} [height=100] - The height of the render texture.
+* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there.
+* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts.
+* @param {number} [resolution=1] - The resolution of the texture being generated.
+*/
+Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution) {
+
+    if (key === undefined) { key = ''; }
+    if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; }
+    if (resolution === undefined) { resolution = 1; }
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {string} key - The key of the RenderTexture in the Cache, if stored there.
+    */
+    this.key = key;
+
+    /**
+    * @property {number} type - Base Phaser object type.
+    */
+    this.type = Phaser.RENDERTEXTURE;
+
+    /**
+    * @property {PIXI.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture.
+    * @private
+    */
+    this._tempMatrix = new PIXI.Matrix();
+
+    PIXI.RenderTexture.call(this, width, height, this.game.renderer, scaleMode, resolution);
+
+    this.render = Phaser.RenderTexture.prototype.render;
+
+};
+
+Phaser.RenderTexture.prototype = Object.create(PIXI.RenderTexture.prototype);
+Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture;
+
+/**
+* This function will draw the display object to the RenderTexture at the given coordinates.
+*
+* When the display object is drawn it takes into account scale and rotation.
+*
+* If you don't want those then use RenderTexture.renderRawXY instead.
+*
+* @method Phaser.RenderTexture.prototype.renderXY
+* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
+* @param {number} x - The x position to render the object at.
+* @param {number} y - The y position to render the object at.
+* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
+*/
+Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) {
+
+    displayObject.updateTransform();
+
+    this._tempMatrix.copyFrom(displayObject.worldTransform);
+    this._tempMatrix.tx = x;
+    this._tempMatrix.ty = y;
+
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        this.renderWebGL(displayObject, this._tempMatrix, clear);
+    }
+    else
+    {
+        this.renderCanvas(displayObject, this._tempMatrix, clear);
+    }
+
+};
+
+/**
+* This function will draw the display object to the RenderTexture at the given coordinates.
+*
+* When the display object is drawn it doesn't take into account scale, rotation or translation.
+*
+* If you need those then use RenderTexture.renderXY instead.
+*
+* @method Phaser.RenderTexture.prototype.renderRawXY
+* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
+* @param {number} x - The x position to render the object at.
+* @param {number} y - The y position to render the object at.
+* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
+*/
+Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) {
+
+    this._tempMatrix.identity().translate(x, y);
+
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        this.renderWebGL(displayObject, this._tempMatrix, clear);
+    }
+    else
+    {
+        this.renderCanvas(displayObject, this._tempMatrix, clear);
+    }
+
+};
+
+/**
+* This function will draw the display object to the RenderTexture.
+*
+* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. 
+* This is now a Matrix allowing you much more control over how the Display Object is rendered.
+* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead.
+*
+* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either
+* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value.
+*
+* @method Phaser.RenderTexture.prototype.render
+* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
+* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object.
+* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
+*/
+Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) {
+
+    if (matrix === undefined || matrix === null)
+    {
+        this._tempMatrix.copyFrom(displayObject.worldTransform);
+    }
+    else
+    {
+        this._tempMatrix.copyFrom(matrix);
+    }
+
+    if (this.renderer.type === PIXI.WEBGL_RENDERER)
+    {
+        this.renderWebGL(displayObject, this._tempMatrix, clear);
+    }
+    else
+    {
+        this.renderCanvas(displayObject, this._tempMatrix, clear);
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Create a new game object for displaying Text.
+*
+* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view.
+* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded.
+*
+* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers.
+*
+* @class Phaser.Text
+* @extends Phaser.Sprite
+* @constructor
+* @param {Phaser.Game} game - Current game instance.
+* @param {number} x - X position of the new text object.
+* @param {number} y - Y position of the new text object.
+* @param {string} text - The actual text that will be written.
+* @param {object} [style] - The style properties to be set on the Text.
+* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font.
+* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`.
+* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`.
+* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`.
+* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`.
+* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable.
+* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
+* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that).
+* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
+* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
+* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'.
+* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke).
+* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used.
+* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap.
+* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop.
+*/
+Phaser.Text = function (game, x, y, text, style) {
+
+    x = x || 0;
+    y = y || 0;
+    text = text.toString() || '';
+    style = style || {};
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @default
+    */
+    this.type = Phaser.TEXT;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    /**
+    * Specify a padding value which is added to the line width and height when calculating the Text size.
+    * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions.
+    * @property {Phaser.Point} padding
+    */
+    this.padding = new Phaser.Point();
+
+    /**
+    * The textBounds property allows you to specify a rectangular region upon which text alignment is based.
+    * See `Text.setTextBounds` for more details.
+    * @property {Phaser.Rectangle} textBounds
+    * @readOnly
+    */
+    this.textBounds = null;
+
+    /**
+     * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered.
+     */
+    this.canvas = document.createElement('canvas');
+
+    /**
+     * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to.
+     */
+    this.context = this.canvas.getContext('2d');
+
+    /**
+    * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}.
+    */
+    this.colors = [];
+
+    /**
+    * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}.
+    */
+    this.strokeColors = [];
+
+    /**
+    * Should the linePositionX and Y values be automatically rounded before rendering the Text?
+    * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text.
+    * @property {boolean} autoRound
+    * @default
+    */
+    this.autoRound = false;
+
+    /**
+     * @property {number} _res - Internal canvas resolution var.
+     * @private
+     */
+    this._res = game.renderer.resolution;
+
+    /**
+    * @property {string} _text - Internal cache var.
+    * @private
+    */
+    this._text = text;
+
+    /**
+    * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`.
+    * @private
+    */
+    this._fontComponents = null;
+
+    /**
+    * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
+    * @private
+    */
+    this._lineSpacing = 0;
+
+    /**
+    * @property {number} _charCount - Internal character counter used by the text coloring.
+    * @private
+    */
+    this._charCount = 0;
+
+    /**
+    * @property {number} _width - Internal width var.
+    * @private
+    */
+    this._width = 0;
+
+    /**
+    * @property {number} _height - Internal height var.
+    * @private
+    */
+    this._height = 0;
+
+    Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas));
+
+    this.setStyle(style);
+
+    if (text !== '')
+    {
+        this.updateText();
+    }
+
+};
+
+Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype);
+Phaser.Text.prototype.constructor = Phaser.Text;
+
+/**
+* Automatically called by World.preUpdate.
+* 
+* @method Phaser.Text#preUpdate
+* @protected
+*/
+Phaser.Text.prototype.preUpdate = function () {
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Override this function to handle any special update requirements.
+*
+* @method Phaser.Text#update
+* @protected
+*/
+Phaser.Text.prototype.update = function() {
+
+};
+
+/**
+* Destroy this Text object, removing it from the group it belongs to.
+*
+* @method Phaser.Text#destroy
+* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
+*/
+Phaser.Text.prototype.destroy = function (destroyChildren) {
+
+    this.texture.destroy(true);
+
+    if (this.canvas && this.canvas.parentNode)
+    {
+        this.canvas.parentNode.removeChild(this.canvas);
+    }
+    else
+    {
+        this.canvas = null;
+        this.context = null;
+    }
+
+    Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
+
+};
+
+/**
+* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters.
+* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value.
+* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow.
+* To remove a shadow already in place you can call this method with no parameters set.
+* 
+* @method Phaser.Text#setShadow
+* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
+* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
+* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow.
+* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
+* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set).
+* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set).
+* @return {Phaser.Text} This Text instance.
+*/
+Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) {
+
+    if (x === undefined) { x = 0; }
+    if (y === undefined) { y = 0; }
+    if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; }
+    if (blur === undefined) { blur = 0; }
+    if (shadowStroke === undefined) { shadowStroke = true; }
+    if (shadowFill === undefined) { shadowFill = true; }
+
+    this.style.shadowOffsetX = x;
+    this.style.shadowOffsetY = y;
+    this.style.shadowColor = color;
+    this.style.shadowBlur = blur;
+    this.style.shadowStroke = shadowStroke;
+    this.style.shadowFill = shadowFill;
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+* Set the style of the text by passing a single style object to it.
+*
+* @method Phaser.Text#setStyle
+* @param {object} [style] - The style properties to be set on the Text.
+* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font.
+* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`.
+* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`.
+* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`.
+* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`.
+* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable.
+* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
+* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that).
+* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
+* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
+* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'.
+* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke).
+* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used.
+* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap.
+* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop.
+* @return {Phaser.Text} This Text instance.
+*/
+Phaser.Text.prototype.setStyle = function (style) {
+
+    style = style || {};
+    style.font = style.font || 'bold 20pt Arial';
+    style.backgroundColor = style.backgroundColor || null;
+    style.fill = style.fill || 'black';
+    style.align = style.align || 'left';
+    style.boundsAlignH = style.boundsAlignH || 'left';
+    style.boundsAlignV = style.boundsAlignV || 'top';
+    style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
+    style.strokeThickness = style.strokeThickness || 0;
+    style.wordWrap = style.wordWrap || false;
+    style.wordWrapWidth = style.wordWrapWidth || 100;
+    style.shadowOffsetX = style.shadowOffsetX || 0;
+    style.shadowOffsetY = style.shadowOffsetY || 0;
+    style.shadowColor = style.shadowColor || 'rgba(0,0,0,0)';
+    style.shadowBlur = style.shadowBlur || 0;
+    style.tabs = style.tabs || 0;
+
+    var components = this.fontToComponents(style.font);
+
+    if (style.fontStyle)
+    {
+        components.fontStyle = style.fontStyle;
+    }
+
+    if (style.fontVariant)
+    {
+        components.fontVariant = style.fontVariant;
+    }
+
+    if (style.fontWeight)
+    {
+        components.fontWeight = style.fontWeight;
+    }
+
+    if (style.fontSize)
+    {
+        if (typeof style.fontSize === 'number')
+        {
+            style.fontSize = style.fontSize + 'px';
+        }
+
+        components.fontSize = style.fontSize;
+    }
+
+    this._fontComponents = components;
+
+    style.font = this.componentsToFont(this._fontComponents);
+    this.style = style;
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+* Renders text. This replaces the Pixi.Text.updateText function as we need a few extra bits in here.
+*
+* @method Phaser.Text#updateText
+* @private
+*/
+Phaser.Text.prototype.updateText = function () {
+
+    this.texture.baseTexture.resolution = this._res;
+
+    this.context.font = this.style.font;
+
+    var outputText = this.text;
+
+    if (this.style.wordWrap)
+    {
+        outputText = this.runWordWrap(this.text);
+    }
+
+    //  Split text into lines
+    var lines = outputText.split(/(?:\r\n|\r|\n)/);
+
+    //  Calculate text width
+    var tabs = this.style.tabs;
+    var lineWidths = [];
+    var maxLineWidth = 0;
+    var fontProperties = this.determineFontProperties(this.style.font);
+
+    for (var i = 0; i < lines.length; i++)
+    {
+        if (tabs === 0)
+        {
+            //  Simple layout (no tabs)
+            var lineWidth = this.context.measureText(lines[i]).width + this.style.strokeThickness + this.padding.x;
+        }
+        else
+        {
+            //  Complex layout (tabs)
+            var line = lines[i].split(/(?:\t)/);
+            var lineWidth = this.padding.x + this.style.strokeThickness;
+
+            if (Array.isArray(tabs))
+            {
+                var tab = 0;
+
+                for (var c = 0; c < line.length; c++)
+                {
+                    var section = Math.ceil(this.context.measureText(line[c]).width);
+
+                    if (c > 0)
+                    {
+                        tab += tabs[c - 1];
+                    }
+
+                    lineWidth = tab + section;
+                }
+            }
+            else
+            {
+                for (var c = 0; c < line.length; c++)
+                {
+                    //  How far to the next tab?
+                    lineWidth += Math.ceil(this.context.measureText(line[c]).width);
+
+                    var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth;
+
+                    lineWidth += diff;
+                }
+            }
+        }
+
+        lineWidths[i] = Math.ceil(lineWidth);
+        maxLineWidth = Math.max(maxLineWidth, lineWidths[i]);
+    }
+
+    var width = maxLineWidth + this.style.strokeThickness;
+
+    this.canvas.width = width * this._res;
+    
+    //  Calculate text height
+    var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y;
+    var height = lineHeight * lines.length;
+    var lineSpacing = this._lineSpacing;
+
+    if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight)
+    {
+        lineSpacing = -lineHeight;
+    }
+
+    //  Adjust for line spacing
+    if (lineSpacing !== 0)
+    {
+        var diff = lineSpacing * (lines.length - 1);
+        height += diff;
+    }
+
+    this.canvas.height = height * this._res;
+
+    this.context.scale(this._res, this._res);
+
+    if (navigator.isCocoonJS)
+    {
+        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
+    }
+
+    if (this.style.backgroundColor)
+    {
+        this.context.fillStyle = this.style.backgroundColor;
+        this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
+    }
+    
+    this.context.fillStyle = this.style.fill;
+    this.context.font = this.style.font;
+    this.context.strokeStyle = this.style.stroke;
+    this.context.textBaseline = 'alphabetic';
+
+    this.context.lineWidth = this.style.strokeThickness;
+    this.context.lineCap = 'round';
+    this.context.lineJoin = 'round';
+
+    var linePositionX;
+    var linePositionY;
+
+    this._charCount = 0;
+
+    //  Draw text line by line
+    for (i = 0; i < lines.length; i++)
+    {
+        //  Split the line by
+
+        linePositionX = this.style.strokeThickness / 2;
+        linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
+
+        if (i > 0)
+        {
+            linePositionY += (lineSpacing * i);
+        }
+
+        if (this.style.align === 'right')
+        {
+            linePositionX += maxLineWidth - lineWidths[i];
+        }
+        else if (this.style.align === 'center')
+        {
+            linePositionX += (maxLineWidth - lineWidths[i]) / 2;
+        }
+
+        if (this.autoRound)
+        {
+            linePositionX = Math.round(linePositionX);
+            linePositionY = Math.round(linePositionY);
+        }
+
+        if (this.colors.length > 0 || this.strokeColors.length > 0)
+        {
+            this.updateLine(lines[i], linePositionX, linePositionY);
+        }
+        else
+        {
+            if (this.style.stroke && this.style.strokeThickness)
+            {
+                this.updateShadow(this.style.shadowStroke);
+
+                if (tabs === 0)
+                {
+                    this.context.strokeText(lines[i], linePositionX, linePositionY);
+                }
+                else
+                {
+                    this.renderTabLine(lines[i], linePositionX, linePositionY, false);
+                }
+            }
+
+            if (this.style.fill)
+            {
+                this.updateShadow(this.style.shadowFill);
+
+                if (tabs === 0)
+                {
+                    this.context.fillText(lines[i], linePositionX, linePositionY);
+                }
+                else
+                {
+                    this.renderTabLine(lines[i], linePositionX, linePositionY, true);
+                }
+            }
+        }
+    }
+
+    this.updateTexture();
+
+};
+
+/**
+* Renders a line of text that contains tab characters if Text.tab > 0.
+* Called automatically by updateText.
+*
+* @method Phaser.Text#renderTabLine
+* @private
+* @param {string} line - The line of text to render.
+* @param {integer} x - The x position to start rendering from.
+* @param {integer} y - The y position to start rendering from.
+* @param {boolean} fill - If true uses fillText, if false uses strokeText.
+*/
+Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) {
+
+    var text = line.split(/(?:\t)/);
+    var tabs = this.style.tabs;
+    var snap = 0;
+
+    if (Array.isArray(tabs))
+    {
+        var tab = 0;
+
+        for (var c = 0; c < text.length; c++)
+        {
+            if (c > 0)
+            {
+                tab += tabs[c - 1];
+            }
+
+            snap = x + tab;
+
+            if (fill)
+            {
+                this.context.fillText(text[c], snap, y);
+            }
+            else
+            {
+                this.context.strokeText(text[c], snap, y);
+            }
+        }
+    }
+    else
+    {
+        for (var c = 0; c < text.length; c++)
+        {
+            var section = Math.ceil(this.context.measureText(text[c]).width);
+
+            //  How far to the next tab?
+            snap = this.game.math.snapToCeil(x, tabs);
+
+            if (fill)
+            {
+                this.context.fillText(text[c], snap, y);
+            }
+            else
+            {
+                this.context.strokeText(text[c], snap, y);
+            }
+
+            x = snap + section;
+        }
+    }
+
+};
+
+/**
+* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled.
+* This is called automatically by Text.updateText.
+*
+* @method Phaser.Text#updateShadow
+* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero.
+*/
+Phaser.Text.prototype.updateShadow = function (state) {
+
+    if (state)
+    {
+        this.context.shadowOffsetX = this.style.shadowOffsetX;
+        this.context.shadowOffsetY = this.style.shadowOffsetY;
+        this.context.shadowColor = this.style.shadowColor;
+        this.context.shadowBlur = this.style.shadowBlur;
+    }
+    else
+    {
+        this.context.shadowOffsetX = 0;
+        this.context.shadowOffsetY = 0;
+        this.context.shadowColor = 0;
+        this.context.shadowBlur = 0;
+    }
+
+};
+
+/**
+* Updates a line of text, applying fill and stroke per-character colors if applicable.
+*
+* @method Phaser.Text#updateLine
+* @private
+*/
+Phaser.Text.prototype.updateLine = function (line, x, y) {
+
+    for (var i = 0; i < line.length; i++)
+    {
+        var letter = line[i];
+
+        if (this.style.stroke && this.style.strokeThickness)
+        {
+            if (this.strokeColors[this._charCount])
+            {
+                this.context.strokeStyle = this.strokeColors[this._charCount];
+            }
+
+            this.updateShadow(this.style.shadowStroke);
+            this.context.strokeText(letter, x, y);
+        }
+
+        if (this.style.fill)
+        {
+            if (this.colors[this._charCount])
+            {
+                this.context.fillStyle = this.colors[this._charCount];
+            }
+
+            this.updateShadow(this.style.shadowFill);
+            this.context.fillText(letter, x, y);
+        }
+
+        x += this.context.measureText(letter).width;
+
+        this._charCount++;
+    }
+
+};
+
+/**
+* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`.
+*
+* @method Phaser.Text#clearColors
+* @return {Phaser.Text} This Text instance.
+*/
+Phaser.Text.prototype.clearColors = function () {
+
+    this.colors = [];
+    this.strokeColors = [];
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+* Set specific colors for certain characters within the Text.
+*
+* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position.
+* The position value is the index of the character in the Text string to start applying this color to.
+* Once set the color remains in use until either another color or the end of the string is encountered.
+* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow.
+*
+* If you wish to change the stroke color see addStrokeColor instead.
+*
+* @method Phaser.Text#addColor
+* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`.
+* @param {number} position - The index of the character in the string to start applying this color value from.
+* @return {Phaser.Text} This Text instance.
+*/
+Phaser.Text.prototype.addColor = function (color, position) {
+
+    this.colors[position] = color;
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+* Set specific stroke colors for certain characters within the Text.
+*
+* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position.
+* The position value is the index of the character in the Text string to start applying this color to.
+* Once set the color remains in use until either another color or the end of the string is encountered.
+* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow.
+*
+* This has no effect if stroke is disabled or has a thickness of 0.
+*
+* If you wish to change the text fill color see addColor instead.
+*
+* @method Phaser.Text#addStrokeColor
+* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`.
+* @param {number} position - The index of the character in the string to start applying this color value from.
+* @return {Phaser.Text} This Text instance.
+*/
+Phaser.Text.prototype.addStrokeColor = function (color, position) {
+
+    this.strokeColors[position] = color;
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
+*
+* @method Phaser.Text#runWordWrap
+* @param {string} text - The text to perform word wrap detection against.
+* @private
+*/
+Phaser.Text.prototype.runWordWrap = function (text) {
+
+    var result = '';
+    var lines = text.split('\n');
+
+    for (var i = 0; i < lines.length; i++)
+    {
+        var spaceLeft = this.style.wordWrapWidth;
+        var words = lines[i].split(' ');
+
+        for (var j = 0; j < words.length; j++)
+        {
+            var wordWidth = this.context.measureText(words[j]).width;
+            var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
+
+            if (wordWidthWithSpace > spaceLeft)
+            {
+                // Skip printing the newline if it's the first word of the line that is greater than the word wrap width.
+                if (j > 0)
+                {
+                    result += '\n';
+                }
+                result += words[j] + ' ';
+                spaceLeft = this.style.wordWrapWidth - wordWidth;
+            }
+            else
+            {
+                spaceLeft -= wordWidthWithSpace;
+                result += words[j] + ' ';
+            }
+        }
+
+        if (i < lines.length-1)
+        {
+            result += '\n';
+        }
+    }
+
+    return result;
+
+};
+
+/**
+* Updates the internal `style.font` if it now differs according to generation from components.
+*
+* @method Phaser.Text#updateFont
+* @private
+* @param {object} components - Font components.
+*/
+Phaser.Text.prototype.updateFont = function (components) {
+
+    var font = this.componentsToFont(components);
+
+    if (this.style.font !== font)
+    {
+        this.style.font = font;
+        this.dirty = true;
+
+        if (this.parent)
+        {
+            this.updateTransform();
+        }
+    }
+
+};
+
+/**
+* Converting a short CSS-font string into the relevant components.
+*
+* @method Phaser.Text#fontToComponents
+* @private
+* @param {string} font - a CSS font string
+*/
+Phaser.Text.prototype.fontToComponents = function (font) {
+
+    // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand:
+    // style - normal | italic | oblique | inherit
+    // variant - normal | small-caps | inherit
+    // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit
+    // size - xx-small | x-small | small | medium | large | x-large | xx-large,
+    //        larger | smaller
+    //        {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %)
+    // font-family - rest (but identifiers or quoted with comma separation)
+    var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);
+
+    if (m)
+    {
+        return {
+            font: font,
+            fontStyle: m[1] || 'normal',
+            fontVariant: m[2] || 'normal',
+            fontWeight: m[3] || 'normal',
+            fontSize: m[4] || 'medium',
+            fontFamily: m[5]
+        };
+    }
+    else
+    {
+        console.warn("Phaser.Text - unparsable CSS font: " + font);
+        return {
+            font: font
+        };
+    }
+
+};
+
+/**
+* Converts individual font components (see `fontToComponents`) to a short CSS font string.
+*
+* @method Phaser.Text#componentsToFont
+* @private
+* @param {object} components - Font components.
+*/
+Phaser.Text.prototype.componentsToFont = function (components) {
+
+    var parts = [];
+    var v;
+
+    v = components.fontStyle;
+    if (v && v !== 'normal') { parts.push(v); }
+
+    v = components.fontVariant;
+    if (v && v !== 'normal') { parts.push(v); }
+
+    v = components.fontWeight;
+    if (v && v !== 'normal') { parts.push(v); }
+
+    v = components.fontSize;
+    if (v && v !== 'medium') { parts.push(v); }
+
+    v = components.fontFamily;
+    if (v) { parts.push(v); }
+
+    if (!parts.length)
+    {
+        // Fallback to whatever value the 'font' was
+        parts.push(components.font);
+    }
+
+    return parts.join(" ");
+
+};
+
+/**
+ * The text to be displayed by this Text object.
+ * Use a \n to insert a carriage return and split the text.
+ * The text will be rendered with any style currently set.
+ *
+ * @method Phaser.Text#setText
+ * @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present.
+ * @return {Phaser.Text} This Text instance.
+ */
+Phaser.Text.prototype.setText = function (text) {
+
+    this.text = text.toString() || '';
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+ * Converts the given array into a tab delimited string and then updates this Text object.
+ * This is mostly used when you want to display external data using tab stops.
+ *
+ * The array can be either single or multi dimensional depending on the result you need:
+ *
+ * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`.
+ *
+ * Where as:
+ *
+ * `[
+ *      [ 'a', 'b', 'c' ],
+ *      [ 'd', 'e', 'f']
+ * ]`
+ *
+ * would convert in to: `"a\tb\tc\nd\te\tf"`
+ *
+ * @method Phaser.Text#parseList
+ * @param {array} list - The array of data to convert into a string.
+ * @return {Phaser.Text} This Text instance.
+ */
+Phaser.Text.prototype.parseList = function (list) {
+
+    if (!Array.isArray(list))
+    {
+        return this;
+    }
+    else
+    {
+        var s = "";
+
+        for (var i = 0; i < list.length; i++)
+        {
+            if (Array.isArray(list[i]))
+            {
+                s += list[i].join("\t");
+
+                if (i < list.length - 1)
+                {
+                    s += "\n";
+                }
+            }
+            else
+            {
+                s += list[i];
+
+                if (i < list.length - 1)
+                {
+                    s += "\t";
+                }
+            }
+        }
+    }
+
+    this.text = s;
+    this.dirty = true;
+
+    return this;
+
+};
+
+/**
+ * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned,
+ * regardless of the number of lines in the text, the font size or any other attribute.
+ *
+ * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly
+ * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment.
+ *
+ * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to
+ * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of
+ * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center
+ * of the text bounds.
+ *
+ * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions
+ * may vary based on font (say for multi-lingual games).
+ *
+ * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width.
+ *
+ * Call this method with no arguments given to reset an existing textBounds.
+ * 
+ * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts
+ * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot`
+ * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then
+ * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot.
+ *
+ * @method Phaser.Text#setTextBounds
+ * @param {number} [x] - The x coordinate of the Text Bounds region.
+ * @param {number} [y] - The y coordinate of the Text Bounds region.
+ * @param {number} [width] - The width of the Text Bounds region.
+ * @param {number} [height] - The height of the Text Bounds region.
+ * @return {Phaser.Text} This Text instance.
+ */
+Phaser.Text.prototype.setTextBounds = function (x, y, width, height) {
+
+    if (x === undefined)
+    {
+        this.textBounds = null;
+    }
+    else
+    {
+        if (!this.textBounds)
+        {
+            this.textBounds = new Phaser.Rectangle(x, y, width, height);
+        }
+        else
+        {
+            this.textBounds.setTo(x, y, width, height);
+        }
+
+        if (this.style.wordWrapWidth > width)
+        {
+            this.style.wordWrapWidth = width;
+        }
+    }
+
+    this.updateTexture();
+    
+    return this;
+
+};
+
+/**
+ * Updates the texture based on the canvas dimensions.
+ *
+ * @method Phaser.Text#updateTexture
+ * @private
+ */
+Phaser.Text.prototype.updateTexture = function () {
+
+    var base = this.texture.baseTexture;
+    var crop = this.texture.crop;
+    var frame = this.texture.frame;
+
+    var w = this.canvas.width;
+    var h = this.canvas.height;
+
+    base.width = w;
+    base.height = h;
+
+    crop.width = w;
+    crop.height = h;
+
+    frame.width = w;
+    frame.height = h;
+
+    this.texture.width = w;
+    this.texture.height = h;
+
+    this._width = w;
+    this._height = h;
+
+    if (this.textBounds)
+    {
+        var x = this.textBounds.x;
+        var y = this.textBounds.y;
+
+        //  Align the canvas based on the bounds
+        if (this.style.boundsAlignH === 'right')
+        {
+            x = this.textBounds.width - this.canvas.width;
+        }
+        else if (this.style.boundsAlignH === 'center')
+        {
+            x = this.textBounds.halfWidth - (this.canvas.width / 2);
+        }
+
+        if (this.style.boundsAlignV === 'bottom')
+        {
+            y = this.textBounds.height - this.canvas.height;
+        }
+        else if (this.style.boundsAlignV === 'middle')
+        {
+            y = this.textBounds.halfHeight - (this.canvas.height / 2);
+        }
+
+        this.pivot.x = -x;
+        this.pivot.y = -y;
+    }
+
+    //  Can't render something with a zero sized dimension
+    this.renderable = (w !== 0 && h !== 0);
+
+    this.texture.baseTexture.dirty();
+
+};
+
+/**
+* Renders the object using the WebGL renderer
+*
+* @method Phaser.Text#_renderWebGL
+* @private
+* @param {RenderSession} renderSession - The Render Session to render the Text on.
+*/
+Phaser.Text.prototype._renderWebGL = function (renderSession) {
+
+    if (this.dirty)
+    {
+        this.updateText();
+        this.dirty = false;
+    }
+
+    PIXI.Sprite.prototype._renderWebGL.call(this, renderSession);
+
+};
+
+/**
+* Renders the object using the Canvas renderer.
+*
+* @method Phaser.Text#_renderCanvas
+* @private
+* @param {RenderSession} renderSession - The Render Session to render the Text on.
+*/
+Phaser.Text.prototype._renderCanvas = function (renderSession) {
+
+    if (this.dirty)
+    {
+        this.updateText();
+        this.dirty = false;
+    }
+     
+    PIXI.Sprite.prototype._renderCanvas.call(this, renderSession);
+
+};
+
+/**
+* Calculates the ascent, descent and fontSize of a given font style.
+*
+* @method Phaser.Text#determineFontProperties
+* @private
+* @param {object} fontStyle 
+*/
+Phaser.Text.prototype.determineFontProperties = function (fontStyle) {
+
+    var properties = Phaser.Text.fontPropertiesCache[fontStyle];
+
+    if (!properties)
+    {
+        properties = {};
+        
+        var canvas = Phaser.Text.fontPropertiesCanvas;
+        var context = Phaser.Text.fontPropertiesContext;
+
+        context.font = fontStyle;
+
+        var width = Math.ceil(context.measureText('|MÉq').width);
+        var baseline = Math.ceil(context.measureText('|MÉq').width);
+        var height = 2 * baseline;
+
+        baseline = baseline * 1.4 | 0;
+
+        canvas.width = width;
+        canvas.height = height;
+
+        context.fillStyle = '#f00';
+        context.fillRect(0, 0, width, height);
+
+        context.font = fontStyle;
+
+        context.textBaseline = 'alphabetic';
+        context.fillStyle = '#000';
+        context.fillText('|MÉq', 0, baseline);
+
+        if (!context.getImageData(0, 0, width, height))
+        {
+            properties.ascent = baseline;
+            properties.descent = baseline + 6;
+            properties.fontSize = properties.ascent + properties.descent;
+
+            Phaser.Text.fontPropertiesCache[fontStyle] = properties;
+
+            return properties;
+        }
+
+        var imagedata = context.getImageData(0, 0, width, height).data;
+        var pixels = imagedata.length;
+        var line = width * 4;
+
+        var i, j;
+
+        var idx = 0;
+        var stop = false;
+
+        // ascent. scan from top to bottom until we find a non red pixel
+        for (i = 0; i < baseline; i++)
+        {
+            for (j = 0; j < line; j += 4)
+            {
+                if (imagedata[idx + j] !== 255)
+                {
+                    stop = true;
+                    break;
+                }
+            }
+
+            if (!stop)
+            {
+                idx += line;
+            }
+            else
+            {
+                break;
+            }
+        }
+
+        properties.ascent = baseline - i;
+
+        idx = pixels - line;
+        stop = false;
+
+        // descent. scan from bottom to top until we find a non red pixel
+        for (i = height; i > baseline; i--)
+        {
+            for (j = 0; j < line; j += 4)
+            {
+                if (imagedata[idx + j] !== 255)
+                {
+                    stop = true;
+                    break;
+                }
+            }
+
+            if (!stop)
+            {
+                idx -= line;
+            }
+            else
+            {
+                break;
+            }
+        }
+
+        properties.descent = i - baseline;
+        //TODO might need a tweak. kind of a temp fix!
+        properties.descent += 6;
+        properties.fontSize = properties.ascent + properties.descent;
+
+        Phaser.Text.fontPropertiesCache[fontStyle] = properties;
+    }
+
+    return properties;
+
+};
+
+/**
+* Returns the bounds of the Text as a rectangle.
+* The bounds calculation takes the worldTransform into account.
+*
+* @method Phaser.Text#getBounds
+* @param {Phaser.Matrix} matrix - The transformation matrix of the Text.
+* @return {Phaser.Rectangle} The framing rectangle
+*/
+Phaser.Text.prototype.getBounds = function (matrix) {
+
+    if (this.dirty)
+    {
+        this.updateText();
+        this.dirty = false;
+    }
+
+    return PIXI.Sprite.prototype.getBounds.call(this, matrix);
+
+};
+
+/**
+* The text to be displayed by this Text object.
+* Use a \n to insert a carriage return and split the text.
+* The text will be rendered with any style currently set.
+*
+* @name Phaser.Text#text
+* @property {string} text
+*/
+Object.defineProperty(Phaser.Text.prototype, 'text', {
+
+    get: function() {
+        return this._text;
+    },
+
+    set: function(value) {
+
+        if (value !== this._text)
+        {
+            this._text = value.toString() || '';
+            this.dirty = true;
+
+            if (this.parent)
+            {
+                this.updateTransform();
+            }
+        }
+
+    }
+
+});
+
+/**
+* Change the font used.
+*
+* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except
+* that unlike using `setStyle` this will not change any current font fill/color settings.
+*
+* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties.
+*
+* @name Phaser.Text#cssFont
+* @property {string} cssFont
+*/
+Object.defineProperty(Phaser.Text.prototype, 'cssFont', {
+
+    get: function() {
+        return this.componentsToFont(this._fontComponents);
+    },
+
+    set: function (value)
+    {
+        value = value || 'bold 20pt Arial';
+        this._fontComponents = this.fontToComponents(value);
+        this.updateFont(this._fontComponents);
+    }
+
+});
+
+/**
+* Change the font family that the text will be rendered in, such as 'Arial'.
+*
+* Multiple CSS font families and generic fallbacks can be specified as long as
+* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed.
+*
+* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`.
+*
+* @name Phaser.Text#font
+* @property {string} font
+*/
+Object.defineProperty(Phaser.Text.prototype, 'font', {
+
+    get: function() {
+        return this._fontComponents.fontFamily;
+    },
+
+    set: function(value) {
+
+        value = value || 'Arial';
+        value = value.trim();
+
+        // If it looks like the value should be quoted, but isn't, then quote it.
+        if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value))
+        {
+            value = "'" + value + "'";
+        }
+
+        this._fontComponents.fontFamily = value;
+        this.updateFont(this._fontComponents);
+
+    }
+
+});
+
+/**
+* The size of the font.
+*
+* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing
+* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`).
+*
+* @name Phaser.Text#fontSize
+* @property {number|string} fontSize
+*/
+Object.defineProperty(Phaser.Text.prototype, 'fontSize', {
+
+    get: function() {
+
+        var size = this._fontComponents.fontSize;
+
+        if (size && /(?:^0$|px$)/.exec(size))
+        {
+            return parseInt(size, 10);
+        }
+        else
+        {
+            return size;
+        }
+
+    },
+
+    set: function(value) {
+
+        value = value || '0';
+        
+        if (typeof value === 'number')
+        {
+            value = value + 'px';
+        }
+
+        this._fontComponents.fontSize = value;
+        this.updateFont(this._fontComponents);
+
+    }
+
+});
+
+/**
+* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}.
+* @name Phaser.Text#fontWeight
+* @property {string} fontWeight
+*/
+Object.defineProperty(Phaser.Text.prototype, 'fontWeight', {
+
+    get: function() {
+        return this._fontComponents.fontWeight || 'normal';
+    },
+
+    set: function(value) {
+
+        value = value || 'normal';
+        this._fontComponents.fontWeight = value;
+        this.updateFont(this._fontComponents);
+
+    }
+
+});
+
+/**
+* The style of the font: 'normal', 'italic', 'oblique'
+* @name Phaser.Text#fontStyle
+* @property {string} fontStyle
+*/
+Object.defineProperty(Phaser.Text.prototype, 'fontStyle', {
+
+    get: function() {
+        return this._fontComponents.fontStyle || 'normal';
+    },
+
+    set: function(value) {
+
+        value = value || 'normal';
+        this._fontComponents.fontStyle = value;
+        this.updateFont(this._fontComponents);
+
+    }
+
+});
+
+/**
+* The variant the font: 'normal', 'small-caps'
+* @name Phaser.Text#fontVariant
+* @property {string} fontVariant
+*/
+Object.defineProperty(Phaser.Text.prototype, 'fontVariant', {
+
+    get: function() {
+        return this._fontComponents.fontVariant || 'normal';
+    },
+
+    set: function(value) {
+
+        value = value || 'normal';
+        this._fontComponents.fontVariant = value;
+        this.updateFont(this._fontComponents);
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#fill
+* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'fill', {
+
+    get: function() {
+        return this.style.fill;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.fill)
+        {
+            this.style.fill = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* Controls the horizontal alignment for multiline text.
+* Can be: 'left', 'center' or 'right'.
+* Does not affect single lines of text. For that please see `setTextBounds`.
+* @name Phaser.Text#align
+* @property {string} align
+*/
+Object.defineProperty(Phaser.Text.prototype, 'align', {
+
+    get: function() {
+        return this.style.align;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.align)
+        {
+            this.style.align = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* The resolution of the canvas the text is rendered to.
+* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis.
+* @name Phaser.Text#resolution
+* @property {integer} resolution
+*/
+Object.defineProperty(Phaser.Text.prototype, 'resolution', {
+
+    get: function() {
+        return this._res;
+    },
+
+    set: function(value) {
+
+        if (value !== this._res)
+        {
+            this._res = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. 
+* Can be an integer or an array of varying tab sizes, one tab per element.
+* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels.
+* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px.
+* 
+* @name Phaser.Text#tabs
+* @property {integer|array} tabs
+*/
+Object.defineProperty(Phaser.Text.prototype, 'tabs', {
+
+    get: function() {
+        return this.style.tabs;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.tabs)
+        {
+            this.style.tabs = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
+* @name Phaser.Text#boundsAlignH
+* @property {string} boundsAlignH
+*/
+Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', {
+
+    get: function() {
+        return this.style.boundsAlignH;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.boundsAlignH)
+        {
+            this.style.boundsAlignH = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
+* @name Phaser.Text#boundsAlignV
+* @property {string} boundsAlignV
+*/
+Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', {
+
+    get: function() {
+        return this.style.boundsAlignV;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.boundsAlignV)
+        {
+            this.style.boundsAlignV = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#stroke
+* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'stroke', {
+
+    get: function() {
+        return this.style.stroke;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.stroke)
+        {
+            this.style.stroke = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#strokeThickness
+* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke)
+*/
+Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', {
+
+    get: function() {
+        return this.style.strokeThickness;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.strokeThickness)
+        {
+            this.style.strokeThickness = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#wordWrap
+* @property {boolean} wordWrap - Indicates if word wrap should be used.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'wordWrap', {
+
+    get: function() {
+        return this.style.wordWrap;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.wordWrap)
+        {
+            this.style.wordWrap = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#wordWrapWidth
+* @property {number} wordWrapWidth - The width at which text will wrap.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', {
+
+    get: function() {
+        return this.style.wordWrapWidth;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.wordWrapWidth)
+        {
+            this.style.wordWrapWidth = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#lineSpacing
+* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', {
+
+    get: function() {
+        return this._lineSpacing;
+    },
+
+    set: function(value) {
+
+        if (value !== this._lineSpacing)
+        {
+            this._lineSpacing = parseFloat(value);
+            this.dirty = true;
+
+            if (this.parent)
+            {
+                this.updateTransform();
+            }
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#shadowOffsetX
+* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', {
+
+    get: function() {
+        return this.style.shadowOffsetX;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.shadowOffsetX)
+        {
+            this.style.shadowOffsetX = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#shadowOffsetY
+* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', {
+
+    get: function() {
+        return this.style.shadowOffsetY;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.shadowOffsetY)
+        {
+            this.style.shadowOffsetY = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#shadowColor
+* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'shadowColor', {
+
+    get: function() {
+        return this.style.shadowColor;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.shadowColor)
+        {
+            this.style.shadowColor = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#shadowBlur
+* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
+*/
+Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', {
+
+    get: function() {
+        return this.style.shadowBlur;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.shadowBlur)
+        {
+            this.style.shadowBlur = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#shadowStroke
+* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', {
+
+    get: function() {
+        return this.style.shadowStroke;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.shadowStroke)
+        {
+            this.style.shadowStroke = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#shadowFill
+* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'shadowFill', {
+
+    get: function() {
+        return this.style.shadowFill;
+    },
+
+    set: function(value) {
+
+        if (value !== this.style.shadowFill)
+        {
+            this.style.shadowFill = value;
+            this.dirty = true;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Text#width
+* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'width', {
+
+    get: function() {
+
+        if (this.dirty)
+        {
+            this.updateText();
+            this.dirty = false;
+        }
+
+        return this.scale.x * this.texture.frame.width;
+    },
+
+    set: function(value) {
+
+        this.scale.x = value / this.texture.frame.width;
+        this._width = value;
+    }
+
+});
+
+/**
+* @name Phaser.Text#height
+* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested.
+*/
+Object.defineProperty(Phaser.Text.prototype, 'height', {
+
+    get: function() {
+
+        if (this.dirty)
+        {
+            this.updateText();
+            this.dirty = false;
+        }
+
+        return this.scale.y * this.texture.frame.height;
+    },
+
+    set: function(value) {
+
+        this.scale.y = value / this.texture.frame.height;
+        this._height = value;
+    }
+
+});
+
+Phaser.Text.fontPropertiesCache = {};
+
+Phaser.Text.fontPropertiesCanvas = document.createElement('canvas');
+Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d');
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
+* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to 
+* match the font structure.
+* 
+* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability 
+* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
+* processing the font texture in an image editor, applying fills and any other effects required.
+*
+* To create multi-line text insert \r, \n or \r\n escape codes into the text string.
+*
+* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly
+* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText.
+*
+* To create a BitmapText data files you can use:
+*
+* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
+* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
+* Littera (Web-based, free): http://kvazars.com/littera/
+*
+* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
+* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson
+*
+* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer.
+*
+* @class Phaser.BitmapText
+* @constructor
+* @extends PIXI.DisplayObjectContainer
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - X coordinate to display the BitmapText object at.
+* @param {number} y - Y coordinate to display the BitmapText object at.
+* @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
+* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
+* @param {number} [size=32] - The size the font will be rendered at in pixels.
+* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text.
+*/
+Phaser.BitmapText = function (game, x, y, font, text, size, align) {
+
+    x = x || 0;
+    y = y || 0;
+    font = font || '';
+    text = text || '';
+    size = size || 32;
+    align = align || 'left';
+
+    PIXI.DisplayObjectContainer.call(this);
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.BITMAPTEXT;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    /**
+    * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text.
+    * @readOnly
+    */
+    this.textWidth = 0;
+
+    /**
+    * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text.
+    * @readOnly
+    */
+    this.textHeight = 0;
+
+    /**
+    * @property {Phaser.Point} anchor - The anchor value of this BitmapText.
+    */
+    this.anchor = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} _prevAnchor - The previous anchor value.
+    * @private
+    */
+    this._prevAnchor = new Phaser.Point();
+
+    /**
+    * @property {array} _glyphs - Private tracker for the letter sprite pool.
+    * @private
+    */
+    this._glyphs = [];
+
+    /**
+    * @property {number} _maxWidth - Internal cache var.
+    * @private
+    */
+    this._maxWidth = 0;
+
+    /**
+    * @property {string} _text - Internal cache var.
+    * @private
+    */
+    this._text = text;
+
+    /**
+    * @property {string} _data - Internal cache var.
+    * @private
+    */
+    this._data = game.cache.getBitmapFont(font);
+
+    /**
+    * @property {string} _font - Internal cache var.
+    * @private
+    */
+    this._font = font;
+
+    /**
+    * @property {number} _fontSize - Internal cache var.
+    * @private
+    */
+    this._fontSize = size;
+
+    /**
+    * @property {string} _align - Internal cache var.
+    * @private
+    */
+    this._align = align;
+
+    /**
+    * @property {number} _tint - Internal cache var.
+    * @private
+    */
+    this._tint = 0xFFFFFF;
+
+    this.updateText();
+
+    /**
+    * @property {boolean} dirty - The dirty state of this object.
+    */
+    this.dirty = false;
+
+    Phaser.Component.Core.init.call(this, game, x, y, '', null);
+
+};
+
+Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
+Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
+
+Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [
+    'Angle',
+    'AutoCull',
+    'Bounds',
+    'Destroy',
+    'FixedToCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'PhysicsBody',
+    'Reset'
+]);
+
+Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method
+* @memberof Phaser.BitmapText
+* @return {boolean} True if the BitmapText was rendered, otherwise false.
+*/
+Phaser.BitmapText.prototype.preUpdate = function () {
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Automatically called by World.preUpdate.
+* @method Phaser.BitmapText.prototype.postUpdate
+*/
+Phaser.BitmapText.prototype.postUpdate = function () {
+
+    Phaser.Component.PhysicsBody.postUpdate.call(this);
+    Phaser.Component.FixedToCamera.postUpdate.call(this);
+
+    if (this.body && this.body.type === Phaser.Physics.ARCADE)
+    {
+        if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight))
+        {
+            this.body.setSize(this.textWidth, this.textHeight);
+        }
+    }
+
+};
+
+/**
+* The text to be displayed by this BitmapText object.
+* 
+* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility.
+*
+* @method Phaser.BitmapText.prototype.setText
+* @param {string} text - The text to be displayed by this BitmapText object.
+*/
+Phaser.BitmapText.prototype.setText = function (text) {
+
+    this.text = text;
+
+};
+
+/**
+* Given the input text this will scan the characters until either a newline is encountered, 
+* or the line exceeds maxWidth, taking into account kerning, character widths and scaling.
+* 
+* @method Phaser.BitmapText.prototype.scanLine
+* @private
+* @param {object} data - A reference to the font object in the Phaser.Cache.
+* @param {float} scale - The scale of the font in relation to the texture.
+* @param {string} text - The text to parse.
+* @return {object} An object containing the parsed characters, total pixel width and x offsets.
+*/
+Phaser.BitmapText.prototype.scanLine = function (data, scale, text) {
+
+    var x = 0;
+    var w = 0;
+    var lastSpace = -1;
+    var prevCharCode = null;
+    var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null;
+    var chars = [];
+
+    //  Let's scan the text and work out if any of the lines are > maxWidth
+    for (var i = 0; i < text.length; i++)
+    {
+        var end = (i === text.length - 1) ? true : false;
+
+        if (/(?:\r\n|\r|\n)/.test(text.charAt(i)))
+        {
+            return { width: w, text: text.substr(0, i), end: end, chars: chars };
+        }
+        else
+        {
+            var charCode = text.charCodeAt(i);
+            var charData = data.chars[charCode];
+
+            var c = 0;
+
+            if (!charData)
+            {
+                // Skip a character not found in the font data
+                continue;
+            }
+
+            //  Adjust for kerning from previous character to this one
+            var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0;
+
+            //  Record the last space in the string
+            lastSpace = /(\s)/.test(text.charAt(i)) ? i : lastSpace;
+
+            //  What will the line width be if we add this character to it?
+            c = (kerning + charData.texture.width + charData.xOffset) * scale;
+
+            //  Do we need to line-wrap?
+            if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1)
+            {
+                //  The last space was at "lastSpace" which was "i - lastSpace" characters ago
+                return { width: w, text: text.substr(0, i - (i - lastSpace)), end: end, chars: chars };
+            }
+            else
+            {
+                w += charData.xAdvance * scale;
+
+                chars.push(x + (charData.xOffset * scale));
+
+                x += charData.xAdvance * scale;
+
+                prevCharCode = charCode;
+            }
+        }
+    }
+
+    return { width: w, text: text, end: end, chars: chars };
+
+};
+
+/**
+* Renders text and updates it when needed.
+*
+* @method Phaser.BitmapText.prototype.updateText
+* @private
+*/
+Phaser.BitmapText.prototype.updateText = function () {
+
+    var data = this._data.font;
+
+    if (!data)
+    {
+        return;
+    }
+
+    var text = this.text;
+    var scale = this._fontSize / data.size;
+    var lines = [];
+
+    var y = 0;
+
+    this.textWidth = 0;
+
+    do
+    {
+        var line = this.scanLine(data, scale, text);
+
+        line.y = y;
+
+        lines.push(line);
+
+        if (line.width > this.textWidth)
+        {
+            this.textWidth = line.width;
+        }
+
+        y += (data.lineHeight * scale);
+
+        text = text.substr(line.text.length + 1);
+        
+    } while (line.end === false);
+
+    this.textHeight = y;
+
+    var t = 0;
+    var align = 0;
+    var ax = this.textWidth * this.anchor.x;
+    var ay = this.textHeight * this.anchor.y;
+
+    for (var i = 0; i < lines.length; i++)
+    {
+        var line = lines[i];
+
+        if (this._align === 'right')
+        {
+            align = this.textWidth - line.width;
+        }
+        else if (this._align === 'center')
+        {
+            align = (this.textWidth - line.width) / 2;
+        }
+
+        for (var c = 0; c < line.text.length; c++)
+        {
+            var charCode = line.text.charCodeAt(c);
+            var charData = data.chars[charCode];
+
+            var g = this._glyphs[t];
+
+            if (g)
+            {
+                //  Sprite already exists in the glyphs pool, so we'll reuse it for this letter
+                g.texture = charData.texture;
+                // g.name = line.text[c];
+                // console.log('reusing', g.name, 'as', line.text[c]);
+            }
+            else
+            {
+                //  We need a new sprite as the pool is empty or exhausted
+                g = new PIXI.Sprite(charData.texture);
+                g.name = line.text[c];
+                this._glyphs.push(g);
+                // console.log('new', line.text[c]);
+            }
+
+            g.position.x = (line.chars[c] + align) - ax;
+            g.position.y = (line.y + (charData.yOffset * scale)) - ay;
+
+            g.scale.set(scale);
+            g.tint = this.tint;
+
+            if (!g.parent)
+            {
+                this.addChild(g);
+            }
+
+            t++;
+        }
+    }
+
+    //  Remove unnecessary children
+    //  This moves them from the display list (children array) but retains them in the _glyphs pool
+    for (i = t; i < this._glyphs.length; i++)
+    {
+        this.removeChild(this._glyphs[i]);
+    }
+
+};
+
+/**
+* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of
+* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they
+* still take up memory while sat in the glyphs pool waiting to be re-used in the future.
+*
+* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool 
+* by calling this method.
+*
+* Calling this doesn't prevent you from increasing the length of the text again in the future.
+*
+* @method Phaser.BitmapText.prototype.purgeGlyphs
+* @return {integer} The amount of glyphs removed from the pool.
+*/
+Phaser.BitmapText.prototype.purgeGlyphs = function () {
+
+    var len = this._glyphs.length;
+    var kept = [];
+
+    for (var i = 0; i < this._glyphs.length; i++)
+    {
+        if (this._glyphs[i].parent !== this)
+        {
+            this._glyphs[i].destroy();
+        }
+        else
+        {
+            kept.push(this._glyphs[i]);
+        }
+    }
+
+    this._glyphs = [];
+    this._glyphs = kept;
+
+    this.updateText();
+
+    return len - kept.length;
+
+};
+
+/**
+* Updates the transform of this object.
+*
+* @method Phaser.BitmapText.prototype.updateTransform
+* @private
+*/
+Phaser.BitmapText.prototype.updateTransform = function () {
+
+    if (this.dirty || !this.anchor.equals(this._prevAnchor))
+    {
+        this.updateText();
+        this.dirty = false;
+        this._prevAnchor.copyFrom(this.anchor);
+    }
+
+    PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
+
+};
+
+/**
+* @name Phaser.BitmapText#align
+* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text.
+*/
+Object.defineProperty(Phaser.BitmapText.prototype, 'align', {
+
+    get: function() {
+        return this._align;
+    },
+
+    set: function(value) {
+
+        if (value !== this._align && (value === 'left' || value === 'center' || value === 'right'))
+        {
+            this._align = value;
+            this.updateText();
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.BitmapText#tint
+* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF)
+*/
+Object.defineProperty(Phaser.BitmapText.prototype, 'tint', {
+
+    get: function() {
+        return this._tint;
+    },
+
+    set: function(value) {
+
+        if (value !== this._tint)
+        {
+            this._tint = value;
+            this.updateText();
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.BitmapText#font
+* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
+*/
+Object.defineProperty(Phaser.BitmapText.prototype, 'font', {
+
+    get: function() {
+        return this._font;
+    },
+
+    set: function(value) {
+
+        if (value !== this._font)
+        {
+            this._font = value.trim();
+            this.updateText();
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.BitmapText#fontSize
+* @property {number} fontSize - The size of the font in pixels.
+*/
+Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', {
+
+    get: function() {
+        return this._fontSize;
+    },
+
+    set: function(value) {
+
+        value = parseInt(value, 10);
+
+        if (value !== this._fontSize && value > 0)
+        {
+            this._fontSize = value;
+            this.updateText();
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.BitmapText#text
+* @property {string} text - The text to be displayed by this BitmapText object.
+*/
+Object.defineProperty(Phaser.BitmapText.prototype, 'text', {
+
+    get: function() {
+        return this._text;
+    },
+
+    set: function(value) {
+
+        if (value !== this._text)
+        {
+            this._text = value.toString() || '';
+            this.updateText();
+        }
+
+    }
+
+});
+
+/**
+* The maximum display width of this BitmapText in pixels.
+* 
+* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped 
+* based on the last whitespace character found in the line.
+* 
+* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored.
+* 
+* Disable maxWidth by setting the value to 0.
+* 
+* @name Phaser.BitmapText#maxWidth
+* @property {number} maxWidth - The maximum width of this BitmapText in pixels.
+*/
+Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', {
+
+    get: function() {
+
+        return this._maxWidth;
+
+    },
+
+    set: function(value) {
+
+        if (value !== this._maxWidth)
+        {
+            this._maxWidth = value;
+            this.updateText();
+        }
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont
+* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos.
+* 
+* @class Phaser.RetroFont
+* @extends Phaser.RenderTexture
+* @constructor
+* @param {Phaser.Game} game - Current game instance.
+* @param {string} key - The font set graphic set as stored in the Game.Cache.
+* @param {number} characterWidth - The width of each character in the font set.
+* @param {number} characterHeight - The height of each character in the font set.
+* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
+* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth.
+* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
+* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
+* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
+* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
+*/
+Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
+
+    if (!game.cache.checkImageKey(key))
+    {
+        return false;
+    }
+
+    if (charsPerRow === undefined || charsPerRow === null)
+    {
+        charsPerRow = game.cache.getImage(key).width / characterWidth;
+    }
+
+    /**
+    * @property {number} characterWidth - The width of each character in the font set.
+    */
+    this.characterWidth = characterWidth;
+
+    /**
+    * @property {number} characterHeight - The height of each character in the font set.
+    */
+    this.characterHeight = characterHeight;
+
+    /**
+    * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here.
+    */
+    this.characterSpacingX = xSpacing || 0;
+
+    /**
+    * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here.
+    */
+    this.characterSpacingY = ySpacing || 0;
+
+    /**
+    * @property {number} characterPerRow - The number of characters per row in the font set.
+    */
+    this.characterPerRow = charsPerRow;
+
+    /**
+    * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
+    * @readonly
+    */
+    this.offsetX = xOffset || 0;
+
+    /**
+    * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
+    * @readonly
+    */
+    this.offsetY = yOffset || 0;
+
+    /**
+    * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
+    */
+    this.align = "left";
+
+    /**
+    * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default)
+    * @default
+    */
+    this.multiLine = false;
+
+    /**
+    * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true.
+    * @default
+    */
+    this.autoUpperCase = true;
+
+    /**
+    * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels.
+    * @default
+    */
+    this.customSpacingX = 0;
+
+    /**
+    * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels.
+    * @default
+    */
+    this.customSpacingY = 0;
+
+    /**
+    * If you need this RetroFont image to have a fixed width you can set the width in this value.
+    * If text is wider than the width specified it will be cropped off.
+    * @property {number} fixedWidth
+    */
+    this.fixedWidth = 0;
+
+    /**
+    * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font.
+    */
+    this.fontSet = game.cache.getImage(key);
+
+    /**
+    * @property {string} _text - The text of the font image.
+    * @private
+    */
+    this._text = '';
+
+    /**
+    * @property {array} grabData - An array of rects for faster character pasting.
+    * @private
+    */
+    this.grabData = [];
+
+    /**
+    * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font.
+    */
+    this.frameData = new Phaser.FrameData();
+
+    //  Now generate our rects for faster copying later on
+    var currentX = this.offsetX;
+    var currentY = this.offsetY;
+    var r = 0;
+
+    for (var c = 0; c < chars.length; c++)
+    {
+        var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight));
+
+        this.grabData[chars.charCodeAt(c)] = frame.index;
+
+        r++;
+
+        if (r === this.characterPerRow)
+        {
+            r = 0;
+            currentX = this.offsetX;
+            currentY += this.characterHeight + this.characterSpacingY;
+        }
+        else
+        {
+            currentX += this.characterWidth + this.characterSpacingX;
+        }
+    }
+
+    game.cache.updateFrameData(key, this.frameData);
+
+    /**
+    * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font.
+    * @readonly
+    */
+    this.stamp = new Phaser.Image(game, 0, 0, key, 0);
+
+    Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST);
+
+    /**
+    * @property {number} type - Base Phaser object type.
+    */
+    this.type = Phaser.RETROFONT;
+
+};
+
+Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype);
+Phaser.RetroFont.prototype.constructor = Phaser.RetroFont;
+
+/**
+* Align each line of multi-line text to the left.
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.ALIGN_LEFT = "left";
+
+/**
+* Align each line of multi-line text to the right.
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.ALIGN_RIGHT = "right";
+
+/**
+* Align each line of multi-line text in the center.
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.ALIGN_CENTER = "center";
+
+/**
+* Text Set 1 =  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
+
+/**
+* Text Set 2 =  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
+/**
+* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
+
+/**
+* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
+
+/**
+* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";
+
+/**
+* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' 
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";
+
+/**
+* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";
+
+/**
+* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
+/**
+* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?!
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";
+
+/**
+* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
+/**
+* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789
+* @constant
+* @type {string}
+*/
+Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";
+
+/**
+* If you need this RetroFont to have a fixed width and custom alignment you can set the width here.
+* If text is wider than the width specified it will be cropped off.
+*
+* @method Phaser.RetroFont#setFixedWidth
+* @memberof Phaser.RetroFont
+* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing.
+* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
+*/
+Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) {
+
+    if (lineAlignment === undefined) { lineAlignment = 'left'; }
+
+    this.fixedWidth = width;
+    this.align = lineAlignment;
+
+};
+
+/**
+* A helper function that quickly sets lots of variables at once, and then updates the text.
+*
+* @method Phaser.RetroFont#setText
+* @memberof Phaser.RetroFont
+* @param {string} content - The text of this sprite.
+* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line.
+* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels.
+* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels.
+* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
+* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true.
+*/
+Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) {
+
+    this.multiLine = multiLine || false;
+    this.customSpacingX = characterSpacing || 0;
+    this.customSpacingY = lineSpacing || 0;
+    this.align = lineAlignment || 'left';
+
+    if (allowLowerCase)
+    {
+        this.autoUpperCase = false;
+    }
+    else
+    {
+        this.autoUpperCase = true;
+    }
+
+    if (content.length > 0)
+    {
+        this.text = content;
+    }
+
+};
+
+/**
+* Updates the texture with the new text.
+*
+* @method Phaser.RetroFont#buildRetroFontText
+* @memberof Phaser.RetroFont
+*/
+Phaser.RetroFont.prototype.buildRetroFontText = function () {
+
+    var cx = 0;
+    var cy = 0;
+
+    //  Clears the textureBuffer
+    this.clear();
+
+    if (this.multiLine)
+    {
+        var lines = this._text.split("\n");
+
+        if (this.fixedWidth > 0)
+        {
+            this.resize(this.fixedWidth, (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
+        }
+        else
+        {
+            this.resize(this.getLongestLine() * (this.characterWidth + this.customSpacingX), (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
+        }
+
+        //  Loop through each line of text
+        for (var i = 0; i < lines.length; i++)
+        {
+            //  Phaser.RetroFont.ALIGN_LEFT
+            cx = 0;
+
+            //  This line of text is held in lines[i] - need to work out the alignment
+            if (this.align === Phaser.RetroFont.ALIGN_RIGHT)
+            {
+                cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX));
+            }
+            else if (this.align === Phaser.RetroFont.ALIGN_CENTER)
+            {
+                cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2);
+                cx += this.customSpacingX / 2;
+            }
+
+            //  Sanity checks
+            if (cx < 0)
+            {
+                cx = 0;
+            }
+
+            this.pasteLine(lines[i], cx, cy, this.customSpacingX);
+
+            cy += this.characterHeight + this.customSpacingY;
+        }
+    }
+    else
+    {
+        if (this.fixedWidth > 0)
+        {
+            this.resize(this.fixedWidth, this.characterHeight, true);
+        }
+        else
+        {
+            this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true);
+        }
+
+        //  Phaser.RetroFont.ALIGN_LEFT
+        cx = 0;
+
+        if (this.align === Phaser.RetroFont.ALIGN_RIGHT)
+        {
+            cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX));
+        }
+        else if (this.align === Phaser.RetroFont.ALIGN_CENTER)
+        {
+            cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2);
+            cx += this.customSpacingX / 2;
+        }
+
+        //  Sanity checks
+        if (cx < 0)
+        {
+            cx = 0;
+        }
+
+        this.pasteLine(this._text, cx, 0, this.customSpacingX);
+    }
+
+    this.requiresReTint = true;
+
+};
+
+/**
+* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates.
+* Used by getLine and getMultiLine
+*
+* @method Phaser.RetroFont#pasteLine
+* @memberof Phaser.RetroFont
+* @param {string} line - The single line of text to paste.
+* @param {number} x - The x coordinate.
+* @param {number} y - The y coordinate.
+* @param {number} customSpacingX - Custom X spacing.
+*/
+Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) {
+
+    for (var c = 0; c < line.length; c++)
+    {
+        //  If it's a space then there is no point copying, so leave a blank space
+        if (line.charAt(c) === " ")
+        {
+            x += this.characterWidth + customSpacingX;
+        }
+        else
+        {
+            //  If the character doesn't exist in the font then we don't want a blank space, we just want to skip it
+            if (this.grabData[line.charCodeAt(c)] >= 0)
+            {
+                this.stamp.frame = this.grabData[line.charCodeAt(c)];
+                this.renderXY(this.stamp, x, y, false);
+
+                x += this.characterWidth + customSpacingX;
+
+                if (x > this.width)
+                {
+                    break;
+                }
+            }
+        }
+    }
+};
+
+/**
+* Works out the longest line of text in _text and returns its length
+*
+* @method Phaser.RetroFont#getLongestLine
+* @memberof Phaser.RetroFont
+* @return {number} The length of the longest line of text.
+*/
+Phaser.RetroFont.prototype.getLongestLine = function () {
+
+    var longestLine = 0;
+
+    if (this._text.length > 0)
+    {
+        var lines = this._text.split("\n");
+
+        for (var i = 0; i < lines.length; i++)
+        {
+            if (lines[i].length > longestLine)
+            {
+                longestLine = lines[i].length;
+            }
+        }
+    }
+
+    return longestLine;
+};
+
+/**
+* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set.
+*
+* @method Phaser.RetroFont#removeUnsupportedCharacters
+* @memberof Phaser.RetroFont
+* @protected
+* @param {boolean} [stripCR=true] - Should it strip carriage returns as well?
+* @return {string}  A clean version of the string.
+*/
+Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) {
+
+    var newString = "";
+
+    for (var c = 0; c < this._text.length; c++)
+    {
+        var aChar = this._text[c];
+        var code = aChar.charCodeAt(0);
+
+        if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n"))
+        {
+            newString = newString.concat(aChar);
+        }
+    }
+
+    return newString;
+
+};
+
+/**
+* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called.
+* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters.
+* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset.
+*
+* @method Phaser.RetroFont#updateOffset
+* @memberof Phaser.RetroFont
+* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
+* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
+*/
+Phaser.RetroFont.prototype.updateOffset = function (x, y) {
+
+    if (this.offsetX === x && this.offsetY === y)
+    {
+        return;
+    }
+
+    var diffX = x - this.offsetX;
+    var diffY = y - this.offsetY;
+
+    var frames = this.game.cache.getFrameData(this.stamp.key).getFrames();
+    var i = frames.length;
+
+    while (i--)
+    {
+        frames[i].x += diffX;
+        frames[i].y += diffY;
+    }
+
+    this.buildRetroFontText();
+
+};
+
+/**
+* @name Phaser.RetroFont#text
+* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true.
+*/
+Object.defineProperty(Phaser.RetroFont.prototype, "text", {
+
+    get: function () {
+
+        return this._text;
+
+    },
+
+    set: function (value) {
+
+        var newText;
+
+        if (this.autoUpperCase)
+        {
+            newText = value.toUpperCase();
+        }
+        else
+        {
+            newText = value;
+        }
+
+        if (newText !== this._text)
+        {
+            this._text = newText;
+
+            this.removeUnsupportedCharacters(this.multiLine);
+
+            this.buildRetroFontText();
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.RetroFont#smoothed
+* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true.
+*/
+Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", {
+
+    get: function () {
+
+        return this.stamp.smoothed;
+
+    },
+
+    set: function (value) {
+
+        this.stamp.smoothed = value;
+        this.buildRetroFontText();
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd, Richard Davey
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Rope is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
+* Please note that Ropes, as with normal Sprites, have no input handler or physics bodies by default. Both need enabling.
+* Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js
+*
+* @class Phaser.Rope
+* @constructor
+* @extends PIXI.Rope
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.Animation
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.BringToTop
+* @extends Phaser.Component.Crop
+* @extends Phaser.Component.Delta
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.LoadTexture
+* @extends Phaser.Component.Overlap
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @extends Phaser.Component.ScaleMinMax
+* @extends Phaser.Component.Smoothed
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - The x coordinate (in world space) to position the Rope at.
+* @param {number} y - The y coordinate (in world space) to position the Rope at.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
+* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+* @param {Array} points - An array of {Phaser.Point}.
+*/
+Phaser.Rope = function (game, x, y, key, frame, points) {
+
+    this.points = [];
+    this.points = points;
+    this._hasUpdateAnimation = false;
+    this._updateAnimationCallback = null;
+    x = x || 0;
+    y = y || 0;
+    key = key || null;
+    frame = frame || null;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.ROPE;
+
+    /**
+    * @property {Phaser.Point} _scroll - Internal cache var.
+    * @private
+    */
+    this._scroll = new Phaser.Point();
+
+    PIXI.Rope.call(this, PIXI.TextureCache['__default'], this.points);
+
+    Phaser.Component.Core.init.call(this, game, x, y, key, frame);
+
+};
+
+Phaser.Rope.prototype = Object.create(PIXI.Rope.prototype);
+Phaser.Rope.prototype.constructor = Phaser.Rope;
+
+Phaser.Component.Core.install.call(Phaser.Rope.prototype, [
+    'Angle',
+    'Animation',
+    'AutoCull',
+    'Bounds',
+    'BringToTop',
+    'Crop',
+    'Delta',
+    'Destroy',
+    'FixedToCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'LoadTexture',
+    'Overlap',
+    'PhysicsBody',
+    'Reset',
+    'ScaleMinMax',
+    'Smoothed'
+]);
+
+Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method Phaser.Rope#preUpdate
+* @memberof Phaser.Rope
+*/
+Phaser.Rope.prototype.preUpdate = function() {
+
+    if (this._scroll.x !== 0)
+    {
+        this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
+    }
+
+    if (this._scroll.y !== 0)
+    {
+        this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
+    }
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Override and use this function in your own custom objects to handle any update requirements you may have.
+*
+* @method Phaser.Rope#update
+* @memberof Phaser.Rope
+*/
+Phaser.Rope.prototype.update = function() {
+
+    if (this._hasUpdateAnimation)
+    {
+        this.updateAnimation.call(this);
+    }
+
+};
+
+/**
+* Resets the Rope. This places the Rope at the given x/y world coordinates, resets the tilePosition and then
+* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
+* If the Rope has a physics body that too is reset.
+*
+* @method Phaser.Rope#reset
+* @memberof Phaser.Rope
+* @param {number} x - The x coordinate (in world space) to position the Sprite at.
+* @param {number} y - The y coordinate (in world space) to position the Sprite at.
+* @return (Phaser.Rope) This instance.
+*/
+Phaser.Rope.prototype.reset = function(x, y) {
+
+    Phaser.Component.Reset.prototype.reset.call(this, x, y);
+
+    this.tilePosition.x = 0;
+    this.tilePosition.y = 0;
+
+    return this;
+
+};
+
+/**
+* A Rope will call it's updateAnimation function on each update loop if it has one
+*
+* @name Phaser.Rope#updateAnimation
+* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it.
+*/
+Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", {
+
+    get: function () {
+
+        return this._updateAnimation;
+
+    },
+
+    set: function (value) {
+
+        if (value && typeof value === 'function')
+        {
+            this._hasUpdateAnimation = true;
+            this._updateAnimation = value;
+        }
+        else
+        {
+            this._hasUpdateAnimation = false;
+            this._updateAnimation = null;
+        }
+
+    }
+
+});
+
+/**
+* The segments that make up the rope body as an array of Phaser.Rectangles
+*
+* @name Phaser.Rope#segments
+* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope
+*/
+Object.defineProperty(Phaser.Rope.prototype, "segments", {
+
+    get: function() {
+
+        var segments = [];
+        var index, x1, y1, x2, y2, width, height, rect;
+
+        for (var i = 0; i < this.points.length; i++)
+        {
+            index = i * 4;
+
+            x1 = this.vertices[index] * this.scale.x;
+            y1 = this.vertices[index + 1] * this.scale.y;
+            x2 = this.vertices[index + 4] * this.scale.x;
+            y2 = this.vertices[index + 3] * this.scale.y;
+
+            width = Phaser.Math.difference(x1, x2);
+            height = Phaser.Math.difference(y1, y2);
+
+            x1 += this.world.x;
+            y1 += this.world.y;
+            rect = new Phaser.Rectangle(x1, y1, width, height);
+            segments.push(rect);
+        }
+
+        return segments;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself.
+* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source.
+* 
+* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites.
+*
+* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background
+* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition`
+* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will 
+* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to
+* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs.
+*
+* An important note about texture dimensions:
+*
+* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be
+* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etch pixels width by height). If the texture isn't a power of two
+* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and
+* bottom of your frame. To avoid this ensure your textures are perfect powers of two.
+* 
+* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However
+* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive
+* additional padding to enforce it to be so.
+*
+* @class Phaser.TileSprite
+* @constructor
+* @extends PIXI.TilingSprite
+* @extends Phaser.Component.Core
+* @extends Phaser.Component.Angle
+* @extends Phaser.Component.Animation
+* @extends Phaser.Component.AutoCull
+* @extends Phaser.Component.Bounds
+* @extends Phaser.Component.BringToTop
+* @extends Phaser.Component.Destroy
+* @extends Phaser.Component.FixedToCamera
+* @extends Phaser.Component.Health
+* @extends Phaser.Component.InCamera
+* @extends Phaser.Component.InputEnabled
+* @extends Phaser.Component.InWorld
+* @extends Phaser.Component.LifeSpan
+* @extends Phaser.Component.LoadTexture
+* @extends Phaser.Component.Overlap
+* @extends Phaser.Component.PhysicsBody
+* @extends Phaser.Component.Reset
+* @extends Phaser.Component.Smoothed
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
+* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
+* @param {number} width - The width of the TileSprite.
+* @param {number} height - The height of the TileSprite.
+* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a RenderTexture, PIXI.Texture or BitmapData.
+* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
+*/
+Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
+
+    x = x || 0;
+    y = y || 0;
+    width = width || 256;
+    height = height || 256;
+    key = key || null;
+    frame = frame || null;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @readonly
+    */
+    this.type = Phaser.TILESPRITE;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.SPRITE;
+
+    /**
+    * @property {Phaser.Point} _scroll - Internal cache var.
+    * @private
+    */
+    this._scroll = new Phaser.Point();
+
+    var def = game.cache.getImage('__default', true);
+
+    PIXI.TilingSprite.call(this, new PIXI.Texture(def.base), width, height);
+
+    Phaser.Component.Core.init.call(this, game, x, y, key, frame);
+
+};
+
+Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
+Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
+
+Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [
+    'Angle',
+    'Animation',
+    'AutoCull',
+    'Bounds',
+    'BringToTop',
+    'Destroy',
+    'FixedToCamera',
+    'Health',
+    'InCamera',
+    'InputEnabled',
+    'InWorld',
+    'LifeSpan',
+    'LoadTexture',
+    'Overlap',
+    'PhysicsBody',
+    'Reset',
+    'Smoothed'
+]);
+
+Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
+Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
+Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
+Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method Phaser.TileSprite#preUpdate
+* @memberof Phaser.TileSprite
+*/
+Phaser.TileSprite.prototype.preUpdate = function() {
+
+    if (this._scroll.x !== 0)
+    {
+        this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
+    }
+
+    if (this._scroll.y !== 0)
+    {
+        this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
+    }
+
+    if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
+    {
+        return false;
+    }
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
+* The scroll speed is specified in pixels per second.
+* A negative x value will scroll to the left. A positive x value will scroll to the right.
+* A negative y value will scroll up. A positive y value will scroll down.
+*
+* @method Phaser.TileSprite#autoScroll
+* @memberof Phaser.TileSprite
+* @param {number} x - Horizontal scroll speed in pixels per second.
+* @param {number} y - Vertical scroll speed in pixels per second.
+*/
+Phaser.TileSprite.prototype.autoScroll = function(x, y) {
+
+    this._scroll.set(x, y);
+
+};
+
+/**
+* Stops an automatically scrolling TileSprite.
+*
+* @method Phaser.TileSprite#stopScroll
+* @memberof Phaser.TileSprite
+*/
+Phaser.TileSprite.prototype.stopScroll = function() {
+
+    this._scroll.set(0, 0);
+
+};
+
+/**
+* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
+* and nulls its reference to game, freeing it up for garbage collection.
+*
+* @method Phaser.TileSprite#destroy
+* @memberof Phaser.TileSprite
+* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
+*/
+Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
+
+    Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
+
+    PIXI.TilingSprite.prototype.destroy.call(this);
+
+};
+
+/**
+* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
+* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
+* If the TileSprite has a physics body that too is reset.
+*
+* @method Phaser.TileSprite#reset
+* @memberof Phaser.TileSprite
+* @param {number} x - The x coordinate (in world space) to position the Sprite at.
+* @param {number} y - The y coordinate (in world space) to position the Sprite at.
+* @return (Phaser.TileSprite) This instance.
+*/
+Phaser.TileSprite.prototype.reset = function(x, y) {
+
+    Phaser.Component.Reset.prototype.reset.call(this, x, y);
+
+    this.tilePosition.x = 0;
+    this.tilePosition.y = 0;
+
+    return this;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* @classdesc
+* Detects device support capabilities and is responsible for device intialization - see {@link Phaser.Device.whenReady whenReady}.
+*
+* This class represents a singleton object that can be accessed directly as `game.device`
+* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it.
+*
+* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization
+* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase.
+* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal.
+*
+* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon
+* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined`
+* when indicating the lack of a feature.
+*
+* Uses elements from System.js by MrDoob and Modernizr
+*
+* @description
+* It is not possible to instantiate the Device class manually.
+*
+* @class
+* @protected
+*/
+Phaser.Device = function () {
+
+    /**
+    * The time the device became ready.
+    * @property {integer} deviceReadyAt
+    * @protected
+    */
+    this.deviceReadyAt = 0;
+
+    /**
+    * The time as which initialization has completed.
+    * @property {boolean} initialized
+    * @protected
+    */
+    this.initialized = false;
+
+    //  Browser / Host / Operating System
+
+    /**
+    * @property {boolean} desktop - Is running on a desktop?
+    * @default
+    */
+    this.desktop = false;
+
+    /**
+    * @property {boolean} iOS - Is running on iOS?
+    * @default
+    */
+    this.iOS = false;
+
+    /**
+    * @property {boolean} cocoonJS - Is the game running under CocoonJS?
+    * @default
+    */
+    this.cocoonJS = false;
+    
+    /**
+    * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App?
+    * @default
+    */
+    this.cocoonJSApp = false;
+    
+    /**
+    * @property {boolean} cordova - Is the game running under Apache Cordova?
+    * @default
+    */
+    this.cordova = false;
+    
+    /**
+    * @property {boolean} node - Is the game running under Node.js?
+    * @default
+    */
+    this.node = false;
+    
+    /**
+    * @property {boolean} nodeWebkit - Is the game running under Node-Webkit?
+    * @default
+    */
+    this.nodeWebkit = false;
+    
+    /**
+    * @property {boolean} electron - Is the game running under GitHub Electron?
+    * @default
+    */
+    this.electron = false;
+    
+    /**
+    * @property {boolean} ejecta - Is the game running under Ejecta?
+    * @default
+    */
+    this.ejecta = false;
+
+    /**
+    * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK?
+    * @default
+    */
+    this.crosswalk = false;
+
+    /**
+    * @property {boolean} android - Is running on android?
+    * @default
+    */
+    this.android = false;
+
+    /**
+    * @property {boolean} chromeOS - Is running on chromeOS?
+    * @default
+    */
+    this.chromeOS = false;
+
+    /**
+    * @property {boolean} linux - Is running on linux?
+    * @default
+    */
+    this.linux = false;
+
+    /**
+    * @property {boolean} macOS - Is running on macOS?
+    * @default
+    */
+    this.macOS = false;
+
+    /**
+    * @property {boolean} windows - Is running on windows?
+    * @default
+    */
+    this.windows = false;
+
+    /**
+    * @property {boolean} windowsPhone - Is running on a Windows Phone?
+    * @default
+    */
+    this.windowsPhone = false;
+
+    //  Features
+
+    /**
+    * @property {boolean} canvas - Is canvas available?
+    * @default
+    */
+    this.canvas = false;
+
+    /**
+    * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap.
+    * @default
+    */
+    this.canvasBitBltShift = null;
+
+    /**
+    * @property {boolean} webGL - Is webGL available?
+    * @default
+    */
+    this.webGL = false;
+
+    /**
+    * @property {boolean} file - Is file available?
+    * @default
+    */
+    this.file = false;
+
+    /**
+    * @property {boolean} fileSystem - Is fileSystem available?
+    * @default
+    */
+    this.fileSystem = false;
+
+    /**
+    * @property {boolean} localStorage - Is localStorage available?
+    * @default
+    */
+    this.localStorage = false;
+
+    /**
+    * @property {boolean} worker - Is worker available?
+    * @default
+    */
+    this.worker = false;
+
+    /**
+    * @property {boolean} css3D - Is css3D available?
+    * @default
+    */
+    this.css3D = false;
+
+    /**
+    * @property {boolean} pointerLock - Is Pointer Lock available?
+    * @default
+    */
+    this.pointerLock = false;
+
+    /**
+    * @property {boolean} typedArray - Does the browser support TypedArrays?
+    * @default
+    */
+    this.typedArray = false;
+
+    /**
+    * @property {boolean} vibration - Does the device support the Vibration API?
+    * @default
+    */
+    this.vibration = false;
+
+    /**
+    * @property {boolean} getUserMedia - Does the device support the getUserMedia API?
+    * @default
+    */
+    this.getUserMedia = true;
+
+    /**
+    * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true)
+    * @default
+    */
+    this.quirksMode = false;
+
+    //  Input
+
+    /**
+    * @property {boolean} touch - Is touch available?
+    * @default
+    */
+    this.touch = false;
+
+    /**
+    * @property {boolean} mspointer - Is mspointer available?
+    * @default
+    */
+    this.mspointer = false;
+
+    /**
+    * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll'
+    * @default
+    * @protected
+    */
+    this.wheelEvent = null;
+
+    //  Browser
+
+    /**
+    * @property {boolean} arora - Set to true if running in Arora.
+    * @default
+    */
+    this.arora = false;
+
+    /**
+    * @property {boolean} chrome - Set to true if running in Chrome.
+    * @default
+    */
+    this.chrome = false;
+
+    /**
+    * @property {number} chromeVersion - If running in Chrome this will contain the major version number.
+    * @default
+    */
+    this.chromeVersion = 0;
+
+    /**
+    * @property {boolean} epiphany - Set to true if running in Epiphany.
+    * @default
+    */
+    this.epiphany = false;
+
+    /**
+    * @property {boolean} firefox - Set to true if running in Firefox.
+    * @default
+    */
+    this.firefox = false;
+
+    /**
+    * @property {number} firefoxVersion - If running in Firefox this will contain the major version number.
+    * @default
+    */
+    this.firefoxVersion = 0;
+
+    /**
+    * @property {boolean} ie - Set to true if running in Internet Explorer.
+    * @default
+    */
+    this.ie = false;
+
+    /**
+    * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion.
+    * @default
+    */
+    this.ieVersion = 0;
+
+    /**
+    * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+)
+    * @default
+    */
+    this.trident = false;
+
+    /**
+    * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx}
+    * @default
+    */
+    this.tridentVersion = 0;
+
+    /**
+    * @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
+    * @default
+    */
+    this.mobileSafari = false;
+
+    /**
+    * @property {boolean} midori - Set to true if running in Midori.
+    * @default
+    */
+    this.midori = false;
+
+    /**
+    * @property {boolean} opera - Set to true if running in Opera.
+    * @default
+    */
+    this.opera = false;
+
+    /**
+    * @property {boolean} safari - Set to true if running in Safari.
+    * @default
+    */
+    this.safari = false;
+
+    /**
+    * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView
+    * @default
+    */
+    this.webApp = false;
+
+    /**
+    * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle)
+    * @default
+    */
+    this.silk = false;
+
+    //  Audio
+
+    /**
+    * @property {boolean} audioData - Are Audio tags available?
+    * @default
+    */
+    this.audioData = false;
+
+    /**
+    * @property {boolean} webAudio - Is the WebAudio API available?
+    * @default
+    */
+    this.webAudio = false;
+
+    /**
+    * @property {boolean} ogg - Can this device play ogg files?
+    * @default
+    */
+    this.ogg = false;
+
+    /**
+    * @property {boolean} opus - Can this device play opus files?
+    * @default
+    */
+    this.opus = false;
+
+    /**
+    * @property {boolean} mp3 - Can this device play mp3 files?
+    * @default
+    */
+    this.mp3 = false;
+
+    /**
+    * @property {boolean} wav - Can this device play wav files?
+    * @default
+    */
+    this.wav = false;
+
+    /**
+    * Can this device play m4a files?
+    * @property {boolean} m4a - True if this device can play m4a files.
+    * @default
+    */
+    this.m4a = false;
+
+    /**
+    * @property {boolean} webm - Can this device play webm files?
+    * @default
+    */
+    this.webm = false;
+
+    //  Video
+
+    /**
+    * @property {boolean} oggVideo - Can this device play ogg video files?
+    * @default
+    */
+    this.oggVideo = false;
+
+    /**
+    * @property {boolean} h264Video - Can this device play h264 mp4 video files?
+    * @default
+    */
+    this.h264Video = false;
+
+    /**
+    * @property {boolean} mp4Video - Can this device play h264 mp4 video files?
+    * @default
+    */
+    this.mp4Video = false;
+
+    /**
+    * @property {boolean} webmVideo - Can this device play webm video files?
+    * @default
+    */
+    this.webmVideo = false;
+
+    /**
+    * @property {boolean} vp9Video - Can this device play vp9 video files?
+    * @default
+    */
+    this.vp9Video = false;
+
+    /**
+    * @property {boolean} hlsVideo - Can this device play hls video files?
+    * @default
+    */
+    this.hlsVideo = false;
+
+    //  Device
+
+    /**
+    * @property {boolean} iPhone - Is running on iPhone?
+    * @default
+    */
+    this.iPhone = false;
+
+    /**
+    * @property {boolean} iPhone4 - Is running on iPhone4?
+    * @default
+    */
+    this.iPhone4 = false;
+
+    /**
+    * @property {boolean} iPad - Is running on iPad?
+    * @default
+    */
+    this.iPad = false;
+
+    // Device features
+
+    /**
+    * @property {number} pixelRatio - PixelRatio of the host device?
+    * @default
+    */
+    this.pixelRatio = 0;
+
+    /**
+    * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays)
+    * @default
+    */
+    this.littleEndian = false;
+
+    /**
+    * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`.
+    * @default
+    */
+    this.LITTLE_ENDIAN = false;
+
+    /**
+    * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views?
+    * @default
+    */
+    this.support32bit = false;
+
+    /**
+    * @property {boolean} fullscreen - Does the browser support the Full Screen API?
+    * @default
+    */
+    this.fullscreen = false;
+
+    /**
+    * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it.
+    * @default
+    */
+    this.requestFullscreen = '';
+
+    /**
+    * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it.
+    * @default
+    */
+    this.cancelFullscreen = '';
+
+    /**
+    * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode?
+    * @default
+    */
+    this.fullscreenKeyboard = false;
+
+};
+
+// Device is really a singleton/static entity; instantiate it
+// and add new methods directly sans-prototype.
+Phaser.Device = new Phaser.Device();
+
+/**
+* This signal is dispatched after device initialization occurs but before any of the ready
+* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked.
+*
+* Local "patching" for a particular device can/should be done in this event.
+*
+* _Note_: This signal is removed after the device has been readied; if a handler has not been
+* added _before_ `new Phaser.Game(..)` it is probably too late.
+*
+* @type {?Phaser.Signal}
+* @static
+*/
+Phaser.Device.onInitialized = new Phaser.Signal();
+
+/**
+* Add a device-ready handler and ensure the device ready sequence is started.
+*
+* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added,
+* which is normally done automatically be calling `new Phaser.Game(..)`.
+*
+* The handler is invoked when the device is considered "ready", which may be immediately
+* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}.
+*
+* @method
+* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument.
+* @param {object} [context] - Context in which to invoke the handler
+* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started.
+*/
+Phaser.Device.whenReady = function (callback, context, nonPrimer) {
+
+    var readyCheck = this._readyCheck;
+
+    if (this.deviceReadyAt || !readyCheck)
+    {
+        callback.call(context, this);
+    }
+    else if (readyCheck._monitor || nonPrimer)
+    {
+        readyCheck._queue = readyCheck._queue || [];
+        readyCheck._queue.push([callback, context]);
+    }
+    else
+    {
+        readyCheck._monitor = readyCheck.bind(this);
+        readyCheck._queue = readyCheck._queue || [];
+        readyCheck._queue.push([callback, context]);
+        
+        var cordova = typeof window.cordova !== 'undefined';
+        var cocoonJS = navigator['isCocoonJS'];
+
+        if (document.readyState === 'complete' || document.readyState === 'interactive')
+        {
+            // Why is there an additional timeout here?
+            window.setTimeout(readyCheck._monitor, 0);
+        }
+        else if (cordova && !cocoonJS)
+        {
+            // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready
+            //  Cordova, but NOT Cocoon?
+            document.addEventListener('deviceready', readyCheck._monitor, false);
+        }
+        else
+        {
+            document.addEventListener('DOMContentLoaded', readyCheck._monitor, false);
+            window.addEventListener('load', readyCheck._monitor, false);
+        }
+    }
+
+};
+
+/**
+* Internal method used for checking when the device is ready.
+* This function is removed from Phaser.Device when the device becomes ready.
+*
+* @method
+* @private
+*/
+Phaser.Device._readyCheck = function () {
+
+    var readyCheck = this._readyCheck;
+
+    if (!document.body)
+    {
+        window.setTimeout(readyCheck._monitor, 20);
+    }
+    else if (!this.deviceReadyAt)
+    {
+        this.deviceReadyAt = Date.now();
+
+        document.removeEventListener('deviceready', readyCheck._monitor);
+        document.removeEventListener('DOMContentLoaded', readyCheck._monitor);
+        window.removeEventListener('load', readyCheck._monitor);
+
+        this._initialize();
+        this.initialized = true;
+
+        this.onInitialized.dispatch(this);
+
+        var item;
+        while ((item = readyCheck._queue.shift()))
+        {
+            var callback = item[0];
+            var context = item[1];
+            callback.call(context, this);
+        }
+
+        // Remove no longer useful methods and properties.
+        this._readyCheck = null;
+        this._initialize = null;
+        this.onInitialized = null;
+    }
+
+};
+
+/**
+* Internal method to initialize the capability checks.
+* This function is removed from Phaser.Device once the device is initialized.
+*
+* @method
+* @private
+*/
+Phaser.Device._initialize = function () {
+
+    var device = this;
+
+    /**
+    * Check which OS is game running on.
+    */
+    function _checkOS () {
+
+        var ua = navigator.userAgent;
+
+        if (/Playstation Vita/.test(ua))
+        {
+            device.vita = true;
+        }
+        else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua))
+        {
+            device.kindle = true;
+            // This will NOT detect early generations of Kindle Fire, I think there is no reliable way...
+            // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true"
+        }
+        else if (/Android/.test(ua))
+        {
+            device.android = true;
+        }
+        else if (/CrOS/.test(ua))
+        {
+            device.chromeOS = true;
+        }
+        else if (/iP[ao]d|iPhone/i.test(ua))
+        {
+            device.iOS = true;
+        }
+        else if (/Linux/.test(ua))
+        {
+            device.linux = true;
+        }
+        else if (/Mac OS/.test(ua))
+        {
+            device.macOS = true;
+        }
+        else if (/Windows/.test(ua))
+        {
+            device.windows = true;
+        }
+
+        if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua))
+        {
+            device.android = false;
+            device.iOS = false;
+            device.macOS = false;
+            device.windows = true;
+            device.windowsPhone = true;
+        }
+
+        var silk = /Silk/.test(ua); // detected in browsers
+
+        if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS)
+        {
+            device.desktop = true;
+        }
+
+        //  Windows Phone / Table reset
+        if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua))))
+        {
+            device.desktop = false;
+        }
+
+    }
+
+    /**
+    * Check HTML5 features of the host environment.
+    */
+    function _checkFeatures () {
+
+        device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS;
+
+        try {
+            device.localStorage = !!localStorage.getItem;
+        } catch (error) {
+            device.localStorage = false;
+        }
+
+        device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
+        device.fileSystem = !!window['requestFileSystem'];
+
+        device.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); /*Force screencanvas to false*/ canvas.screencanvas = false; return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )();
+        device.webGL = !!device.webGL;
+
+        device.worker = !!window['Worker'];
+
+        device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
+
+        device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true;
+
+        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
+
+        window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
+
+        device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL;
+
+        // Older versions of firefox (< 21) apparently claim support but user media does not actually work
+        if (device.firefox && device.firefoxVersion < 21)
+        {
+            device.getUserMedia = false;
+        }
+
+        // TODO: replace canvasBitBltShift detection with actual feature check
+
+        // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it
+        // is safer to not try and use the fast copy-over method.
+        if (!device.iOS && (device.ie || device.firefox || device.chrome))
+        {
+            device.canvasBitBltShift = true;
+        }
+
+        // Known not to work
+        if (device.safari || device.mobileSafari)
+        {
+            device.canvasBitBltShift = false;
+        }
+
+    }
+
+    /**
+    * Checks/configures various input.
+    */
+    function _checkInput () {
+
+        if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1))
+        {
+            device.touch = true;
+        }
+
+        if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled)
+        {
+            device.mspointer = true;
+        }
+
+        if (!device.cocoonJS)
+        {
+            // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel
+            if ('onwheel' in window || (device.ie && 'WheelEvent' in window))
+            {
+                // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+
+                device.wheelEvent = 'wheel';
+            }
+            else if ('onmousewheel' in window)
+            {
+                // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7.
+                device.wheelEvent = 'mousewheel';
+            }
+            else if (device.firefox && 'MouseScrollEvent' in window)
+            {
+                // FF prior to 17. This should probably be scrubbed.
+                device.wheelEvent = 'DOMMouseScroll';
+            }
+        }
+
+    }
+
+    /**
+    * Checks for support of the Full Screen API.
+    */
+    function _checkFullScreenSupport () {
+
+        var fs = [
+            'requestFullscreen',
+            'requestFullScreen',
+            'webkitRequestFullscreen',
+            'webkitRequestFullScreen',
+            'msRequestFullscreen',
+            'msRequestFullScreen',
+            'mozRequestFullScreen',
+            'mozRequestFullscreen'
+        ];
+
+        var element = document.createElement('div');
+
+        for (var i = 0; i < fs.length; i++)
+        {
+            if (element[fs[i]])
+            {
+                device.fullscreen = true;
+                device.requestFullscreen = fs[i];
+                break;
+            }
+        }
+
+        var cfs = [
+            'cancelFullScreen',
+            'exitFullscreen',
+            'webkitCancelFullScreen',
+            'webkitExitFullscreen',
+            'msCancelFullScreen',
+            'msExitFullscreen',
+            'mozCancelFullScreen',
+            'mozExitFullscreen'
+        ];
+
+        if (device.fullscreen)
+        {
+            for (var i = 0; i < cfs.length; i++)
+            {
+                if (document[cfs[i]])
+                {
+                    device.cancelFullscreen = cfs[i];
+                    break;
+                }
+            }
+        }
+
+        //  Keyboard Input?
+        if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'])
+        {
+            device.fullscreenKeyboard = true;
+        }
+
+    }
+
+    /**
+    * Check what browser is game running in.
+    */
+    function _checkBrowser () {
+
+        var ua = navigator.userAgent;
+
+        if (/Arora/.test(ua))
+        {
+            device.arora = true;
+        }
+        else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone)
+        {
+            device.chrome = true;
+            device.chromeVersion = parseInt(RegExp.$1, 10);
+        }
+        else if (/Epiphany/.test(ua))
+        {
+            device.epiphany = true;
+        }
+        else if (/Firefox\D+(\d+)/.test(ua))
+        {
+            device.firefox = true;
+            device.firefoxVersion = parseInt(RegExp.$1, 10);
+        }
+        else if (/AppleWebKit/.test(ua) && device.iOS)
+        {
+            device.mobileSafari = true;
+        }
+        else if (/MSIE (\d+\.\d+);/.test(ua))
+        {
+            device.ie = true;
+            device.ieVersion = parseInt(RegExp.$1, 10);
+        }
+        else if (/Midori/.test(ua))
+        {
+            device.midori = true;
+        }
+        else if (/Opera/.test(ua))
+        {
+            device.opera = true;
+        }
+        else if (/Safari/.test(ua) && !device.windowsPhone)
+        {
+            device.safari = true;
+        }
+        else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua))
+        {
+            device.ie = true;
+            device.trident = true;
+            device.tridentVersion = parseInt(RegExp.$1, 10);
+            device.ieVersion = parseInt(RegExp.$3, 10);
+        }
+
+        //  Silk gets its own if clause because its ua also contains 'Safari'
+        if (/Silk/.test(ua))
+        {
+            device.silk = true;
+        }
+
+        //  WebApp mode in iOS
+        if (navigator['standalone'])
+        {
+            device.webApp = true;
+        }
+        
+        if (typeof window.cordova !== "undefined")
+        {
+            device.cordova = true;
+        }
+        
+        if (typeof process !== "undefined" && typeof require !== "undefined")
+        {
+            device.node = true;
+        }
+        
+        if (device.node && typeof process.versions === 'object')
+        {
+            device.nodeWebkit = !!process.versions['node-webkit'];
+            
+            device.electron = !!process.versions.electron;
+        }
+        
+        if (navigator['isCocoonJS'])
+        {
+            device.cocoonJS = true;
+        }
+        
+        if (device.cocoonJS)
+        {
+            try {
+                device.cocoonJSApp = (typeof CocoonJS !== "undefined");
+            }
+            catch(error)
+            {
+                device.cocoonJSApp = false;
+            }
+        }
+
+        if (typeof window.ejecta !== "undefined")
+        {
+            device.ejecta = true;
+        }
+
+        if (/Crosswalk/.test(ua))
+        {
+            device.crosswalk = true;
+        }
+
+    }
+
+    /**
+    * Check video support.
+    */
+    function _checkVideo () {
+
+        var videoElement = document.createElement("video");
+        var result = false;
+
+        try {
+            if (result = !!videoElement.canPlayType)
+            {
+                if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ''))
+                {
+                    device.oggVideo = true;
+                }
+
+                if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ''))
+                {
+                    // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
+                    device.h264Video = true;
+                    device.mp4Video = true;
+                }
+
+                if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, ''))
+                {
+                    device.webmVideo = true;
+                }
+
+                if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, ''))
+                {
+                    device.vp9Video = true;
+                }
+
+                if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, ''))
+                {
+                    device.hlsVideo = true;
+                }
+            }
+        } catch (e) {}
+    }
+
+    /**
+    * Check audio support.
+    */
+    function _checkAudio () {
+
+        device.audioData = !!(window['Audio']);
+        device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']);
+        var audioElement = document.createElement('audio');
+        var result = false;
+
+        try {
+            if (result = !!audioElement.canPlayType)
+            {
+                if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''))
+                {
+                    device.ogg = true;
+                }
+
+                if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, ''))
+                {
+                    device.opus = true;
+                }
+
+                if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, ''))
+                {
+                    device.mp3 = true;
+                }
+
+                // Mimetypes accepted:
+                //   developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
+                //   bit.ly/iphoneoscodecs
+                if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''))
+                {
+                    device.wav = true;
+                }
+
+                if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, ''))
+                {
+                    device.m4a = true;
+                }
+
+                if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''))
+                {
+                    device.webm = true;
+                }
+            }
+        } catch (e) {
+        }
+
+    }
+
+    /**
+    * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess.
+    */
+    function _checkDevice () {
+
+        device.pixelRatio = window['devicePixelRatio'] || 1;
+        device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
+        device.iPhone4 = (device.pixelRatio == 2 && device.iPhone);
+        device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
+
+        if (typeof Int8Array !== 'undefined')
+        {
+            device.typedArray = true;
+        }
+        else
+        {
+            device.typedArray = false;
+        }
+
+        if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined')
+        {
+            device.littleEndian = _checkIsLittleEndian();
+            device.LITTLE_ENDIAN = device.littleEndian;
+        }
+
+        device.support32bit = (typeof ArrayBuffer !== "undefined" && typeof Uint8ClampedArray !== "undefined" && typeof Int32Array !== "undefined" && device.littleEndian !== null && _checkIsUint8ClampedImageData());
+
+        navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
+
+        if (navigator.vibrate)
+        {
+            device.vibration = true;
+        }
+
+    }
+
+    /**
+    * Check Little or Big Endian system.
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    */
+    function _checkIsLittleEndian () {
+
+        var a = new ArrayBuffer(4);
+        var b = new Uint8Array(a);
+        var c = new Uint32Array(a);
+
+        b[0] = 0xa1;
+        b[1] = 0xb2;
+        b[2] = 0xc3;
+        b[3] = 0xd4;
+
+        if (c[0] == 0xd4c3b2a1)
+        {
+            return true;
+        }
+
+        if (c[0] == 0xa1b2c3d4)
+        {
+            return false;
+        }
+        else
+        {
+            //  Could not determine endianness
+            return null;
+        }
+
+    }
+
+    /**
+    * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray.
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    */
+    function _checkIsUint8ClampedImageData () {
+
+        if (Uint8ClampedArray === undefined)
+        {
+            return false;
+        }
+
+        var elem = document.createElement('canvas');
+        var ctx = elem.getContext('2d');
+
+        if (!ctx)
+        {
+            return false;
+        }
+
+        var image = ctx.createImageData(1, 1);
+
+        return image.data instanceof Uint8ClampedArray;
+
+    }
+
+    /**
+    * Check whether the host environment support 3D CSS.
+    */
+    function _checkCSS3D () {
+
+        var el = document.createElement('p');
+        var has3d;
+        var transforms = {
+            'webkitTransform': '-webkit-transform',
+            'OTransform': '-o-transform',
+            'msTransform': '-ms-transform',
+            'MozTransform': '-moz-transform',
+            'transform': 'transform'
+        };
+
+        // Add it to the body to get the computed style.
+        document.body.insertBefore(el, null);
+
+        for (var t in transforms)
+        {
+            if (el.style[t] !== undefined)
+            {
+                el.style[t] = "translate3d(1px,1px,1px)";
+                has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
+            }
+        }
+
+        document.body.removeChild(el);
+        device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
+
+    }
+
+    //  Run the checks
+    _checkOS();
+    _checkAudio();
+    _checkVideo();
+    _checkBrowser();
+    _checkCSS3D();
+    _checkDevice();
+    _checkFeatures();
+    _checkFullScreenSupport();
+    _checkInput();
+
+};
+
+/**
+* Check whether the host environment can play audio.
+*
+* @method canPlayAudio
+* @memberof Phaser.Device.prototype
+* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'.
+* @return {boolean} True if the given file type is supported by the browser, otherwise false.
+*/
+Phaser.Device.canPlayAudio = function (type) {
+
+    if (type === 'mp3' && this.mp3)
+    {
+        return true;
+    }
+    else if (type === 'ogg' && (this.ogg || this.opus))
+    {
+        return true;
+    }
+    else if (type === 'm4a' && this.m4a)
+    {
+        return true;
+    }
+    else if (type === 'opus' && this.opus)
+    {
+        return true;
+    }
+    else if (type === 'wav' && this.wav)
+    {
+        return true;
+    }
+    else if (type === 'webm' && this.webm)
+    {
+        return true;
+    }
+
+    return false;
+
+};
+
+/**
+* Check whether the host environment can play video files.
+*
+* @method canPlayVideo
+* @memberof Phaser.Device.prototype
+* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'.
+* @return {boolean} True if the given file type is supported by the browser, otherwise false.
+*/
+Phaser.Device.canPlayVideo = function (type) {
+
+    if (type === 'webm' && (this.webmVideo || this.vp9Video))
+    {
+        return true;
+    }
+    else if (type === 'mp4' && (this.mp4Video || this.h264Video))
+    {
+        return true;
+    }
+    else if ((type === 'ogg' || type === 'ogv') && this.oggVideo)
+    {
+        return true;
+    }
+    else if (type === 'mpeg' && this.hlsVideo)
+    {
+        return true;
+    }
+
+    return false;
+
+};
+
+/**
+* Check whether the console is open.
+* Note that this only works in Firefox with Firebug and earlier versions of Chrome.
+* It used to work in Chrome, but then they removed the ability: {@link http://src.chromium.org/viewvc/blink?view=revision&revision=151136}
+*
+* @method isConsoleOpen
+* @memberof Phaser.Device.prototype
+*/
+Phaser.Device.isConsoleOpen = function () {
+
+    if (window.console && window.console['firebug'])
+    {
+        return true;
+    }
+
+    if (window.console)
+    {
+        console.profile();
+        console.profileEnd();
+
+        if (console.clear)
+        {
+            console.clear();
+        }
+
+        if (console['profiles'])
+        {
+            return console['profiles'].length > 0;
+        }
+    }
+
+    return false;
+
+};
+
+/**
+* Detect if the host is a an Android Stock browser.
+* This is available before the device "ready" event.
+*
+* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices.
+*
+* @example
+* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO;
+* 
+* @method isAndroidStockBrowser
+* @memberof Phaser.Device.prototype
+*/
+Phaser.Device.isAndroidStockBrowser = function () {
+
+    var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);
+    return matches && matches[1] < 537;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* DOM utility class.
+*
+* Provides a useful Window and Element functions as well as cross-browser compatibility buffer.
+*
+* Some code originally derived from {@link https://github.com/ryanve/verge verge}.
+* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013.
+* 
+* @class Phaser.DOM
+* @static
+*/
+Phaser.DOM = {
+
+    /**
+    * Get the [absolute] position of the element relative to the Document.
+    *
+    * The value may vary slightly as the page is scrolled due to rounding errors.
+    *
+    * @method Phaser.DOM.getOffset
+    * @param {DOMElement} element - The targeted element that we want to retrieve the offset.
+    * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset.
+    * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties.
+    */
+    getOffset: function (element, point) {
+
+        point = point || new Phaser.Point();
+
+        var box = element.getBoundingClientRect();
+
+        var scrollTop = Phaser.DOM.scrollY;
+        var scrollLeft = Phaser.DOM.scrollX;
+        var clientTop = document.documentElement.clientTop;
+        var clientLeft = document.documentElement.clientLeft;
+
+        point.x = box.left + scrollLeft - clientLeft;
+        point.y = box.top + scrollTop - clientTop;
+
+        return point;
+
+    },
+
+    /**
+    * A cross-browser element.getBoundingClientRect method with optional cushion.
+    * 
+    * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport.
+    * Its properties match the native rectangle.
+    * The cushion parameter is an amount of pixels (+/-) to cushion the element.
+    * It adjusts the measurements such that it is possible to detect when an element is near the viewport.
+    * 
+    * @method Phaser.DOM.getBounds
+    * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for.
+    * @param {number} [cushion] - A +/- pixel adjustment amount.
+    * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given.
+    */
+    getBounds: function (element, cushion) {
+
+        if (cushion === undefined) { cushion = 0; }
+
+        element = element && !element.nodeType ? element[0] : element;
+
+        if (!element || element.nodeType !== 1)
+        {
+            return false;
+        }
+        else
+        {
+            return this.calibrate(element.getBoundingClientRect(), cushion);
+        }
+
+    },
+
+    /**
+    * Calibrates element coordinates for `inLayoutViewport` checks.
+    *
+    * @method Phaser.DOM.calibrate
+    * @private
+    * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}`
+    * @param {number} [cushion] - A value to adjust the coordinates by.
+    * @return {object} The calibrated element coordinates
+    */
+    calibrate: function (coords, cushion) {
+
+        cushion = +cushion || 0;
+
+        var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 };
+
+        output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion);
+        output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion);
+
+        return output;
+
+    },
+
+    /**
+    * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element)    
+    * 
+    * @method Phaser.DOM.getAspectRatio
+    * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods.
+    * @return {number} The aspect ratio.
+    */
+    getAspectRatio: function (object) {
+
+        object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object;
+
+        var w = object['width'];
+        var h = object['height'];
+
+        if (typeof w === 'function')
+        {
+            w = w.call(object);
+        }
+
+        if (typeof h === 'function')
+        {
+            h = h.call(object);
+        }
+
+        return w / h;
+
+    },
+
+    /**
+    * Tests if the given DOM element is within the Layout viewport.
+    * 
+    * The optional cushion parameter allows you to specify a distance.
+    * 
+    * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it.
+    * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it.
+    * 
+    * @method Phaser.DOM.inLayoutViewport
+    * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas.
+    * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport.
+    * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it.
+    */
+    inLayoutViewport: function (element, cushion) {
+
+        var r = this.getBounds(element, cushion);
+
+        return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height;
+
+    },
+
+    /**
+    * Returns the device screen orientation.
+    *
+    * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'.
+    *
+    * Order of resolving:
+    * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers.
+    * - Screen size ratio check - If fallback is 'screen', suited for desktops.
+    * - Viewport size ratio check - If fallback is 'viewport', suited for mobile.
+    * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track.
+    * - Media query
+    * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..)
+    *
+    * See
+    * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation)
+    * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation)
+    * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx
+    * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries
+    * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation
+    * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation
+    *
+    * @method Phaser.DOM.getScreenOrientation
+    * @protected
+    * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'.
+    */
+    getScreenOrientation: function (primaryFallback) {
+
+        var screen = window.screen;
+        var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
+
+        if (orientation && typeof orientation.type === 'string')
+        {
+            // Screen Orientation API specification
+            return orientation.type;
+        }
+        else if (typeof orientation === 'string')
+        {
+            // moz/ms-orientation are strings
+            return orientation;
+        }
+
+        var PORTRAIT = 'portrait-primary';
+        var LANDSCAPE = 'landscape-primary';
+        
+        if (primaryFallback === 'screen')
+        {
+            return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE;
+        }
+        else if (primaryFallback === 'viewport')
+        {
+            return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE;
+        }
+        else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number')
+        {
+            // This may change by device based on "natural" orientation.
+            return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE;
+        }
+        else if (window.matchMedia)
+        {
+            if (window.matchMedia("(orientation: portrait)").matches)
+            {
+                return PORTRAIT;
+            }
+            else if (window.matchMedia("(orientation: landscape)").matches)
+            {
+                return LANDSCAPE;
+            }
+        }
+
+        return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE;
+
+    },
+
+    /**
+    * The bounds of the Visual viewport, as discussed in 
+    * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one}
+    * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers.   
+    *
+    * Supported mobile:
+    *   iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16
+    *
+    * The properties change dynamically.
+    *
+    * @type {Phaser.Rectangle}
+    * @property {number} x - Scroll, left offset - eg. "scrollX"
+    * @property {number} y - Scroll, top offset - eg. "scrollY"
+    * @property {number} width - Viewport width in pixels.
+    * @property {number} height - Viewport height in pixels.
+    * @readonly
+    */
+    visualBounds: new Phaser.Rectangle(),
+
+    /**
+    * The bounds of the Layout viewport, as discussed in 
+    * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two};
+    * but honoring the constraints as specified applicable viewport meta-tag.
+    *
+    * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see
+    * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}).
+    *
+    * This is _not_ representative of the Visual bounds: in particular the non-primary axis will
+    * generally be significantly larger than the screen height on mobile devices when running with a
+    * constrained viewport.
+    *
+    * The properties change dynamically.
+    *
+    * @type {Phaser.Rectangle}
+    * @property {number} width - Viewport width in pixels.
+    * @property {number} height - Viewport height in pixels.
+    * @readonly
+    */
+    layoutBounds: new Phaser.Rectangle(),
+
+    /**
+    * The size of the document / Layout viewport.
+    *
+    * This incorrectly reports the dimensions in IE.
+    *
+    * The properties change dynamically.
+    *
+    * @type {Phaser.Rectangle}
+    * @property {number} width - Document width in pixels.
+    * @property {number} height - Document height in pixels.
+    * @readonly
+    */
+    documentBounds: new Phaser.Rectangle()
+
+};
+
+Phaser.Device.whenReady(function (device) {
+
+    // All target browsers should support page[XY]Offset.
+    var scrollX = window && ('pageXOffset' in window) ?
+        function () { return window.pageXOffset; } :
+        function () { return document.documentElement.scrollLeft; };
+
+    var scrollY = window && ('pageYOffset' in window) ?
+        function () { return window.pageYOffset; } :
+        function () { return document.documentElement.scrollTop; };
+
+    /**
+    * A cross-browser window.scrollX.
+    *
+    * @name Phaser.DOM.scrollX
+    * @property {number} scrollX
+    * @readonly
+    * @protected
+    */
+    Object.defineProperty(Phaser.DOM, "scrollX", {
+        get: scrollX
+    });
+
+    /**
+    * A cross-browser window.scrollY.
+    *
+    * @name Phaser.DOM.scrollY
+    * @property {number} scrollY
+    * @readonly
+    * @protected
+    */
+    Object.defineProperty(Phaser.DOM, "scrollY", {
+        get: scrollY
+    });
+
+    Object.defineProperty(Phaser.DOM.visualBounds, "x", {
+        get: scrollX
+    });
+
+    Object.defineProperty(Phaser.DOM.visualBounds, "y", {
+        get: scrollY
+    });
+
+    Object.defineProperty(Phaser.DOM.layoutBounds, "x", {
+        value: 0
+    });
+
+    Object.defineProperty(Phaser.DOM.layoutBounds, "y", {
+        value: 0
+    });
+
+    var treatAsDesktop = device.desktop &&
+        (document.documentElement.clientWidth <= window.innerWidth) &&
+        (document.documentElement.clientHeight <= window.innerHeight);
+
+    // Desktop browsers align the layout viewport with the visual viewport.
+    // This differs from mobile browsers with their zooming design.
+    // Ref. http://quirksmode.org/mobile/tableViewport.html  
+    if (treatAsDesktop)
+    {
+
+        // PST- When scrollbars are not included this causes upstream issues in ScaleManager.
+        // So reverted to the old "include scrollbars."
+        var clientWidth = function () {
+            return Math.max(window.innerWidth, document.documentElement.clientWidth);
+        };
+        var clientHeight = function () {
+            return Math.max(window.innerHeight, document.documentElement.clientHeight);
+        };
+
+        // Interested in area sans-scrollbar
+        Object.defineProperty(Phaser.DOM.visualBounds, "width", {
+            get: clientWidth
+        });
+
+        Object.defineProperty(Phaser.DOM.visualBounds, "height", {
+            get: clientHeight
+        });
+
+        Object.defineProperty(Phaser.DOM.layoutBounds, "width", {
+            get: clientWidth
+        });
+
+        Object.defineProperty(Phaser.DOM.layoutBounds, "height", {
+            get: clientHeight
+        });
+
+    } else {
+
+        Object.defineProperty(Phaser.DOM.visualBounds, "width", {
+            get: function () {
+                return window.innerWidth;
+            }
+        });
+
+        Object.defineProperty(Phaser.DOM.visualBounds, "height", {
+            get: function () {
+                return window.innerHeight;
+            }
+        });
+
+        Object.defineProperty(Phaser.DOM.layoutBounds, "width", {
+
+            get: function () {
+                var a = document.documentElement.clientWidth;
+                var b = window.innerWidth;
+
+                return a < b ? b : a; // max
+            }
+
+        });
+
+        Object.defineProperty(Phaser.DOM.layoutBounds, "height", {
+
+            get: function () {
+                var a = document.documentElement.clientHeight;
+                var b = window.innerHeight;
+
+                return a < b ? b : a; // max
+            }
+
+        });
+
+    }
+
+    // For Phaser.DOM.documentBounds
+    // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html
+
+    Object.defineProperty(Phaser.DOM.documentBounds, "x", {
+        value: 0
+    });
+
+    Object.defineProperty(Phaser.DOM.documentBounds, "y", {
+        value: 0
+    });
+
+    Object.defineProperty(Phaser.DOM.documentBounds, "width", {
+
+        get: function () {
+            var d = document.documentElement;
+            return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth);
+        }
+
+    });
+
+    Object.defineProperty(Phaser.DOM.documentBounds, "height", {
+
+        get: function () {
+            var d = document.documentElement;
+            return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight);
+        }
+
+    });
+
+}, null, true);
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, including styles, offset and aspect ratio.
+*
+* @class Phaser.Canvas
+* @static
+*/
+Phaser.Canvas = {
+
+    /**
+    * Creates a `canvas` DOM element. The element is not automatically added to the document.
+    *
+    * @method Phaser.Canvas.create
+    * @param {number} [width=256] - The width of the canvas element.
+    * @param {number} [height=256] - The height of the canvas element..
+    * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set.
+    * @return {HTMLCanvasElement} The newly created canvas element.
+    */
+    create: function (width, height, id) {
+
+        width = width || 256;
+        height = height || 256;
+
+        var canvas = document.createElement('canvas');
+
+        if (typeof id === 'string' && id !== '')
+        {
+            canvas.id = id;
+        }
+
+        canvas.width = width;
+        canvas.height = height;
+
+        canvas.style.display = 'block';
+
+        return canvas;
+
+    },
+
+    /**
+    * Sets the background color behind the canvas. This changes the canvas style property.
+    *
+    * @method Phaser.Canvas.setBackgroundColor
+    * @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
+    * @param {string} [color] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
+    * @return {HTMLCanvasElement} Returns the source canvas.
+    */
+    setBackgroundColor: function (canvas, color) {
+
+        color = color || 'rgb(0,0,0)';
+
+        canvas.style.backgroundColor = color;
+
+        return canvas;
+
+    },
+
+    /**
+    * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
+    *
+    * @method Phaser.Canvas.setTouchAction
+    * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
+    * @param {string} [value] - The touch action to set. Defaults to 'none'.
+    * @return {HTMLCanvasElement} The source canvas.
+    */
+    setTouchAction: function (canvas, value) {
+
+        value = value || 'none';
+
+        canvas.style.msTouchAction = value;
+        canvas.style['ms-touch-action'] = value;
+        canvas.style['touch-action'] = value;
+
+        return canvas;
+
+    },
+
+    /**
+    * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
+    *
+    * @method Phaser.Canvas.setUserSelect
+    * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
+    * @param {string} [value] - The touch action to set. Defaults to 'none'.
+    * @return {HTMLCanvasElement} The source canvas.
+    */
+    setUserSelect: function (canvas, value) {
+
+        value = value || 'none';
+
+        canvas.style['-webkit-touch-callout'] = value;
+        canvas.style['-webkit-user-select'] = value;
+        canvas.style['-khtml-user-select'] = value;
+        canvas.style['-moz-user-select'] = value;
+        canvas.style['-ms-user-select'] = value;
+        canvas.style['user-select'] = value;
+        canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
+
+        return canvas;
+
+    },
+
+    /**
+    * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
+    * If no parent is given it will be added as a child of the document.body.
+    *
+    * @method Phaser.Canvas.addToDOM
+    * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM.
+    * @param {string|HTMLElement} parent - The DOM element to add the canvas to.
+    * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element.
+    * @return {HTMLCanvasElement} Returns the source canvas.
+    */
+    addToDOM: function (canvas, parent, overflowHidden) {
+
+        var target;
+
+        if (overflowHidden === undefined) { overflowHidden = true; }
+
+        if (parent)
+        {
+            if (typeof parent === 'string')
+            {
+                // hopefully an element ID
+                target = document.getElementById(parent);
+            }
+            else if (typeof parent === 'object' && parent.nodeType === 1)
+            {
+                // quick test for a HTMLelement
+                target = parent;
+            }
+        }
+
+        // Fallback, covers an invalid ID and a non HTMLelement object
+        if (!target)
+        {
+            target = document.body;
+        }
+
+        if (overflowHidden && target.style)
+        {
+            target.style.overflow = 'hidden';
+        }
+
+        target.appendChild(canvas);
+
+        return canvas;
+
+    },
+
+    /**
+    * Removes the given canvas element from the DOM.
+    *
+    * @method Phaser.Canvas.removeFromDOM
+    * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM.
+    */
+    removeFromDOM: function (canvas) {
+
+        if (canvas.parentNode)
+        {
+            canvas.parentNode.removeChild(canvas);
+        }
+
+    },
+
+    /**
+    * Sets the transform of the given canvas to the matrix values provided.
+    *
+    * @method Phaser.Canvas.setTransform
+    * @param {CanvasRenderingContext2D} context - The context to set the transform on.
+    * @param {number} translateX - The value to translate horizontally by.
+    * @param {number} translateY - The value to translate vertically by.
+    * @param {number} scaleX - The value to scale horizontally by.
+    * @param {number} scaleY - The value to scale vertically by.
+    * @param {number} skewX - The value to skew horizontaly by.
+    * @param {number} skewY - The value to skew vertically by.
+    * @return {CanvasRenderingContext2D} Returns the source context.
+    */
+    setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
+
+        context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
+
+        return context;
+
+    },
+
+    /**
+    * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
+    * By default browsers have image smoothing enabled, which isn't always what you visually want, especially
+    * when using pixel art in a game. Note that this sets the property on the context itself, so that any image
+    * drawn to the context will be affected. This sets the property across all current browsers but support is
+    * patchy on earlier browsers, especially on mobile.
+    *
+    * @method Phaser.Canvas.setSmoothingEnabled
+    * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
+    * @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
+    * @return {CanvasRenderingContext2D} Returns the source context.
+    */
+    setSmoothingEnabled: function (context, value) {
+
+        var vendor = [ 'i', 'mozI', 'oI', 'webkitI', 'msI' ];
+
+        for (var prefix in vendor)
+        {
+            var s = vendor[prefix] + 'mageSmoothingEnabled';
+
+            if (s in context)
+            {
+                context[s] = value;
+                return context;
+            }
+        }
+
+        return context;
+
+    },
+
+    /**
+     * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`.
+     *
+     * @method Phaser.Canvas.getSmoothingEnabled
+     * @param {CanvasRenderingContext2D} context - The context to check for smoothing on.
+     * @return {boolean} True if the given context has image smoothing enabled, otherwise false.
+     */
+    getSmoothingEnabled: function (context) {
+
+        return (context['imageSmoothingEnabled'] || context['mozImageSmoothingEnabled'] || context['oImageSmoothingEnabled'] || context['webkitImageSmoothingEnabled'] || context['msImageSmoothingEnabled']);
+
+    },
+
+    /**
+    * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit).
+    * Note that if this doesn't given the desired result then see the setSmoothingEnabled.
+    *
+    * @method Phaser.Canvas.setImageRenderingCrisp
+    * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
+    * @return {HTMLCanvasElement} Returns the source canvas.
+    */
+    setImageRenderingCrisp: function (canvas) {
+
+        canvas.style['image-rendering'] = 'optimizeSpeed';
+        canvas.style['image-rendering'] = 'crisp-edges';
+        canvas.style['image-rendering'] = '-moz-crisp-edges';
+        canvas.style['image-rendering'] = '-webkit-optimize-contrast';
+        canvas.style['image-rendering'] = 'optimize-contrast';
+        canvas.style['image-rendering'] = 'pixelated';
+        canvas.style.msInterpolationMode = 'nearest-neighbor';
+
+        return canvas;
+
+    },
+
+    /**
+    * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
+    * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
+    *
+    * @method Phaser.Canvas.setImageRenderingBicubic
+    * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
+    * @return {HTMLCanvasElement} Returns the source canvas.
+    */
+    setImageRenderingBicubic: function (canvas) {
+
+        canvas.style['image-rendering'] = 'auto';
+        canvas.style.msInterpolationMode = 'bicubic';
+
+        return canvas;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Abstracts away the use of RAF or setTimeOut for the core game update loop.
+*
+* @class Phaser.RequestAnimationFrame
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available.
+*/
+Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) {
+
+    if (forceSetTimeOut === undefined) { forceSetTimeOut = false; }
+
+    /**
+    * @property {Phaser.Game} game - The currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
+    * @default
+    */
+    this.isRunning = false;
+
+    /**
+    * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available.
+    */
+    this.forceSetTimeOut = forceSetTimeOut;
+
+    var vendors = [
+        'ms',
+        'moz',
+        'webkit',
+        'o'
+    ];
+
+    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++)
+    {
+        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
+        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
+    }
+
+    /**
+    * @property {boolean} _isSetTimeOut  - true if the browser is using setTimeout instead of raf.
+    * @private
+    */
+    this._isSetTimeOut = false;
+
+    /**
+    * @property {function} _onLoop - The function called by the update.
+    * @private
+    */
+    this._onLoop = null;
+
+    /**
+    * @property {number} _timeOutID - The callback ID used when calling cancel.
+    * @private
+    */
+    this._timeOutID = null;
+
+};
+
+Phaser.RequestAnimationFrame.prototype = {
+
+    /**
+    * Starts the requestAnimationFrame running or setTimeout if unavailable in browser
+    * @method Phaser.RequestAnimationFrame#start
+    */
+    start: function () {
+
+        this.isRunning = true;
+
+        var _this = this;
+
+        if (!window.requestAnimationFrame || this.forceSetTimeOut)
+        {
+            this._isSetTimeOut = true;
+
+            this._onLoop = function () {
+                return _this.updateSetTimeout();
+            };
+
+            this._timeOutID = window.setTimeout(this._onLoop, 0);
+        }
+        else
+        {
+            this._isSetTimeOut = false;
+
+            this._onLoop = function (time) {
+                return _this.updateRAF(time);
+            };
+
+            this._timeOutID = window.requestAnimationFrame(this._onLoop);
+        }
+
+    },
+
+    /**
+    * The update method for the requestAnimationFrame
+    * @method Phaser.RequestAnimationFrame#updateRAF
+    * 
+    */
+    updateRAF: function (rafTime) {
+
+        // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below)
+        this.game.update(Math.floor(rafTime));
+
+        this._timeOutID = window.requestAnimationFrame(this._onLoop);
+
+    },
+
+    /**
+    * The update method for the setTimeout.
+    * @method Phaser.RequestAnimationFrame#updateSetTimeout
+    */
+    updateSetTimeout: function () {
+
+        this.game.update(Date.now());
+
+        this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall);
+
+    },
+
+    /**
+    * Stops the requestAnimationFrame from running.
+    * @method Phaser.RequestAnimationFrame#stop
+    */
+    stop: function () {
+
+        if (this._isSetTimeOut)
+        {
+            clearTimeout(this._timeOutID);
+        }
+        else
+        {
+            window.cancelAnimationFrame(this._timeOutID);
+        }
+
+        this.isRunning = false;
+
+    },
+
+    /**
+    * Is the browser using setTimeout?
+    * @method Phaser.RequestAnimationFrame#isSetTimeOut
+    * @return {boolean}
+    */
+    isSetTimeOut: function () {
+        return this._isSetTimeOut;
+    },
+
+    /**
+    * Is the browser using requestAnimationFrame?
+    * @method Phaser.RequestAnimationFrame#isRAF
+    * @return {boolean}
+    */
+    isRAF: function () {
+        return (this._isSetTimeOut === false);
+    }
+
+};
+
+Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A collection of useful mathematical functions.
+*
+* These are normally accessed through `game.math`.
+*
+* @class Phaser.Math
+* @static
+* @see {@link Phaser.Utils}
+* @see {@link Phaser.ArrayUtils}
+*/
+Phaser.Math = {
+
+    /**
+    * Twice PI.
+    * @property {number} Phaser.Math#PI2
+    * @default ~6.283
+    */
+    PI2: Math.PI * 2,
+
+    /**
+    * Two number are fuzzyEqual if their difference is less than epsilon.
+    *
+    * @method Phaser.Math#fuzzyEqual
+    * @param {number} a
+    * @param {number} b
+    * @param {number} [epsilon=(small value)]
+    * @return {boolean} True if |a-b|<epsilon
+    */
+    fuzzyEqual: function (a, b, epsilon) {
+        if (epsilon === undefined) { epsilon = 0.0001; }
+        return Math.abs(a - b) < epsilon;
+    },
+
+    /**
+    * `a` is fuzzyLessThan `b` if it is less than b + epsilon.
+    *
+    * @method Phaser.Math#fuzzyLessThan
+    * @param {number} a
+    * @param {number} b
+    * @param {number} [epsilon=(small value)]
+    * @return {boolean} True if a<b+epsilon
+    */
+    fuzzyLessThan: function (a, b, epsilon) {
+        if (epsilon === undefined) { epsilon = 0.0001; }
+        return a < b + epsilon;
+    },
+
+    /**
+    * `a` is fuzzyGreaterThan `b` if it is more than b - epsilon.
+    *
+    * @method Phaser.Math#fuzzyGreaterThan
+    * @param {number} a
+    * @param {number} b
+    * @param {number} [epsilon=(small value)]
+    * @return {boolean} True if a>b+epsilon
+    */
+    fuzzyGreaterThan: function (a, b, epsilon) {
+        if (epsilon === undefined) { epsilon = 0.0001; }
+        return a > b - epsilon;
+    },
+
+    /**
+    * @method Phaser.Math#fuzzyCeil
+    *
+    * @param {number} val
+    * @param {number} [epsilon=(small value)]
+    * @return {boolean} ceiling(val-epsilon)
+    */
+    fuzzyCeil: function (val, epsilon) {
+        if (epsilon === undefined) { epsilon = 0.0001; }
+        return Math.ceil(val - epsilon);
+    },
+
+    /**
+    * @method Phaser.Math#fuzzyFloor
+    *
+    * @param {number} val
+    * @param {number} [epsilon=(small value)]
+    * @return {boolean} floor(val-epsilon)
+    */
+    fuzzyFloor: function (val, epsilon) {
+        if (epsilon === undefined) { epsilon = 0.0001; }
+        return Math.floor(val + epsilon);
+    },
+
+    /**
+    * Averages all values passed to the function and returns the result.
+    *
+    * @method Phaser.Math#average
+    * @params {...number} The numbers to average
+    * @return {number} The average of all given values.
+    */
+    average: function () {
+
+        var sum = 0;
+
+        for (var i = 0; i < arguments.length; i++) {
+            sum += (+arguments[i]);
+        }
+
+        return sum / arguments.length;
+
+    },
+
+    /**
+    * @method Phaser.Math#shear
+    * @param {number} n
+    * @return {number} n mod 1
+    */
+    shear: function (n) {
+        return n % 1;
+    },
+
+    /**
+    * Snap a value to nearest grid slice, using rounding.
+    *
+    * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15.
+    *
+    * @method Phaser.Math#snapTo
+    * @param {number} input - The value to snap.
+    * @param {number} gap - The interval gap of the grid.
+    * @param {number} [start] - Optional starting offset for gap.
+    * @return {number}
+    */
+    snapTo: function (input, gap, start) {
+
+        if (start === undefined) { start = 0; }
+
+        if (gap === 0) {
+            return input;
+        }
+
+        input -= start;
+        input = gap * Math.round(input / gap);
+
+        return start + input;
+
+    },
+
+    /**
+    * Snap a value to nearest grid slice, using floor.
+    *
+    * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. 
+    * As will 14 snap to 10... but 16 will snap to 15.
+    *
+    * @method Phaser.Math#snapToFloor
+    * @param {number} input - The value to snap.
+    * @param {number} gap - The interval gap of the grid.
+    * @param {number} [start] - Optional starting offset for gap.
+    * @return {number}
+    */
+    snapToFloor: function (input, gap, start) {
+
+        if (start === undefined) { start = 0; }
+
+        if (gap === 0) {
+            return input;
+        }
+
+        input -= start;
+        input = gap * Math.floor(input / gap);
+
+        return start + input;
+
+    },
+
+    /**
+    * Snap a value to nearest grid slice, using ceil.
+    *
+    * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15.
+    * As will 14 will snap to 15... but 16 will snap to 20.
+    *
+    * @method Phaser.Math#snapToCeil
+    * @param {number} input - The value to snap.
+    * @param {number} gap - The interval gap of the grid.
+    * @param {number} [start] - Optional starting offset for gap.
+    * @return {number}
+    */
+    snapToCeil: function (input, gap, start) {
+
+        if (start === undefined) { start = 0; }
+
+        if (gap === 0) {
+            return input;
+        }
+
+        input -= start;
+        input = gap * Math.ceil(input / gap);
+
+        return start + input;
+
+    },
+
+    /**
+    * Round to some place comparative to a `base`, default is 10 for decimal place.
+    * The `place` is represented by the power applied to `base` to get that place.
+    *
+    *     e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
+    *
+    *     roundTo(2000/7,3) === 0
+    *     roundTo(2000/7,2) == 300
+    *     roundTo(2000/7,1) == 290
+    *     roundTo(2000/7,0) == 286
+    *     roundTo(2000/7,-1) == 285.7
+    *     roundTo(2000/7,-2) == 285.71
+    *     roundTo(2000/7,-3) == 285.714
+    *     roundTo(2000/7,-4) == 285.7143
+    *     roundTo(2000/7,-5) == 285.71429
+    *
+    *     roundTo(2000/7,3,2)  == 288       -- 100100000
+    *     roundTo(2000/7,2,2)  == 284       -- 100011100
+    *     roundTo(2000/7,1,2)  == 286       -- 100011110
+    *     roundTo(2000/7,0,2)  == 286       -- 100011110
+    *     roundTo(2000/7,-1,2) == 285.5     -- 100011101.1
+    *     roundTo(2000/7,-2,2) == 285.75    -- 100011101.11
+    *     roundTo(2000/7,-3,2) == 285.75    -- 100011101.11
+    *     roundTo(2000/7,-4,2) == 285.6875  -- 100011101.1011
+    *     roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
+    *
+    * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
+    * because we are rounding 100011.1011011011011011 which rounds up.
+    *
+    * @method Phaser.Math#roundTo
+    * @param {number} value - The value to round.
+    * @param {number} place - The place to round to.
+    * @param {number} base - The base to round in... default is 10 for decimal.
+    * @return {number}
+    */
+    roundTo: function (value, place, base) {
+
+        if (place === undefined) { place = 0; }
+        if (base === undefined) { base = 10; }
+
+        var p = Math.pow(base, -place);
+
+        return Math.round(value * p) / p;
+
+    },
+
+    /**
+    * @method Phaser.Math#floorTo
+    * @param {number} value - The value to round.
+    * @param {number} place - The place to round to.
+    * @param {number} base - The base to round in... default is 10 for decimal.
+    * @return {number}
+    */
+    floorTo: function (value, place, base) {
+
+        if (place === undefined) { place = 0; }
+        if (base === undefined) { base = 10; }
+
+        var p = Math.pow(base, -place);
+
+        return Math.floor(value * p) / p;
+
+    },
+
+    /**
+    * @method Phaser.Math#ceilTo
+    * @param {number} value - The value to round.
+    * @param {number} place - The place to round to.
+    * @param {number} base - The base to round in... default is 10 for decimal.
+    * @return {number}
+    */
+    ceilTo: function (value, place, base) {
+
+        if (place === undefined) { place = 0; }
+        if (base === undefined) { base = 10; }
+
+        var p = Math.pow(base, -place);
+
+        return Math.ceil(value * p) / p;
+
+    },
+
+    /**
+    * Find the angle of a segment from (x1, y1) -> (x2, y2).
+    * @method Phaser.Math#angleBetween
+    * @param {number} x1
+    * @param {number} y1
+    * @param {number} x2
+    * @param {number} y2
+    * @return {number} The angle, in radians.
+    */
+    angleBetween: function (x1, y1, x2, y2) {
+        return Math.atan2(y2 - y1, x2 - x1);
+    },
+
+    /**
+    * Find the angle of a segment from (x1, y1) -> (x2, y2).
+    * Note that the difference between this method and Math.angleBetween is that this assumes the y coordinate travels
+    * down the screen.
+    *
+    * @method Phaser.Math#angleBetweenY
+    * @param {number} x1
+    * @param {number} y1
+    * @param {number} x2
+    * @param {number} y2
+    * @return {number} The angle, in radians.
+    */
+    angleBetweenY: function (x1, y1, x2, y2) {
+        return Math.atan2(x2 - x1, y2 - y1);
+    },
+
+    /**
+    * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
+    * @method Phaser.Math#angleBetweenPoints
+    * @param {Phaser.Point} point1
+    * @param {Phaser.Point} point2
+    * @return {number} The angle, in radians.
+    */
+    angleBetweenPoints: function (point1, point2) {
+        return Math.atan2(point2.y - point1.y, point2.x - point1.x);
+    },
+
+    /**
+    * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
+    * @method Phaser.Math#angleBetweenPointsY
+    * @param {Phaser.Point} point1
+    * @param {Phaser.Point} point2
+    * @return {number} The angle, in radians.
+    */
+    angleBetweenPointsY: function (point1, point2) {
+        return Math.atan2(point2.x - point1.x, point2.y - point1.y);
+    },
+
+    /**
+    * Reverses an angle.
+    * @method Phaser.Math#reverseAngle
+    * @param {number} angleRad - The angle to reverse, in radians.
+    * @return {number} Returns the reverse angle, in radians.
+    */
+    reverseAngle: function (angleRad) {
+        return this.normalizeAngle(angleRad + Math.PI, true);
+    },
+
+    /**
+    * Normalizes an angle to the [0,2pi) range.
+    * @method Phaser.Math#normalizeAngle
+    * @param {number} angleRad - The angle to normalize, in radians.
+    * @return {number} Returns the angle, fit within the [0,2pi] range, in radians.
+    */
+    normalizeAngle: function (angleRad) {
+
+        angleRad = angleRad % (2 * Math.PI);
+        return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI;
+
+    },
+
+    /**
+    * Adds the given amount to the value, but never lets the value go over the specified maximum.
+    *
+    * @method Phaser.Math#maxAdd
+    * @param {number} value - The value to add the amount to.
+    * @param {number} amount - The amount to add to the value.
+    * @param {number} max - The maximum the value is allowed to be.
+    * @return {number}
+    */
+    maxAdd: function (value, amount, max) {
+        return Math.min(value + amount, max);
+    },
+
+    /**
+    * Subtracts the given amount from the value, but never lets the value go below the specified minimum.
+    *
+    * @method Phaser.Math#minSub
+    * @param {number} value - The base value.
+    * @param {number} amount - The amount to subtract from the base value.
+    * @param {number} min - The minimum the value is allowed to be.
+    * @return {number} The new value.
+    */
+    minSub: function (value, amount, min) {
+        return Math.max(value - amount, min);
+    },
+
+    /**
+    * Ensures that the value always stays between min and max, by wrapping the value around.
+    *
+    * If `max` is not larger than `min` the result is 0.
+    *
+    * @method Phaser.Math#wrap
+    * @param {number} value - The value to wrap.
+    * @param {number} min - The minimum the value is allowed to be.
+    * @param {number} max - The maximum the value is allowed to be, should be larger than `min`.
+    * @return {number} The wrapped value.
+    */
+    wrap: function (value, min, max) {
+
+        var range = max - min;
+
+        if (range <= 0)
+        {
+            return 0;
+        }
+
+        var result = (value - min) % range;
+
+        if (result < 0)
+        {
+            result += range;
+        }
+
+        return result + min;
+
+    },
+
+    /**
+    * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
+    *
+    * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative.
+    *
+    * @method Phaser.Math#wrapValue
+    * @param {number} value - The value to add the amount to.
+    * @param {number} amount - The amount to add to the value.
+    * @param {number} max - The maximum the value is allowed to be.
+    * @return {number} The wrapped value.
+    */
+    wrapValue: function (value, amount, max) {
+
+        var diff;
+        value = Math.abs(value);
+        amount = Math.abs(amount);
+        max = Math.abs(max);
+        diff = (value + amount) % max;
+
+        return diff;
+
+    },
+
+    /**
+    * Returns true if the number given is odd.
+    *
+    * @method Phaser.Math#isOdd
+    * @param {integer} n - The number to check.
+    * @return {boolean} True if the given number is odd. False if the given number is even.
+    */
+    isOdd: function (n) {
+        // Does not work with extremely large values
+        return !!(n & 1);
+    },
+
+    /**
+    * Returns true if the number given is even.
+    *
+    * @method Phaser.Math#isEven
+    * @param {integer} n - The number to check.
+    * @return {boolean} True if the given number is even. False if the given number is odd.
+    */
+    isEven: function (n) {
+        // Does not work with extremely large values
+        return !(n & 1);
+    },
+
+    /**
+    * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters.
+    *
+    * Prefer the standard `Math.min` function when appropriate.
+    *
+    * @method Phaser.Math#min
+    * @return {number} The lowest value from those given.
+    * @see {@link http://jsperf.com/math-s-min-max-vs-homemade}
+    */
+    min: function () {
+
+        if (arguments.length === 1 && typeof arguments[0] === 'object')
+        {
+            var data = arguments[0];
+        }
+        else
+        {
+            var data = arguments;
+        }
+
+        for (var i = 1, min = 0, len = data.length; i < len; i++)
+        {
+            if (data[i] < data[min])
+            {
+                min = i;
+            }
+        }
+
+        return data[min];
+
+    },
+
+    /**
+    * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters.
+    *
+    * Prefer the standard `Math.max` function when appropriate.
+    *
+    * @method Phaser.Math#max
+    * @return {number} The largest value from those given.
+    * @see {@link http://jsperf.com/math-s-min-max-vs-homemade}
+    */
+    max: function () {
+
+        if (arguments.length === 1 && typeof arguments[0] === 'object')
+        {
+            var data = arguments[0];
+        }
+        else
+        {
+            var data = arguments;
+        }
+
+        for (var i = 1, max = 0, len = data.length; i < len; i++)
+        {
+            if (data[i] > data[max])
+            {
+                max = i;
+            }
+        }
+
+        return data[max];
+
+    },
+
+    /**
+    * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters.
+    * It will find the lowest matching property value from the given objects.
+    *
+    * @method Phaser.Math#minProperty
+    * @return {number} The lowest value from those given.
+    */
+    minProperty: function (property) {
+
+        if (arguments.length === 2 && typeof arguments[1] === 'object')
+        {
+            var data = arguments[1];
+        }
+        else
+        {
+            var data = arguments.slice(1);
+        }
+
+        for (var i = 1, min = 0, len = data.length; i < len; i++)
+        {
+            if (data[i][property] < data[min][property])
+            {
+                min = i;
+            }
+        }
+
+        return data[min][property];
+
+    },
+
+    /**
+    * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters.
+    * It will find the largest matching property value from the given objects.
+    *
+    * @method Phaser.Math#maxProperty
+    * @return {number} The largest value from those given.
+    */
+    maxProperty: function (property) {
+
+        if (arguments.length === 2 && typeof arguments[1] === 'object')
+        {
+            var data = arguments[1];
+        }
+        else
+        {
+            var data = arguments.slice(1);
+        }
+
+        for (var i = 1, max = 0, len = data.length; i < len; i++)
+        {
+            if (data[i][property] > data[max][property])
+            {
+                max = i;
+            }
+        }
+
+        return data[max][property];
+
+    },
+
+    /**
+    * Keeps an angle value between -180 and +180; or -PI and PI if radians.
+    *
+    * @method Phaser.Math#wrapAngle
+    * @param {number} angle - The angle value to wrap
+    * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected.
+    * @return {number} The new angle value; will be the same as the input angle if it was within bounds.
+    */
+    wrapAngle: function (angle, radians) {
+
+        return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180);
+
+    },
+
+    /**
+    * A Linear Interpolation Method, mostly used by Phaser.Tween.
+    *
+    * @method Phaser.Math#linearInterpolation
+    * @param {Array} v - The input array of values to interpolate between.
+    * @param {number} k - The percentage of interpolation, between 0 and 1.
+    * @return {number} The interpolated value
+    */
+    linearInterpolation: function (v, k) {
+
+        var m = v.length - 1;
+        var f = m * k;
+        var i = Math.floor(f);
+
+        if (k < 0)
+        {
+            return this.linear(v[0], v[1], f);
+        }
+
+        if (k > 1)
+        {
+            return this.linear(v[m], v[m - 1], m - f);
+        }
+
+        return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
+
+    },
+
+    /**
+    * A Bezier Interpolation Method, mostly used by Phaser.Tween.
+    *
+    * @method Phaser.Math#bezierInterpolation
+    * @param {Array} v - The input array of values to interpolate between.
+    * @param {number} k - The percentage of interpolation, between 0 and 1.
+    * @return {number} The interpolated value
+    */
+    bezierInterpolation: function (v, k) {
+
+        var b = 0;
+        var n = v.length - 1;
+
+        for (var i = 0; i <= n; i++)
+        {
+            b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
+        }
+
+        return b;
+
+    },
+
+    /**
+    * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween.
+    *
+    * @method Phaser.Math#catmullRomInterpolation
+    * @param {Array} v - The input array of values to interpolate between.
+    * @param {number} k - The percentage of interpolation, between 0 and 1.
+    * @return {number} The interpolated value
+    */
+    catmullRomInterpolation: function (v, k) {
+
+        var m = v.length - 1;
+        var f = m * k;
+        var i = Math.floor(f);
+
+        if (v[0] === v[m])
+        {
+            if (k < 0)
+            {
+                i = Math.floor(f = m * (1 + k));
+            }
+
+            return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
+        }
+        else
+        {
+            if (k < 0)
+            {
+                return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
+            }
+
+            if (k > 1)
+            {
+                return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
+            }
+
+            return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
+        }
+
+    },
+
+    /**
+    * Calculates a linear (interpolation) value over t.
+    *
+    * @method Phaser.Math#linear
+    * @param {number} p0
+    * @param {number} p1
+    * @param {number} t
+    * @return {number}
+    */
+    linear: function (p0, p1, t) {
+        return (p1 - p0) * t + p0;
+    },
+
+    /**
+    * @method Phaser.Math#bernstein
+    * @protected
+    * @param {number} n
+    * @param {number} i
+    * @return {number}
+    */
+    bernstein: function (n, i) {
+        return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
+    },
+
+    /**
+    * @method Phaser.Math#factorial
+    * @param {number} value - the number you want to evaluate
+    * @return {number}
+    */
+    factorial : function( value ){
+
+        if (value === 0)
+        {
+            return 1;
+        }
+
+        var res = value;
+
+        while(--value)
+        {
+            res *= value;
+        }
+
+        return res;
+
+    },
+
+    /**
+    * Calculates a catmum rom value.
+    *
+    * @method Phaser.Math#catmullRom
+    * @protected
+    * @param {number} p0
+    * @param {number} p1
+    * @param {number} p2
+    * @param {number} p3
+    * @param {number} t
+    * @return {number}
+    */
+    catmullRom: function (p0, p1, p2, p3, t) {
+
+        var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
+
+        return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
+
+    },
+
+    /**
+    * The (absolute) difference between two values.
+    *
+    * @method Phaser.Math#difference
+    * @param {number} a
+    * @param {number} b
+    * @return {number}
+    */
+    difference: function (a, b) {
+        return Math.abs(a - b);
+    },
+
+    /**
+    * Round to the next whole number _away_ from zero.
+    *
+    * @method Phaser.Math#roundAwayFromZero
+    * @param {number} value - Any number.
+    * @return {integer} The rounded value of that number.
+    */
+    roundAwayFromZero: function (value) {
+
+        // "Opposite" of truncate.
+        return (value > 0) ? Math.ceil(value) : Math.floor(value);
+
+    },
+
+    /**
+    * Generate a sine and cosine table simultaneously and extremely quickly.
+    * The parameters allow you to specify the length, amplitude and frequency of the wave.
+    * This generator is fast enough to be used in real-time.
+    * Code based on research by Franky of scene.at
+    *
+    * @method Phaser.Math#sinCosGenerator
+    * @param {number} length - The length of the wave
+    * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
+    * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
+    * @param {number} frequency  - The frequency of the sine and cosine table data
+    * @return {{sin:number[], cos:number[]}} Returns the table data.
+    */
+    sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) {
+
+        if (sinAmplitude === undefined) { sinAmplitude = 1.0; }
+        if (cosAmplitude === undefined) { cosAmplitude = 1.0; }
+        if (frequency === undefined) { frequency = 1.0; }
+
+        var sin = sinAmplitude;
+        var cos = cosAmplitude;
+        var frq = frequency * Math.PI / length;
+
+        var cosTable = [];
+        var sinTable = [];
+
+        for (var c = 0; c < length; c++) {
+
+            cos -= sin * frq;
+            sin += cos * frq;
+
+            cosTable[c] = cos;
+            sinTable[c] = sin;
+
+        }
+
+        return { sin: sinTable, cos: cosTable, length: length };
+
+    },
+
+    /**
+    * Returns the euclidian distance between the two given set of coordinates.
+    *
+    * @method Phaser.Math#distance
+    * @param {number} x1
+    * @param {number} y1
+    * @param {number} x2
+    * @param {number} y2
+    * @return {number} The distance between the two sets of coordinates.
+    */
+    distance: function (x1, y1, x2, y2) {
+
+        var dx = x1 - x2;
+        var dy = y1 - y2;
+
+        return Math.sqrt(dx * dx + dy * dy);
+
+    },
+
+    /**
+    * Returns the euclidean distance squared between the two given set of
+    * coordinates (cuts out a square root operation before returning).
+    *
+    * @method Phaser.Math#distanceSq
+    * @param {number} x1
+    * @param {number} y1
+    * @param {number} x2
+    * @param {number} y2
+    * @return {number} The distance squared between the two sets of coordinates.
+    */
+    distanceSq: function (x1, y1, x2, y2) {
+
+        var dx = x1 - x2;
+        var dy = y1 - y2;
+
+        return dx * dx + dy * dy;
+
+    },
+
+    /**
+    * Returns the distance between the two given set of coordinates at the power given.
+    *
+    * @method Phaser.Math#distancePow
+    * @param {number} x1
+    * @param {number} y1
+    * @param {number} x2
+    * @param {number} y2
+    * @param {number} [pow=2]
+    * @return {number} The distance between the two sets of coordinates.
+    */
+    distancePow: function (x1, y1, x2, y2, pow) {
+
+        if (pow === undefined) { pow = 2; }
+
+        return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow));
+
+    },
+
+    /**
+    * Force a value within the boundaries by clamping `x` to the range `[a, b]`.
+    *
+    * @method Phaser.Math#clamp
+    * @param {number} x
+    * @param {number} a
+    * @param {number} b
+    * @return {number}
+    */
+    clamp: function (x, a, b) {
+        return ( x < a ) ? a : ( ( x > b ) ? b : x );
+    },
+
+    /**
+    * Clamp `x` to the range `[a, Infinity)`.
+    * Roughly the same as `Math.max(x, a)`, except for NaN handling.
+    *
+    * @method Phaser.Math#clampBottom
+    * @param {number} x
+    * @param {number} a
+    * @return {number}
+    */
+    clampBottom: function (x, a) {
+        return x < a ? a : x;
+    },
+
+    /**
+    * Checks if two values are within the given tolerance of each other.
+    *
+    * @method Phaser.Math#within
+    * @param {number} a - The first number to check
+    * @param {number} b - The second number to check
+    * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range.
+    * @return {boolean} True if a is <= tolerance of b.
+    * @see {@link Phaser.Math.fuzzyEqual}
+    */
+    within: function (a, b, tolerance) {
+        return (Math.abs(a - b) <= tolerance);
+    },
+
+    /**
+    * Linear mapping from range <a1, a2> to range <b1, b2>
+    *
+    * @method Phaser.Math#mapLinear
+    * @param {number} x the value to map
+    * @param {number} a1 first endpoint of the range <a1, a2>
+    * @param {number} a2 final endpoint of the range <a1, a2>
+    * @param {number} b1 first endpoint of the range <b1, b2>
+    * @param {number} b2 final endpoint of the range  <b1, b2>
+    * @return {number}
+    */
+    mapLinear: function (x, a1, a2, b1, b2) {
+        return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
+    },
+
+    /**
+    * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
+    *
+    * @method Phaser.Math#smoothstep
+    * @param {number} x
+    * @param {number} min
+    * @param {number} max
+    * @return {number}
+    */
+    smoothstep: function (x, min, max) {
+        x = Math.max(0, Math.min(1, (x - min) / (max - min)));
+        return x * x * (3 - 2 * x);
+    },
+
+    /**
+    * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
+    *
+    * @method Phaser.Math#smootherstep
+    * @param {number} x
+    * @param {number} min
+    * @param {number} max
+    * @return {number}
+    */
+    smootherstep: function (x, min, max) {
+        x = Math.max(0, Math.min(1, (x - min) / (max - min)));
+        return x * x * x * (x * (x * 6 - 15) + 10);
+    },
+
+    /**
+    * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0.
+    *
+    * This works differently from `Math.sign` for values of NaN and -0, etc.
+    *
+    * @method Phaser.Math#sign
+    * @param {number} x
+    * @return {integer} An integer in {-1, 0, 1}
+    */
+    sign: function (x) {
+        return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
+    },
+
+    /**
+    * Work out what percentage value `a` is of value `b` using the given base.
+    *
+    * @method Phaser.Math#percent
+    * @param {number} a - The value to work out the percentage for.
+    * @param {number} b - The value you wish to get the percentage of.
+    * @param {number} [base=0] - The base value.
+    * @return {number} The percentage a is of b, between 0 and 1.
+    */
+    percent: function (a, b, base) {
+
+        if (base === undefined) { base = 0; }
+
+        if (a > b || base > b)
+        {
+            return 1;
+        }
+        else if (a < base || base > a)
+        {
+            return 0;
+        }
+        else
+        {
+            return (a - base) / b;
+        }
+
+    }
+
+};
+
+var degreeToRadiansFactor = Math.PI / 180;
+var radianToDegreesFactor = 180 / Math.PI;
+
+/**
+* Convert degrees to radians.
+*
+* @method Phaser.Math#degToRad
+* @param {number} degrees - Angle in degrees.
+* @return {number} Angle in radians.
+*/
+Phaser.Math.degToRad = function degToRad (degrees) {
+    return degrees * degreeToRadiansFactor;
+};
+
+/**
+* Convert degrees to radians.
+*
+* @method Phaser.Math#radToDeg
+* @param {number} radians - Angle in radians.
+* @return {number} Angle in degrees
+*/
+Phaser.Math.radToDeg = function radToDeg (radians) {
+    return radians * radianToDegreesFactor;
+};
+
+/* jshint noempty: false */
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* An extremely useful repeatable random data generator.
+*
+* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
+*
+* The random number genererator is based on the Alea PRNG, but is modified.
+*  - https://github.com/coverslide/node-alea
+*  - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
+*  - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404)
+*
+* @class Phaser.RandomDataGenerator
+* @constructor
+* @param {any[]} [seeds] - An array of values to use as the seed.
+*/
+Phaser.RandomDataGenerator = function (seeds) {
+
+    if (seeds === undefined) { seeds = []; }
+
+    /**
+    * @property {number} c - Internal var.
+    * @private
+    */
+    this.c = 1;
+
+    /**
+    * @property {number} s0 - Internal var.
+    * @private
+    */
+    this.s0 = 0;
+
+    /**
+    * @property {number} s1 - Internal var.
+    * @private
+    */
+    this.s1 = 0;
+
+    /**
+    * @property {number} s2 - Internal var.
+    * @private
+    */
+    this.s2 = 0;
+
+    this.sow(seeds);
+
+};
+
+Phaser.RandomDataGenerator.prototype = {
+
+    /**
+    * Private random helper.
+    *
+    * @method Phaser.RandomDataGenerator#rnd
+    * @private
+    * @return {number}
+    */
+    rnd: function () {
+
+        var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
+
+        this.c = t | 0;
+        this.s0 = this.s1;
+        this.s1 = this.s2;
+        this.s2 = t - this.c;
+
+        return this.s2;
+    },
+
+    /**
+    * Reset the seed of the random data generator.
+    *
+    * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present.
+    *
+    * @method Phaser.RandomDataGenerator#sow
+    * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used.
+    */
+    sow: function (seeds) {
+
+        // Always reset to default seed
+        this.s0 = this.hash(' ');
+        this.s1 = this.hash(this.s0);
+        this.s2 = this.hash(this.s1);
+        this.c = 1;
+
+        if (!seeds)
+        {
+            return;
+        }
+
+        // Apply any seeds
+        for (var i = 0; i < seeds.length && (seeds[i] != null); i++)
+        {
+            var seed = seeds[i];
+
+            this.s0 -= this.hash(seed);
+            this.s0 += ~~(this.s0 < 0);
+            this.s1 -= this.hash(seed);
+            this.s1 += ~~(this.s1 < 0);
+            this.s2 -= this.hash(seed);
+            this.s2 += ~~(this.s2 < 0);
+        }
+
+    },
+
+    /**
+    * Internal method that creates a seed hash.
+    *
+    * @method Phaser.RandomDataGenerator#hash
+    * @private
+    * @param {any} data
+    * @return {number} hashed value.
+    */
+    hash: function (data) {
+
+        var h, i, n;
+        n = 0xefc8249d;
+        data = data.toString();
+
+        for (i = 0; i < data.length; i++) {
+            n += data.charCodeAt(i);
+            h = 0.02519603282416938 * n;
+            n = h >>> 0;
+            h -= n;
+            h *= n;
+            n = h >>> 0;
+            h -= n;
+            n += h * 0x100000000;// 2^32
+        }
+
+        return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
+
+    },
+
+    /**
+    * Returns a random integer between 0 and 2^32.
+    *
+    * @method Phaser.RandomDataGenerator#integer
+    * @return {number} A random integer between 0 and 2^32.
+    */
+    integer: function() {
+
+        return this.rnd.apply(this) * 0x100000000;// 2^32
+
+    },
+
+    /**
+    * Returns a random real number between 0 and 1.
+    *
+    * @method Phaser.RandomDataGenerator#frac
+    * @return {number} A random real number between 0 and 1.
+    */
+    frac: function() {
+
+        return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;   // 2^-53
+
+    },
+
+    /**
+    * Returns a random real number between 0 and 2^32.
+    *
+    * @method Phaser.RandomDataGenerator#real
+    * @return {number} A random real number between 0 and 2^32.
+    */
+    real: function() {
+
+        return this.integer() + this.frac();
+
+    },
+
+    /**
+    * Returns a random integer between and including min and max.
+    *
+    * @method Phaser.RandomDataGenerator#integerInRange
+    * @param {number} min - The minimum value in the range.
+    * @param {number} max - The maximum value in the range.
+    * @return {number} A random number between min and max.
+    */
+    integerInRange: function (min, max) {
+
+        return Math.floor(this.realInRange(0, max - min + 1) + min);
+
+    },
+
+    /**
+    * Returns a random integer between and including min and max.
+    * This method is an alias for RandomDataGenerator.integerInRange.
+    *
+    * @method Phaser.RandomDataGenerator#between
+    * @param {number} min - The minimum value in the range.
+    * @param {number} max - The maximum value in the range.
+    * @return {number} A random number between min and max.
+    */
+    between: function (min, max) {
+
+        return this.integerInRange(min, max);
+
+    },
+
+    /**
+    * Returns a random real number between min and max.
+    *
+    * @method Phaser.RandomDataGenerator#realInRange
+    * @param {number} min - The minimum value in the range.
+    * @param {number} max - The maximum value in the range.
+    * @return {number} A random number between min and max.
+    */
+    realInRange: function (min, max) {
+
+        return this.frac() * (max - min) + min;
+
+    },
+
+    /**
+    * Returns a random real number between -1 and 1.
+    *
+    * @method Phaser.RandomDataGenerator#normal
+    * @return {number} A random real number between -1 and 1.
+    */
+    normal: function () {
+
+        return 1 - 2 * this.frac();
+
+    },
+
+    /**
+    * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
+    *
+    * @method Phaser.RandomDataGenerator#uuid
+    * @return {string} A valid RFC4122 version4 ID hex string
+    */
+    uuid: function () {
+
+        var a = '';
+        var b = '';
+
+        for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
+        {
+        }
+
+        return b;
+
+    },
+
+    /**
+    * Returns a random member of `array`.
+    *
+    * @method Phaser.RandomDataGenerator#pick
+    * @param {Array} ary - An Array to pick a random member of.
+    * @return {any} A random member of the array.
+    */
+    pick: function (ary) {
+
+        return ary[this.integerInRange(0, ary.length - 1)];
+
+    },
+
+    /**
+    * Returns a random member of `array`, favoring the earlier entries.
+    *
+    * @method Phaser.RandomDataGenerator#weightedPick
+    * @param {Array} ary - An Array to pick a random member of.
+    * @return {any} A random member of the array.
+    */
+    weightedPick: function (ary) {
+
+        return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)];
+
+    },
+
+    /**
+    * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
+    *
+    * @method Phaser.RandomDataGenerator#timestamp
+    * @param {number} min - The minimum value in the range.
+    * @param {number} max - The maximum value in the range.
+    * @return {number} A random timestamp between min and max.
+    */
+    timestamp: function (min, max) {
+
+        return this.realInRange(min || 946684800000, max || 1577862000000);
+
+    },
+
+    /**
+    * Returns a random angle between -180 and 180.
+    *
+    * @method Phaser.RandomDataGenerator#angle
+    * @return {number} A random number between -180 and 180.
+    */
+    angle: function() {
+
+        return this.integerInRange(-180, 180);
+
+    }
+
+};
+
+Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator;
+
+/**
+ * @author       Timo Hausmann
+ * @author       Richard Davey <rich@photonstorm.com>
+ * @copyright    2015 Photon Storm Ltd.
+ * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+ */
+
+/**
+* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts.
+* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result.
+* Original version at https://github.com/timohausmann/quadtree-js/
+*
+* @class Phaser.QuadTree
+* @constructor
+* @param {number} x - The top left coordinate of the quadtree.
+* @param {number} y - The top left coordinate of the quadtree.
+* @param {number} width - The width of the quadtree in pixels.
+* @param {number} height - The height of the quadtree in pixels.
+* @param {number} [maxObjects=10] - The maximum number of objects per node.
+* @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
+* @param {number} [level=0] - Which level is this?
+*/
+Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) {
+
+    /**
+    * @property {number} maxObjects - The maximum number of objects per node.
+    * @default
+    */
+    this.maxObjects = 10;
+
+    /**
+    * @property {number} maxLevels - The maximum number of levels to break down to.
+    * @default
+    */
+    this.maxLevels = 4;
+
+    /**
+    * @property {number} level - The current level.
+    */
+    this.level = 0;
+
+    /**
+    * @property {object} bounds - Object that contains the quadtree bounds.
+    */
+    this.bounds = {};
+
+    /**
+    * @property {array} objects - Array of quadtree children.
+    */
+    this.objects = [];
+
+    /**
+    * @property {array} nodes - Array of associated child nodes.
+    */
+    this.nodes = [];
+
+    /**
+    * @property {array} _empty - Internal empty array.
+    * @private
+    */
+    this._empty = [];
+
+    this.reset(x, y, width, height, maxObjects, maxLevels, level);
+
+};
+
+Phaser.QuadTree.prototype = {
+
+    /**
+    * Resets the QuadTree.
+    *
+    * @method Phaser.QuadTree#reset
+    * @param {number} x - The top left coordinate of the quadtree.
+    * @param {number} y - The top left coordinate of the quadtree.
+    * @param {number} width - The width of the quadtree in pixels.
+    * @param {number} height - The height of the quadtree in pixels.
+    * @param {number} [maxObjects=10] - The maximum number of objects per node.
+    * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
+    * @param {number} [level=0] - Which level is this?
+    */
+    reset: function (x, y, width, height, maxObjects, maxLevels, level) {
+
+        this.maxObjects = maxObjects || 10;
+        this.maxLevels = maxLevels || 4;
+        this.level = level || 0;
+
+        this.bounds = {
+            x: Math.round(x),
+            y: Math.round(y),
+            width: width,
+            height: height,
+            subWidth: Math.floor(width / 2),
+            subHeight: Math.floor(height / 2),
+            right: Math.round(x) + Math.floor(width / 2),
+            bottom: Math.round(y) + Math.floor(height / 2)
+        };
+
+        this.objects.length = 0;
+        this.nodes.length = 0;
+
+    },
+
+    /**
+    * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property.
+    *
+    * @method Phaser.QuadTree#populate
+    * @param {Phaser.Group} group - The Group to add to the quadtree.
+    */
+    populate: function (group) {
+
+        group.forEach(this.populateHandler, this, true);
+
+    },
+
+    /**
+    * Handler for the populate method.
+    *
+    * @method Phaser.QuadTree#populateHandler
+    * @param {Phaser.Sprite|object} sprite - The Sprite to check.
+    */
+    populateHandler: function (sprite) {
+
+        if (sprite.body && sprite.exists)
+        {
+            this.insert(sprite.body);
+        }
+
+    },
+
+    /**
+    * Split the node into 4 subnodes
+    *
+    * @method Phaser.QuadTree#split
+    */
+    split: function () {
+
+        //  top right node
+        this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
+
+        //  top left node
+        this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
+
+        //  bottom left node
+        this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
+
+        //  bottom right node
+        this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
+
+    },
+
+    /**
+    * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes.
+    *
+    * @method Phaser.QuadTree#insert
+    * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties.
+    */
+    insert: function (body) {
+
+        var i = 0;
+        var index;
+
+        //  if we have subnodes ...
+        if (this.nodes[0] != null)
+        {
+            index = this.getIndex(body);
+
+            if (index !== -1)
+            {
+                this.nodes[index].insert(body);
+                return;
+            }
+        }
+
+        this.objects.push(body);
+
+        if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
+        {
+            //  Split if we don't already have subnodes
+            if (this.nodes[0] == null)
+            {
+                this.split();
+            }
+
+            //  Add objects to subnodes
+            while (i < this.objects.length)
+            {
+                index = this.getIndex(this.objects[i]);
+
+                if (index !== -1)
+                {
+                    //  this is expensive - see what we can do about it
+                    this.nodes[index].insert(this.objects.splice(i, 1)[0]);
+                }
+                else
+                {
+                    i++;
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Determine which node the object belongs to.
+    *
+    * @method Phaser.QuadTree#getIndex
+    * @param {Phaser.Rectangle|object} rect - The bounds in which to check.
+    * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node.
+    */
+    getIndex: function (rect) {
+
+        //  default is that rect doesn't fit, i.e. it straddles the internal quadrants
+        var index = -1;
+
+        if (rect.x < this.bounds.right && rect.right < this.bounds.right)
+        {
+            if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
+            {
+                //  rect fits within the top-left quadrant of this quadtree
+                index = 1;
+            }
+            else if (rect.y > this.bounds.bottom)
+            {
+                //  rect fits within the bottom-left quadrant of this quadtree
+                index = 2;
+            }
+        }
+        else if (rect.x > this.bounds.right)
+        {
+            //  rect can completely fit within the right quadrants
+            if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
+            {
+                //  rect fits within the top-right quadrant of this quadtree
+                index = 0;
+            }
+            else if (rect.y > this.bounds.bottom)
+            {
+                //  rect fits within the bottom-right quadrant of this quadtree
+                index = 3;
+            }
+        }
+
+        return index;
+
+    },
+
+    /**
+    * Return all objects that could collide with the given Sprite or Rectangle.
+    *
+    * @method Phaser.QuadTree#retrieve
+    * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle.
+    * @return {array} - Array with all detected objects.
+    */
+    retrieve: function (source) {
+
+        if (source instanceof Phaser.Rectangle)
+        {
+            var returnObjects = this.objects;
+
+            var index = this.getIndex(source);
+        }
+        else
+        {
+            if (!source.body)
+            {
+                return this._empty;
+            }
+
+            var returnObjects = this.objects;
+
+            var index = this.getIndex(source.body);
+        }
+
+        if (this.nodes[0])
+        {
+            //  If rect fits into a subnode ..
+            if (index !== -1)
+            {
+                returnObjects = returnObjects.concat(this.nodes[index].retrieve(source));
+            }
+            else
+            {
+                //  If rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
+                returnObjects = returnObjects.concat(this.nodes[0].retrieve(source));
+                returnObjects = returnObjects.concat(this.nodes[1].retrieve(source));
+                returnObjects = returnObjects.concat(this.nodes[2].retrieve(source));
+                returnObjects = returnObjects.concat(this.nodes[3].retrieve(source));
+            }
+        }
+
+        return returnObjects;
+
+    },
+
+    /**
+    * Clear the quadtree.
+    * @method Phaser.QuadTree#clear
+    */
+    clear: function () {
+
+        this.objects.length = 0;
+
+        var i = this.nodes.length;
+
+        while (i--)
+        {
+            this.nodes[i].clear();
+            this.nodes.splice(i, 1);
+        }
+
+        this.nodes.length = 0;
+    }
+
+};
+
+Phaser.QuadTree.prototype.constructor = Phaser.QuadTree;
+
+/**
+* Javascript QuadTree
+* @version 1.0
+*
+* @version 1.3, March 11th 2014
+* @author Richard Davey
+* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
+* it massively to add node indexing, removed lots of temp. var creation and significantly
+* increased performance as a result.
+*
+* Original version at https://github.com/timohausmann/quadtree-js/
+*/
+
+/**
+* @copyright © 2012 Timo Hausmann
+*
+* Permission is hereby granted, free of charge, to any person obtaining
+* a copy of this software and associated documentation files (the
+* "Software"), to deal in the Software without restriction, including
+* without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to
+* permit persons to whom the Software is furnished to do so, subject to
+* the following conditions:
+*
+* The above copyright notice and this permission notice shall be
+* included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
+*
+* @class Phaser.Net
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Net = function (game) {
+
+    this.game = game;
+
+};
+
+Phaser.Net.prototype = {
+
+    /**
+    * Returns the hostname given by the browser.
+    *
+    * @method Phaser.Net#getHostName
+    * @return {string}
+    */
+    getHostName: function () {
+
+        if (window.location && window.location.hostname) {
+            return window.location.hostname;
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Compares the given domain name against the hostname of the browser containing the game.
+    * If the domain name is found it returns true.
+    * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
+    * Do not include 'http://' at the start.
+    *
+    * @method Phaser.Net#checkDomainName
+    * @param {string} domain
+    * @return {boolean} true if the given domain fragment can be found in the window.location.hostname
+    */
+    checkDomainName: function (domain) {
+        return window.location.hostname.indexOf(domain) !== -1;
+    },
+
+    /**
+    * Updates a value on the Query String and returns it in full.
+    * If the value doesn't already exist it is set.
+    * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string.
+    * Optionally you can redirect to the new url, or just return it as a string.
+    *
+    * @method Phaser.Net#updateQueryString
+    * @param {string} key - The querystring key to update.
+    * @param {string} value - The new value to be set. If it already exists it will be replaced.
+    * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
+    * @param {string} url - The URL to modify. If none is given it uses window.location.href.
+    * @return {string} If redirect is false then the modified url and query string is returned.
+    */
+    updateQueryString: function (key, value, redirect, url) {
+
+        if (redirect === undefined) { redirect = false; }
+        if (url === undefined || url === '') { url = window.location.href; }
+
+        var output = '';
+        var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
+
+        if (re.test(url))
+        {
+            if (typeof value !== 'undefined' && value !== null)
+            {
+                output = url.replace(re, '$1' + key + "=" + value + '$2$3');
+            }
+            else
+            {
+                output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
+            }
+        }
+        else
+        {
+            if (typeof value !== 'undefined' && value !== null)
+            {
+                var separator = url.indexOf('?') !== -1 ? '&' : '?';
+                var hash = url.split('#');
+                url = hash[0] + separator + key + '=' + value;
+
+                if (hash[1]) {
+                    url += '#' + hash[1];
+                }
+
+                output = url;
+
+            }
+            else
+            {
+                output = url;
+            }
+        }
+
+        if (redirect)
+        {
+            window.location.href = output;
+        }
+        else
+        {
+            return output;
+        }
+
+    },
+
+    /**
+    * Returns the Query String as an object.
+    * If you specify a parameter it will return just the value of that parameter, should it exist.
+    *
+    * @method Phaser.Net#getQueryString
+    * @param {string} [parameter=''] - If specified this will return just the value for that key.
+    * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
+    */
+    getQueryString: function (parameter) {
+
+        if (parameter === undefined) { parameter = ''; }
+
+        var output = {};
+        var keyValues = location.search.substring(1).split('&');
+
+        for (var i in keyValues)
+        {
+            var key = keyValues[i].split('=');
+
+            if (key.length > 1)
+            {
+                if (parameter && parameter == this.decodeURI(key[0]))
+                {
+                    return this.decodeURI(key[1]);
+                }
+                else
+                {
+                    output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
+                }
+            }
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Returns the Query String as an object.
+    * If you specify a parameter it will return just the value of that parameter, should it exist.
+    *
+    * @method Phaser.Net#decodeURI
+    * @param {string} value - The URI component to be decoded.
+    * @return {string} The decoded value.
+    */
+    decodeURI: function (value) {
+        return decodeURIComponent(value.replace(/\+/g, " "));
+    }
+
+};
+
+Phaser.Net.prototype.constructor = Phaser.Net;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated.
+* Tweens are hooked into the game clock and pause system, adjusting based on the game state.
+*
+* TweenManager is based heavily on tween.js by http://soledadpenades.com.
+* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object.
+* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors.
+* Please see https://github.com/sole/tween.js for a full list of contributors.
+* 
+* @class Phaser.TweenManager
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.TweenManager = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {array<Phaser.Tween>} _tweens - All of the currently running tweens.
+    * @private
+    */
+    this._tweens = [];
+
+    /**
+    * @property {array<Phaser.Tween>} _add - All of the tweens queued to be added in the next update.
+    * @private
+    */
+    this._add = [];
+
+    this.easeMap = {
+
+        "Power0": Phaser.Easing.Power0,
+        "Power1": Phaser.Easing.Power1,
+        "Power2": Phaser.Easing.Power2,
+        "Power3": Phaser.Easing.Power3,
+        "Power4": Phaser.Easing.Power4,
+
+        "Linear": Phaser.Easing.Linear.None,
+        "Quad": Phaser.Easing.Quadratic.Out,
+        "Cubic": Phaser.Easing.Cubic.Out,
+        "Quart": Phaser.Easing.Quartic.Out,
+        "Quint": Phaser.Easing.Quintic.Out,
+        "Sine": Phaser.Easing.Sinusoidal.Out,
+        "Expo": Phaser.Easing.Exponential.Out,
+        "Circ": Phaser.Easing.Circular.Out,
+        "Elastic": Phaser.Easing.Elastic.Out,
+        "Back": Phaser.Easing.Back.Out,
+        "Bounce": Phaser.Easing.Bounce.Out,
+
+        "Quad.easeIn": Phaser.Easing.Quadratic.In,
+        "Cubic.easeIn": Phaser.Easing.Cubic.In,
+        "Quart.easeIn": Phaser.Easing.Quartic.In,
+        "Quint.easeIn": Phaser.Easing.Quintic.In,
+        "Sine.easeIn": Phaser.Easing.Sinusoidal.In,
+        "Expo.easeIn": Phaser.Easing.Exponential.In,
+        "Circ.easeIn": Phaser.Easing.Circular.In,
+        "Elastic.easeIn": Phaser.Easing.Elastic.In,
+        "Back.easeIn": Phaser.Easing.Back.In,
+        "Bounce.easeIn": Phaser.Easing.Bounce.In,
+
+        "Quad.easeOut": Phaser.Easing.Quadratic.Out,
+        "Cubic.easeOut": Phaser.Easing.Cubic.Out,
+        "Quart.easeOut": Phaser.Easing.Quartic.Out,
+        "Quint.easeOut": Phaser.Easing.Quintic.Out,
+        "Sine.easeOut": Phaser.Easing.Sinusoidal.Out,
+        "Expo.easeOut": Phaser.Easing.Exponential.Out,
+        "Circ.easeOut": Phaser.Easing.Circular.Out,
+        "Elastic.easeOut": Phaser.Easing.Elastic.Out,
+        "Back.easeOut": Phaser.Easing.Back.Out,
+        "Bounce.easeOut": Phaser.Easing.Bounce.Out,
+
+        "Quad.easeInOut": Phaser.Easing.Quadratic.InOut,
+        "Cubic.easeInOut": Phaser.Easing.Cubic.InOut,
+        "Quart.easeInOut": Phaser.Easing.Quartic.InOut,
+        "Quint.easeInOut": Phaser.Easing.Quintic.InOut,
+        "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut,
+        "Expo.easeInOut": Phaser.Easing.Exponential.InOut,
+        "Circ.easeInOut": Phaser.Easing.Circular.InOut,
+        "Elastic.easeInOut": Phaser.Easing.Elastic.InOut,
+        "Back.easeInOut": Phaser.Easing.Back.InOut,
+        "Bounce.easeInOut": Phaser.Easing.Bounce.InOut
+
+    };
+
+    this.game.onPause.add(this._pauseAll, this);
+    this.game.onResume.add(this._resumeAll, this);
+
+};
+
+Phaser.TweenManager.prototype = {
+
+    /**
+    * Get all the tween objects in an array.
+    * @method Phaser.TweenManager#getAll
+    * @returns {Phaser.Tween[]} Array with all tween objects.
+    */
+    getAll: function () {
+
+        return this._tweens;
+
+    },
+
+    /**
+    * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events.
+    * @method Phaser.TweenManager#removeAll
+    */
+    removeAll: function () {
+
+        for (var i = 0; i < this._tweens.length; i++)
+        {
+            this._tweens[i].pendingDelete = true;
+        }
+
+        this._add = [];
+
+    },
+    
+    /**
+    * Remove all tweens from a specific object, array of objects or Group.
+    * 
+    * @method Phaser.TweenManager#removeFrom
+    * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from.
+    * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself.
+    */
+    removeFrom: function (obj, children) {
+        
+        if (children === undefined) { children = true; }
+
+        var i;
+        var len;
+
+        if (Array.isArray(obj))
+        {
+            for (i = 0, len = obj.length; i < len; i++)
+            {
+                this.removeFrom(obj[i]);
+            }
+        }
+        else if (obj.type === Phaser.GROUP && children)
+        {
+            for (var i = 0, len = obj.children.length; i < len; i++)
+            {
+                this.removeFrom(obj.children[i]);
+            }
+        }
+        else
+        {
+            for (i = 0, len = this._tweens.length; i < len; i++)
+            {
+                if (obj === this._tweens[i].target)
+                {
+                    this.remove(this._tweens[i]);
+                }
+            }
+
+            for (i = 0, len = this._add.length; i < len; i++)
+            {
+                if (obj === this._add[i].target)
+                {
+                    this.remove(this._add[i]);
+                }
+            }
+        }
+        
+    },
+
+    /**
+    * Add a new tween into the TweenManager.
+    *
+    * @method Phaser.TweenManager#add
+    * @param {Phaser.Tween} tween - The tween object you want to add.
+    * @returns {Phaser.Tween} The tween object you added to the manager.
+    */
+    add: function (tween) {
+
+        tween._manager = this;
+        this._add.push(tween);
+
+    },
+
+    /**
+    * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
+    *
+    * @method Phaser.TweenManager#create
+    * @param {object} object - Object the tween will be run on.
+    * @returns {Phaser.Tween} The newly created tween object.
+    */
+    create: function (object) {
+
+        return new Phaser.Tween(object, this.game, this);
+
+    },
+
+    /**
+    * Remove a tween from this manager.
+    *
+    * @method Phaser.TweenManager#remove
+    * @param {Phaser.Tween} tween - The tween object you want to remove.
+    */
+    remove: function (tween) {
+
+        var i = this._tweens.indexOf(tween);
+
+        if (i !== -1)
+        {
+            this._tweens[i].pendingDelete = true;
+        }
+        else
+        {
+            i = this._add.indexOf(tween);
+
+            if (i !== -1)
+            {
+                this._add[i].pendingDelete = true;
+            }
+        }
+
+    },
+
+    /**
+    * Update all the tween objects you added to this manager.
+    *
+    * @method Phaser.TweenManager#update
+    * @returns {boolean} Return false if there's no tween to update, otherwise return true.
+    */
+    update: function () {
+
+        var addTweens = this._add.length;
+        var numTweens = this._tweens.length;
+
+        if (numTweens === 0 && addTweens === 0)
+        {
+            return false;
+        }
+
+        var i = 0;
+
+        while (i < numTweens)
+        {
+            if (this._tweens[i].update(this.game.time.time))
+            {
+                i++;
+            }
+            else
+            {
+                this._tweens.splice(i, 1);
+
+                numTweens--;
+            }
+        }
+
+        //  If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running
+        if (addTweens > 0)
+        {
+            this._tweens = this._tweens.concat(this._add);
+            this._add.length = 0;
+        }
+
+        return true;
+
+    },
+
+    /**
+    * Checks to see if a particular Sprite is currently being tweened.
+    *
+    * @method Phaser.TweenManager#isTweening
+    * @param {object} object - The object to check for tweens against.
+    * @returns {boolean} Returns true if the object is currently being tweened, false if not.
+    */
+    isTweening: function(object) {
+
+        return this._tweens.some(function(tween) {
+            return tween.target === object;
+        });
+
+    },
+
+    /**
+    * Private. Called by game focus loss. Pauses all currently running tweens.
+    *
+    * @method Phaser.TweenManager#_pauseAll
+    * @private
+    */
+    _pauseAll: function () {
+
+        for (var i = this._tweens.length - 1; i >= 0; i--)
+        {
+            this._tweens[i]._pause();
+        }
+
+    },
+
+    /**
+    * Private. Called by game focus loss. Resumes all currently paused tweens.
+    *
+    * @method Phaser.TweenManager#_resumeAll
+    * @private
+    */
+    _resumeAll: function () {
+
+        for (var i = this._tweens.length - 1; i >= 0; i--)
+        {
+            this._tweens[i]._resume();
+        }
+
+    },
+
+    /**
+    * Pauses all currently running tweens.
+    *
+    * @method Phaser.TweenManager#pauseAll
+    */
+    pauseAll: function () {
+
+        for (var i = this._tweens.length - 1; i >= 0; i--)
+        {
+            this._tweens[i].pause();
+        }
+
+    },
+
+    /**
+    * Resumes all currently paused tweens.
+    *
+    * @method Phaser.TweenManager#resumeAll
+    */
+    resumeAll: function () {
+
+        for (var i = this._tweens.length - 1; i >= 0; i--)
+        {
+            this._tweens[i].resume(true);
+        }
+
+    }
+
+};
+
+Phaser.TweenManager.prototype.constructor = Phaser.TweenManager;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Tween allows you to alter one or more properties of a target object over a defined period of time.
+* This can be used for things such as alpha fading Sprites, scaling them or motion.
+* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object
+* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and
+* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children.
+*
+* @class Phaser.Tween
+* @constructor
+* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale.
+* @param {Phaser.Game} game - Current game instance.
+* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween.
+*/
+Phaser.Tween = function (target, game, manager) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale.
+    */
+    this.target = target;
+
+    /**
+    * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween.
+    */
+    this.manager = manager;
+
+    /**
+    * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween.
+    */
+    this.timeline = [];
+
+    /**
+    * If set to `true` the current tween will play in reverse.
+    * If the tween hasn't yet started this has no effect.
+    * If there are child tweens then all child tweens will play in reverse from the current point.
+    * @property {boolean} reverse
+    * @default
+    */
+    this.reverse = false;
+
+    /**
+    * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc.
+    * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete.
+    *
+    * @property {number} timeScale
+    * @default
+    */
+    this.timeScale = 1;
+
+    /**
+    * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count.
+    */
+    this.repeatCounter = 0;
+
+    /**
+    * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager.
+    * @default
+    * @readonly
+    */
+    this.pendingDelete = false;
+
+    /**
+    * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished.
+    * It will be sent 2 parameters: the target object and this tween.
+    * @property {Phaser.Signal} onStart
+    */
+    this.onStart = new Phaser.Signal();
+
+    /**
+    * The onLoop event is fired if the Tween or any child tween loops.
+    * It will be sent 2 parameters: the target object and this tween.
+    * @property {Phaser.Signal} onLoop
+    */
+    this.onLoop = new Phaser.Signal();
+
+    /**
+    * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired.
+    * It will be sent 2 parameters: the target object and this tween.
+    * @property {Phaser.Signal} onRepeat
+    */
+    this.onRepeat = new Phaser.Signal();
+
+    /**
+    * The onChildComplete event is fired when the Tween or any of its children completes.
+    * Fires every time a child completes unless a child is set to repeat forever.
+    * It will be sent 2 parameters: the target object and this tween.
+    * @property {Phaser.Signal} onChildComplete
+    */
+    this.onChildComplete = new Phaser.Signal();
+
+    /**
+    * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1).
+    * It will be sent 2 parameters: the target object and this tween.
+    * @property {Phaser.Signal} onComplete
+    */
+    this.onComplete = new Phaser.Signal();
+
+    /**
+    * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running.
+    * @default
+    */
+    this.isRunning = false;
+
+    /**
+    * @property {number} current - The current Tween child being run.
+    * @default
+    * @readonly
+    */
+    this.current = 0;
+
+    /**
+    * @property {object} properties - Target property cache used when building the child data values.
+    */
+    this.properties = {};
+
+    /**
+    * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it.
+    */
+    this.chainedTween = null;
+
+    /**
+    * @property {boolean} isPaused - Is this Tween paused or not?
+    * @default
+    */
+    this.isPaused = false;
+
+    /**
+    * @property {function} _onUpdateCallback - An onUpdate callback.
+    * @private
+    * @default null
+    */
+    this._onUpdateCallback = null;
+
+    /**
+    * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback.
+    * @private
+    * @default null
+    */
+    this._onUpdateCallbackContext = null;
+
+    /**
+    * @property {number} _pausedTime - Private pause timer.
+    * @private
+    * @default
+    */
+    this._pausedTime = 0;
+
+    /**
+    * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss?
+    * @private
+    */
+    this._codePaused = false;
+
+    /**
+    * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not.
+    * @private
+    */
+    this._hasStarted = false;
+};
+
+Phaser.Tween.prototype = {
+
+    /**
+    * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
+    * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
+    * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
+    * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
+    *
+    * @method Phaser.Tween#to
+    * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
+    * @param {number} [duration=1000] - Duration of this tween in ms.
+    * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
+    * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
+    * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
+    * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this induvidual tween, not any chained tweens.
+    * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
+    * @return {Phaser.Tween} This Tween object.
+    */
+    to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
+
+        if (duration === undefined || duration <= 0) { duration = 1000; }
+        if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; }
+        if (autoStart === undefined) { autoStart = false; }
+        if (delay === undefined) { delay = 0; }
+        if (repeat === undefined) { repeat = 0; }
+        if (yoyo === undefined) { yoyo = false; }
+
+        if (typeof ease === 'string' && this.manager.easeMap[ease])
+        {
+            ease = this.manager.easeMap[ease];
+        }
+
+        if (this.isRunning)
+        {
+            console.warn('Phaser.Tween.to cannot be called after Tween.start');
+            return this;
+        }
+
+        this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo));
+
+        if (autoStart)
+        {
+            this.start();
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
+    * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
+    * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
+    * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
+    *
+    * @method Phaser.Tween#from
+    * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
+    * @param {number} [duration=1000] - Duration of this tween in ms.
+    * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
+    * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
+    * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
+    * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this induvidual tween, not any chained tweens.
+    * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
+    * @return {Phaser.Tween} This Tween object.
+    */
+    from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
+
+        if (duration === undefined) { duration = 1000; }
+        if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; }
+        if (autoStart === undefined) { autoStart = false; }
+        if (delay === undefined) { delay = 0; }
+        if (repeat === undefined) { repeat = 0; }
+        if (yoyo === undefined) { yoyo = false; }
+
+        if (typeof ease === 'string' && this.manager.easeMap[ease])
+        {
+            ease = this.manager.easeMap[ease];
+        }
+
+        if (this.isRunning)
+        {
+            console.warn('Phaser.Tween.from cannot be called after Tween.start');
+            return this;
+        }
+
+        this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo));
+
+        if (autoStart)
+        {
+            this.start();
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Starts the tween running. Can also be called by the autoStart parameter of `Tween.to` or `Tween.from`.
+    * This sets the `Tween.isRunning` property to `true` and dispatches a `Tween.onStart` signal.
+    * If the Tween has a delay set then nothing will start tweening until the delay has expired.
+    *
+    * @method Phaser.Tween#start
+    * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    start: function (index) {
+
+        if (index === undefined) { index = 0; }
+
+        if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning)
+        {
+            return this;
+        }
+
+        //  Populate the tween data
+        for (var i = 0; i < this.timeline.length; i++)
+        {
+            //  Build our master property list with the starting values
+            for (var property in this.timeline[i].vEnd)
+            {
+                this.properties[property] = this.target[property] || 0;
+
+                if (!Array.isArray(this.properties[property]))
+                {
+                    //  Ensures we're using numbers, not strings
+                    this.properties[property] *= 1.0;
+                }
+            }
+        }
+
+        for (var i = 0; i < this.timeline.length; i++)
+        {
+            this.timeline[i].loadValues();
+        }
+
+        this.manager.add(this);
+
+        this.isRunning = true;
+
+        if (index < 0 || index > this.timeline.length - 1)
+        {
+            index = 0;
+        }
+
+        this.current = index;
+
+        this.timeline[this.current].start();
+
+        return this;
+
+    },
+
+    /**
+    * Stops the tween if running and flags it for deletion from the TweenManager.
+    * If called directly the `Tween.onComplete` signal is not dispatched and no chained tweens are started unless the complete parameter is set to `true`.
+    * If you just wish to pause a tween then use Tween.pause instead.
+    *
+    * @method Phaser.Tween#stop
+    * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    stop: function (complete) {
+
+        if (complete === undefined) { complete = false; }
+
+        this.isRunning = false;
+
+        this._onUpdateCallback = null;
+        this._onUpdateCallbackContext = null;
+
+        if (complete)
+        {
+            this.onComplete.dispatch(this.target, this);
+
+            if (this.chainedTween)
+            {
+                this.chainedTween.start();
+            }
+        }
+
+        this.manager.remove(this);
+
+        return this;
+
+    },
+
+    /**
+    * Updates either a single TweenData or all TweenData objects properties to the given value.
+    * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak.
+    * The property is not checked, so if you pass an invalid one you'll generate a run-time error.
+    *
+    * @method Phaser.Tween#updateTweenData
+    * @param {string} property - The property to update.
+    * @param {number|function} value - The value to set the property to.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    updateTweenData: function (property, value, index) {
+
+        if (this.timeline.length === 0) { return this; }
+
+        if (index === undefined) { index = 0; }
+
+        if (index === -1)
+        {
+            for (var i = 0; i < this.timeline.length; i++)
+            {
+                this.timeline[i][property] = value;
+            }
+        }
+        else
+        {
+            this.timeline[index][property] = value;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts.
+    * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
+    * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay.
+    * If you have child tweens and pass -1 as the index value it sets the delay across all of them.
+    *
+    * @method Phaser.Tween#delay
+    * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    delay: function (duration, index) {
+
+        return this.updateTweenData('delay', duration, index);
+
+    },
+
+    /**
+    * Sets the number of times this tween will repeat.
+    * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat.
+    * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them.
+    * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll.
+    *
+    * @method Phaser.Tween#repeat
+    * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
+    * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    repeat: function (total, repeatDelay, index) {
+
+        if (repeatDelay === undefined) { repeatDelay = 0; }
+
+        this.updateTweenData('repeatCounter', total, index);
+
+        return this.updateTweenData('repeatDelay', repeatDelay, index);
+
+    },
+
+    /**
+    * Sets the delay in milliseconds before this tween will repeat itself.
+    * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
+    * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
+    * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
+    *
+    * @method Phaser.Tween#repeatDelay
+    * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    repeatDelay: function (duration, index) {
+
+        return this.updateTweenData('repeatDelay', duration, index);
+
+    },
+
+    /**
+    * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start.
+    * Used in combination with repeat you can create endless loops.
+    * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo.
+    * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them.
+    * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll.
+    *
+    * @method Phaser.Tween#yoyo
+    * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo.
+    * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    yoyo: function(enable, yoyoDelay, index) {
+
+        if (yoyoDelay === undefined) { yoyoDelay = 0; }
+
+        this.updateTweenData('yoyo', enable, index);
+
+        return this.updateTweenData('yoyoDelay', yoyoDelay, index);
+
+    },
+
+    /**
+    * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled).
+    * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
+    * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
+    * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
+    *
+    * @method Phaser.Tween#yoyoDelay
+    * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    yoyoDelay: function (duration, index) {
+
+        return this.updateTweenData('yoyoDelay', duration, index);
+
+    },
+
+    /**
+    * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
+    * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
+    * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
+    * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them.
+    *
+    * @method Phaser.Tween#easing
+    * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    easing: function (ease, index) {
+
+        if (typeof ease === 'string' && this.manager.easeMap[ease])
+        {
+            ease = this.manager.easeMap[ease];
+        }
+
+        return this.updateTweenData('easingFunction', ease, index);
+
+    },
+
+    /**
+    * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation.
+    * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
+    * The interpolation function is only used if the target properties is an array.
+    * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them.
+    *
+    * @method Phaser.Tween#interpolation
+    * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default)
+    * @param {object} [context] - The context under which the interpolation function will be run.
+    * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    interpolation: function (interpolation, context, index) {
+
+        if (context === undefined) { context = Phaser.Math; }
+
+        this.updateTweenData('interpolationFunction', interpolation, index);
+
+        return this.updateTweenData('interpolationContext', context, index);
+
+    },
+
+    /**
+    * Set how many times this tween and all of its children will repeat.
+    * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing.
+    * When all child tweens have completed Tween.onLoop will be dispatched.
+    *
+    * @method Phaser.Tween#repeat
+    * @param {number} total - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    repeatAll: function (total) {
+
+        if (total === undefined) { total = 0; }
+
+        this.repeatCounter = total;
+
+        return this;
+
+    },
+
+    /**
+    * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called
+    * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress.
+    * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes.
+    * For that you should listen to `onComplete` on the final tween in your chain.
+    *
+    * If you pass multiple tweens to this method they will be joined into a single long chain.
+    * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C.
+    * Any previously chained tweens that may have been set will be overwritten.
+    *
+    * @method Phaser.Tween#chain
+    * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    chain: function () {
+
+        var i = arguments.length;
+
+        while (i--)
+        {
+            if (i > 0)
+            {
+                arguments[i - 1].chainedTween = arguments[i];
+            }
+            else
+            {
+                this.chainedTween = arguments[i];
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Enables the looping of this tween and all child tweens. If this tween has no children this setting has no effect.
+    * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`.
+    * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero.
+    *
+    * Usage:
+    * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
+    * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
+    * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
+    * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
+    * .loop();
+    * @method Phaser.Tween#loop
+    * @param {boolean} [value=true] - If `true` this tween and any child tweens will loop once they reach the end. Set to `false` to remove an active loop.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    loop: function (value) {
+
+        if (value === undefined) { value = true; }
+
+        if (value)
+        {
+            this.repeatAll(-1);
+        }
+        else
+        {
+            this.repeatCounter = 0;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Sets a callback to be fired each time this tween updates.
+    *
+    * @method Phaser.Tween#onUpdateCallback
+    * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback.
+    * @param {object} callbackContext - The context in which to call the onUpdate callback.
+    * @return {Phaser.Tween} This tween. Useful for method chaining.
+    */
+    onUpdateCallback: function (callback, callbackContext) {
+
+        this._onUpdateCallback = callback;
+        this._onUpdateCallbackContext = callbackContext;
+
+        return this;
+
+    },
+
+    /**
+    * Pauses the tween. Resume playback with Tween.resume.
+    *
+    * @method Phaser.Tween#pause
+    */
+    pause: function () {
+
+        this.isPaused = true;
+
+        this._codePaused = true;
+
+        this._pausedTime = this.game.time.time;
+
+    },
+
+    /**
+    * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
+    *
+    * @private
+    * @method Phaser.Tween#_pause
+    */
+    _pause: function () {
+
+        if (!this._codePaused)
+        {
+            this.isPaused = true;
+
+            this._pausedTime = this.game.time.time;
+        }
+
+    },
+
+    /**
+    * Resumes a paused tween.
+    *
+    * @method Phaser.Tween#resume
+    */
+    resume: function () {
+
+        if (this.isPaused)
+        {
+            this.isPaused = false;
+
+            this._codePaused = false;
+
+            for (var i = 0; i < this.timeline.length; i++)
+            {
+                if (!this.timeline[i].isRunning)
+                {
+                    this.timeline[i].startTime += (this.game.time.time - this._pausedTime);
+                }
+            }
+        }
+
+    },
+
+    /**
+    * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
+    * @method Phaser.Tween#_resume
+    * @private
+    */
+    _resume: function () {
+
+        if (this._codePaused)
+        {
+            return;
+        }
+        else
+        {
+            this.resume();
+        }
+
+    },
+
+    /**
+    * Core tween update function called by the TweenManager. Does not need to be invoked directly.
+    *
+    * @method Phaser.Tween#update
+    * @param {number} time - A timestamp passed in by the TweenManager.
+    * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active).
+    */
+    update: function (time) {
+
+        if (this.pendingDelete)
+        {
+            return false;
+        }
+
+        if (this.isPaused)
+        {
+            return true;
+        }
+
+        var status = this.timeline[this.current].update(time);
+
+        if (status === Phaser.TweenData.PENDING)
+        {
+            return true;
+        }
+        else if (status === Phaser.TweenData.RUNNING)
+        {
+            if (!this._hasStarted)
+            {
+                this.onStart.dispatch(this.target, this);
+                this._hasStarted = true;
+            }
+
+            if (this._onUpdateCallback !== null)
+            {
+                this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]);
+            }
+
+            //  In case the update callback modifies this tween
+            return this.isRunning;
+        }
+        else if (status === Phaser.TweenData.LOOPED)
+        {
+            this.onLoop.dispatch(this.target, this);
+            return true;
+        }
+        else if (status === Phaser.TweenData.COMPLETE)
+        {
+            var complete = false;
+
+            //  What now?
+            if (this.reverse)
+            {
+                this.current--;
+
+                if (this.current < 0)
+                {
+                    this.current = this.timeline.length - 1;
+                    complete = true;
+                }
+            }
+            else
+            {
+                this.current++;
+
+                if (this.current === this.timeline.length)
+                {
+                    this.current = 0;
+                    complete = true;
+                }
+            }
+
+            if (complete)
+            {
+                //  We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it?
+                if (this.repeatCounter === -1)
+                {
+                    this.timeline[this.current].start();
+                    this.onRepeat.dispatch(this.target, this);
+                    return true;
+                }
+                else if (this.repeatCounter > 0)
+                {
+                    this.repeatCounter--;
+
+                    this.timeline[this.current].start();
+                    this.onRepeat.dispatch(this.target, this);
+                    return true;
+                }
+                else
+                {
+                    //  No more repeats and no more children, so we're done
+                    this.isRunning = false;
+                    this.onComplete.dispatch(this.target, this);
+
+                    if (this.chainedTween)
+                    {
+                        this.chainedTween.start();
+                    }
+
+                    return false;
+                }
+            }
+            else
+            {
+                //  We've still got some children to go
+                this.onChildComplete.dispatch(this.target, this);
+                this.timeline[this.current].start();
+                return true;
+            }
+        }
+
+    },
+
+    /**
+    * This will generate an array populated with the tweened object values from start to end.
+    * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
+    * It ignores delay and repeat counts and any chained tweens, but does include child tweens.
+    * Just one play through of the tween data is returned, including yoyo if set.
+    *
+    * @method Phaser.Tween#generateData
+    * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
+    * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned.
+    * @return {array} An array of tweened values.
+    */
+    generateData: function (frameRate, data) {
+
+        if (this.game === null || this.target === null)
+        {
+            return null;
+        }
+
+        if (frameRate === undefined) {
+            frameRate = 60;
+        }
+
+        if (data === undefined) {
+            data = [];
+        }
+
+        //  Populate the tween data
+        for (var i = 0; i < this.timeline.length; i++)
+        {
+            //  Build our master property list with the starting values
+            for (var property in this.timeline[i].vEnd)
+            {
+                this.properties[property] = this.target[property] || 0;
+
+                if (!Array.isArray(this.properties[property]))
+                {
+                    //  Ensures we're using numbers, not strings
+                    this.properties[property] *= 1.0;
+                }
+            }
+        }
+
+        for (var i = 0; i < this.timeline.length; i++)
+        {
+            this.timeline[i].loadValues();
+        }
+
+        for (var i = 0; i < this.timeline.length; i++)
+        {
+            data = data.concat(this.timeline[i].generateData(frameRate));
+        }
+
+        return data;
+
+    }
+
+};
+
+/**
+* @name Phaser.Tween#totalDuration
+* @property {Phaser.TweenData} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds.
+*/
+Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', {
+
+    get: function () {
+
+        var total = 0;
+
+        for (var i = 0; i < this.timeline.length; i++)
+        {
+            total += this.timeline[i].duration;
+        }
+
+        return total;
+
+    }
+
+});
+
+Phaser.Tween.prototype.constructor = Phaser.Tween;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the
+* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for
+* TweenData objects and can contain multiple TweenData objects.
+*
+* @class Phaser.TweenData
+* @constructor
+* @param {Phaser.Tween} parent - The Tween that owns this TweenData object.
+*/
+Phaser.TweenData = function (parent) {
+
+    /**
+    * @property {Phaser.Tween} parent - The Tween which owns this TweenData.
+    */
+    this.parent = parent;
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = parent.game;
+
+    /**
+    * @property {object} vStart - An object containing the values at the start of the tween.
+    * @private
+    */
+    this.vStart = {};
+
+    /**
+    * @property {object} vStartCache - Cached starting values.
+    * @private
+    */
+    this.vStartCache = {};
+
+    /**
+    * @property {object} vEnd - An object containing the values at the end of the tween.
+    * @private
+    */
+    this.vEnd = {};
+
+    /**
+    * @property {object} vEndCache - Cached ending values.
+    * @private
+    */
+    this.vEndCache = {};
+
+    /**
+    * @property {number} duration - The duration of the tween in ms.
+    * @default
+    */
+    this.duration = 1000;
+
+    /**
+    * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is.
+    * @readonly
+    */
+    this.percent = 0;
+
+    /**
+    * @property {number} value - The current calculated value.
+    * @readonly
+    */
+    this.value = 0;
+
+    /**
+    * @property {number} repeatCounter - If the Tween is set to repeat this contains the current repeat count.
+    */
+    this.repeatCounter = 0;
+
+    /**
+    * @property {number} repeatDelay - The amount of time in ms between repeats of this tween.
+    */
+    this.repeatDelay = 0;
+
+    /**
+    * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween)
+    * @default
+    */
+    this.interpolate = false;
+
+    /**
+    * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false.
+    * @default
+    */
+    this.yoyo = false;
+
+    /**
+    * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween.
+    */
+    this.yoyoDelay = 0;
+
+    /**
+    * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true).
+    * @default
+    */
+    this.inReverse = false;
+
+    /**
+    * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats.
+    * @default
+    */
+    this.delay = 0;
+
+    /**
+    * @property {number} dt - Current time value.
+    */
+    this.dt = 0;
+
+    /**
+    * @property {number} startTime - The time the Tween started or null if it hasn't yet started.
+    */
+    this.startTime = null;
+
+    /**
+    * @property {function} easingFunction - The easing function used for the Tween.
+    * @default Phaser.Easing.Default
+    */
+    this.easingFunction = Phaser.Easing.Default;
+
+    /**
+    * @property {function} interpolationFunction - The interpolation function used for the Tween.
+    * @default Phaser.Math.linearInterpolation
+    */
+    this.interpolationFunction = Phaser.Math.linearInterpolation;
+
+    /**
+    * @property {object} interpolationContext - The interpolation function context used for the Tween.
+    * @default Phaser.Math
+    */
+    this.interpolationContext = Phaser.Math;
+
+    /**
+    * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running.
+    * @default
+    */
+    this.isRunning = false;
+
+    /**
+    * @property {boolean} isFrom - Is this a from tween or a to tween?
+    * @default
+    */
+    this.isFrom = false;
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.TweenData.PENDING = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.TweenData.RUNNING = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.TweenData.LOOPED = 2;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.TweenData.COMPLETE = 3;
+
+Phaser.TweenData.prototype = {
+
+    /**
+    * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
+    * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
+    *
+    * @method Phaser.TweenData#to
+    * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
+    * @param {number} [duration=1000] - Duration of this tween in ms.
+    * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will.
+    * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
+    * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens.
+    * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
+    * @return {Phaser.TweenData} This Tween object.
+    */
+    to: function (properties, duration, ease, delay, repeat, yoyo) {
+
+        this.vEnd = properties;
+        this.duration = duration;
+        this.easingFunction = ease;
+        this.delay = delay;
+        this.repeatCounter = repeat;
+        this.yoyo = yoyo;
+
+        this.isFrom = false;
+
+        return this;
+
+    },
+
+    /**
+    * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
+    * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
+    *
+    * @method Phaser.TweenData#from
+    * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
+    * @param {number} [duration=1000] - Duration of this tween in ms.
+    * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will.
+    * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
+    * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens.
+    * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
+    * @return {Phaser.TweenData} This Tween object.
+    */
+    from: function (properties, duration, ease, delay, repeat, yoyo) {
+
+        this.vEnd = properties;
+        this.duration = duration;
+        this.easingFunction = ease;
+        this.delay = delay;
+        this.repeatCounter = repeat;
+        this.yoyo = yoyo;
+
+        this.isFrom = true;
+
+        return this;
+
+    },
+
+    /**
+    * Starts the Tween running.
+    *
+    * @method Phaser.TweenData#start
+    * @return {Phaser.TweenData} This Tween object.
+    */
+    start: function () {
+
+        this.startTime = this.game.time.time + this.delay;
+
+        if (this.parent.reverse)
+        {
+            this.dt = this.duration;
+        }
+        else
+        {
+            this.dt = 0;
+        }
+
+        if (this.delay > 0)
+        {
+            this.isRunning = false;
+        }
+        else
+        {
+            this.isRunning = true;
+        }
+
+        if (this.isFrom)
+        {
+            //  Reverse them all and instant set them
+            for (var property in this.vStartCache)
+            {
+                this.vStart[property] = this.vEndCache[property];
+                this.vEnd[property] = this.vStartCache[property];
+                this.parent.target[property] = this.vStart[property];
+            }
+        }
+
+        this.value = 0;
+        this.yoyoCounter = 0;
+
+        return this;
+
+    },
+
+    /**
+    * Loads the values from the target object into this Tween.
+    *
+    * @private
+    * @method Phaser.TweenData#loadValues
+    * @return {Phaser.TweenData} This Tween object.
+    */
+    loadValues: function () {
+
+        for (var property in this.parent.properties)
+        {
+            //  Load the property from the parent object
+            this.vStart[property] = this.parent.properties[property];
+
+            //  Check if an Array was provided as property value
+            if (Array.isArray(this.vEnd[property]))
+            {
+                if (this.vEnd[property].length === 0)
+                {
+                    continue;
+                }
+
+                if (this.percent === 0)
+                {
+                    //  Put the start value at the beginning of the array
+                    //  but we only want to do this once, if the Tween hasn't run before
+                    this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]);
+                }
+            }
+
+            if (typeof this.vEnd[property] !== 'undefined')
+            {
+                if (typeof this.vEnd[property] === 'string')
+                {
+                    //  Parses relative end values with start as base (e.g.: +10, -3)
+                    this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10);
+                }
+
+                this.parent.properties[property] = this.vEnd[property];
+            }
+            else
+            {
+                //  Null tween
+                this.vEnd[property] = this.vStart[property];
+            }
+
+            this.vStartCache[property] = this.vStart[property];
+            this.vEndCache[property] = this.vEnd[property];
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Updates this Tween. This is called automatically by Phaser.Tween.
+    *
+    * @protected
+    * @method Phaser.TweenData#update
+    * @param {number} time - A timestamp passed in by the Tween parent.
+    * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE.
+    */
+    update: function (time) {
+
+        if (!this.isRunning)
+        {
+            if (time >= this.startTime)
+            {
+                this.isRunning = true;
+            }
+            else
+            {
+                return Phaser.TweenData.PENDING;
+            }
+        }
+        else
+        {
+            //  Is Running, but is waiting to repeat
+            if (time < this.startTime)
+            {
+                return Phaser.TweenData.RUNNING;
+            }
+        }
+
+        if (this.parent.reverse)
+        {
+            this.dt -= this.game.time.elapsedMS * this.parent.timeScale;
+            this.dt = Math.max(this.dt, 0);
+        }
+        else
+        {
+            this.dt += this.game.time.elapsedMS * this.parent.timeScale;
+            this.dt = Math.min(this.dt, this.duration);
+        }
+
+        this.percent = this.dt / this.duration;
+
+        this.value = this.easingFunction(this.percent);
+
+        for (var property in this.vEnd)
+        {
+            var start = this.vStart[property];
+            var end = this.vEnd[property];
+
+            if (Array.isArray(end))
+            {
+                this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value);
+            }
+            else
+            {
+                this.parent.target[property] = start + ((end - start) * this.value);
+            }
+        }
+
+        if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0))
+        {
+            return this.repeat();
+        }
+        
+        return Phaser.TweenData.RUNNING;
+
+    },
+
+    /**
+    * This will generate an array populated with the tweened object values from start to end.
+    * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
+    * Just one play through of the tween data is returned, including yoyo if set.
+    *
+    * @method Phaser.TweenData#generateData
+    * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
+    * @return {array} An array of tweened values.
+    */
+    generateData: function (frameRate) {
+
+        if (this.parent.reverse)
+        {
+            this.dt = this.duration;
+        }
+        else
+        {
+            this.dt = 0;
+        }
+
+        var data = [];
+        var complete = false;
+        var fps = (1 / frameRate) * 1000;
+
+        do
+        {
+            if (this.parent.reverse)
+            {
+                this.dt -= fps;
+                this.dt = Math.max(this.dt, 0);
+            }
+            else
+            {
+                this.dt += fps;
+                this.dt = Math.min(this.dt, this.duration);
+            }
+
+            this.percent = this.dt / this.duration;
+
+            this.value = this.easingFunction(this.percent);
+
+            var blob = {};
+
+            for (var property in this.vEnd)
+            {
+                var start = this.vStart[property];
+                var end = this.vEnd[property];
+
+                if (Array.isArray(end))
+                {
+                    blob[property] = this.interpolationFunction(end, this.value);
+                }
+                else
+                {
+                    blob[property] = start + ((end - start) * this.value);
+                }
+            }
+
+            data.push(blob);
+
+            if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0))
+            {
+                complete = true;
+            }
+
+        } while (!complete);
+
+        if (this.yoyo)
+        {
+            var reversed = data.slice();
+            reversed.reverse();
+            data = data.concat(reversed);
+        }
+
+        return data;
+
+    },
+
+    /**
+    * Checks if this Tween is meant to repeat or yoyo and handles doing so.
+    *
+    * @private
+    * @method Phaser.TweenData#repeat
+    * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE.
+    */
+    repeat: function () {
+
+        //  If not a yoyo and repeatCounter = 0 then we're done
+        if (this.yoyo)
+        {
+            //  We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end
+            if (this.inReverse && this.repeatCounter === 0)
+            {
+                return Phaser.TweenData.COMPLETE;
+            }
+
+            this.inReverse = !this.inReverse;
+        }
+        else
+        {
+            if (this.repeatCounter === 0)
+            {
+                return Phaser.TweenData.COMPLETE;
+            }
+        }
+
+        if (this.inReverse)
+        {
+            //  If inReverse we're going from vEnd to vStartCache
+            for (var property in this.vStartCache)
+            {
+                this.vStart[property] = this.vEndCache[property];
+                this.vEnd[property] = this.vStartCache[property];
+            }
+        }
+        else
+        {
+            //  If not inReverse we're just repopulating the cache again
+            for (var property in this.vStartCache)
+            {
+                this.vStart[property] = this.vStartCache[property];
+                this.vEnd[property] = this.vEndCache[property];
+            }
+
+            //  -1 means repeat forever, otherwise decrement the repeatCounter
+            //  We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total
+            if (this.repeatCounter > 0)
+            {
+                this.repeatCounter--;
+            }
+        }
+
+        this.startTime = this.game.time.time;
+
+        if (this.yoyo && this.inReverse)
+        {
+            this.startTime += this.yoyoDelay;
+        }
+        else if (!this.inReverse)
+        {
+            this.startTime += this.repeatDelay;
+        }
+
+        if (this.parent.reverse)
+        {
+            this.dt = this.duration;
+        }
+        else
+        {
+            this.dt = 0;
+        }
+
+        return Phaser.TweenData.LOOPED;
+
+    }
+
+};
+
+Phaser.TweenData.prototype.constructor = Phaser.TweenData;
+
+/* jshint curly: false */
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A collection of easing methods defining ease-in and ease-out curves.
+*
+* @class Phaser.Easing
+*/
+Phaser.Easing = {
+
+    /**
+    * Linear easing.
+    *
+    * @class Phaser.Easing.Linear
+    */
+    Linear: {
+
+        /**
+        * Linear Easing (no variation).
+        *
+        * @method Phaser.Easing.Linear#None
+        * @param {number} k - The value to be tweened.
+        * @returns {number} k.
+        */
+        None: function ( k ) {
+
+            return k;
+
+        }
+
+    },
+
+    /**
+    * Quadratic easing.
+    *
+    * @class Phaser.Easing.Quadratic
+    */
+    Quadratic: {
+
+        /**
+        * Ease-in.
+        *
+        * @method Phaser.Easing.Quadratic#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} k^2.
+        */
+        In: function ( k ) {
+
+            return k * k;
+
+        },
+
+        /**
+        * Ease-out.
+        *
+        * @method Phaser.Easing.Quadratic#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} k* (2-k).
+        */
+        Out: function ( k ) {
+
+            return k * ( 2 - k );
+
+        },
+
+        /**
+        * Ease-in/out.
+        *
+        * @method Phaser.Easing.Quadratic#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
+            return - 0.5 * ( --k * ( k - 2 ) - 1 );
+
+        }
+
+    },
+
+    /**
+    * Cubic easing.
+    *
+    * @class Phaser.Easing.Cubic
+    */
+    Cubic: {
+
+        /**
+        * Cubic ease-in.
+        *
+        * @method Phaser.Easing.Cubic#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            return k * k * k;
+
+        },
+
+        /**
+        * Cubic ease-out.
+        *
+        * @method Phaser.Easing.Cubic#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            return --k * k * k + 1;
+
+        },
+
+        /**
+        * Cubic ease-in/out.
+        *
+        * @method Phaser.Easing.Cubic#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
+            return 0.5 * ( ( k -= 2 ) * k * k + 2 );
+
+        }
+
+    },
+
+    /**
+    * Quartic easing.
+    *
+    * @class Phaser.Easing.Quartic
+    */
+    Quartic: {
+
+        /**
+        * Quartic ease-in.
+        *
+        * @method Phaser.Easing.Quartic#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            return k * k * k * k;
+
+        },
+
+        /**
+        * Quartic ease-out.
+        *
+        * @method Phaser.Easing.Quartic#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            return 1 - ( --k * k * k * k );
+
+        },
+
+        /**
+        * Quartic ease-in/out.
+        *
+        * @method Phaser.Easing.Quartic#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
+            return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
+
+        }
+
+    },
+
+    /**
+    * Quintic easing.
+    *
+    * @class Phaser.Easing.Quintic
+    */
+    Quintic: {
+
+        /**
+        * Quintic ease-in.
+        *
+        * @method Phaser.Easing.Quintic#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            return k * k * k * k * k;
+
+        },
+
+        /**
+        * Quintic ease-out.
+        *
+        * @method Phaser.Easing.Quintic#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            return --k * k * k * k * k + 1;
+
+        },
+
+        /**
+        * Quintic ease-in/out.
+        *
+        * @method Phaser.Easing.Quintic#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
+            return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
+
+        }
+
+    },
+
+    /**
+    * Sinusoidal easing.
+    *
+    * @class Phaser.Easing.Sinusoidal
+    */
+    Sinusoidal: {
+
+        /**
+        * Sinusoidal ease-in.
+        *
+        * @method Phaser.Easing.Sinusoidal#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            if (k === 0) return 0;
+            if (k === 1) return 1;
+            return 1 - Math.cos( k * Math.PI / 2 );
+
+        },
+
+        /**
+        * Sinusoidal ease-out.
+        *
+        * @method Phaser.Easing.Sinusoidal#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            if (k === 0) return 0;
+            if (k === 1) return 1;
+            return Math.sin( k * Math.PI / 2 );
+
+        },
+
+        /**
+        * Sinusoidal ease-in/out.
+        *
+        * @method Phaser.Easing.Sinusoidal#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if (k === 0) return 0;
+            if (k === 1) return 1;
+            return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
+
+        }
+
+    },
+
+    /**
+    * Exponential easing.
+    *
+    * @class Phaser.Easing.Exponential
+    */
+    Exponential: {
+
+        /**
+        * Exponential ease-in.
+        *
+        * @method Phaser.Easing.Exponential#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            return k === 0 ? 0 : Math.pow( 1024, k - 1 );
+
+        },
+
+        /**
+        * Exponential ease-out.
+        *
+        * @method Phaser.Easing.Exponential#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
+
+        },
+
+        /**
+        * Exponential ease-in/out.
+        *
+        * @method Phaser.Easing.Exponential#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( k === 0 ) return 0;
+            if ( k === 1 ) return 1;
+            if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
+            return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
+
+        }
+
+    },
+
+    /**
+    * Circular easing.
+    *
+    * @class Phaser.Easing.Circular
+    */
+    Circular: {
+
+        /**
+        * Circular ease-in.
+        *
+        * @method Phaser.Easing.Circular#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            return 1 - Math.sqrt( 1 - k * k );
+
+        },
+
+        /**
+        * Circular ease-out.
+        *
+        * @method Phaser.Easing.Circular#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            return Math.sqrt( 1 - ( --k * k ) );
+
+        },
+
+        /**
+        * Circular ease-in/out.
+        *
+        * @method Phaser.Easing.Circular#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
+            return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
+
+        }
+
+    },
+
+    /**
+    * Elastic easing.
+    *
+    * @class Phaser.Easing.Elastic
+    */
+    Elastic: {
+
+        /**
+        * Elastic ease-in.
+        *
+        * @method Phaser.Easing.Elastic#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            var s, a = 0.1, p = 0.4;
+            if ( k === 0 ) return 0;
+            if ( k === 1 ) return 1;
+            if ( !a || a < 1 ) { a = 1; s = p / 4; }
+            else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
+            return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
+
+        },
+
+        /**
+        * Elastic ease-out.
+        *
+        * @method Phaser.Easing.Elastic#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            var s, a = 0.1, p = 0.4;
+            if ( k === 0 ) return 0;
+            if ( k === 1 ) return 1;
+            if ( !a || a < 1 ) { a = 1; s = p / 4; }
+            else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
+            return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
+
+        },
+
+        /**
+        * Elastic ease-in/out.
+        *
+        * @method Phaser.Easing.Elastic#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            var s, a = 0.1, p = 0.4;
+            if ( k === 0 ) return 0;
+            if ( k === 1 ) return 1;
+            if ( !a || a < 1 ) { a = 1; s = p / 4; }
+            else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
+            if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
+            return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
+
+        }
+
+    },
+
+    /**
+    * Back easing.
+    *
+    * @class Phaser.Easing.Back
+    */
+    Back: {
+
+        /**
+        * Back ease-in.
+        *
+        * @method Phaser.Easing.Back#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            var s = 1.70158;
+            return k * k * ( ( s + 1 ) * k - s );
+
+        },
+
+        /**
+        * Back ease-out.
+        *
+        * @method Phaser.Easing.Back#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            var s = 1.70158;
+            return --k * k * ( ( s + 1 ) * k + s ) + 1;
+
+        },
+
+        /**
+        * Back ease-in/out.
+        *
+        * @method Phaser.Easing.Back#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            var s = 1.70158 * 1.525;
+            if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
+            return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
+
+        }
+
+    },
+
+    /**
+    * Bounce easing.
+    *
+    * @class Phaser.Easing.Bounce
+    */
+    Bounce: {
+
+        /**
+        * Bounce ease-in.
+        *
+        * @method Phaser.Easing.Bounce#In
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        In: function ( k ) {
+
+            return 1 - Phaser.Easing.Bounce.Out( 1 - k );
+
+        },
+
+        /**
+        * Bounce ease-out.
+        *
+        * @method Phaser.Easing.Bounce#Out
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        Out: function ( k ) {
+
+            if ( k < ( 1 / 2.75 ) ) {
+
+                return 7.5625 * k * k;
+
+            } else if ( k < ( 2 / 2.75 ) ) {
+
+                return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
+
+            } else if ( k < ( 2.5 / 2.75 ) ) {
+
+                return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
+
+            } else {
+
+                return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
+
+            }
+
+        },
+
+        /**
+        * Bounce ease-in/out.
+        *
+        * @method Phaser.Easing.Bounce#InOut
+        * @param {number} k - The value to be tweened.
+        * @returns {number} The tweened value.
+        */
+        InOut: function ( k ) {
+
+            if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5;
+            return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
+
+        }
+
+    }
+
+};
+
+Phaser.Easing.Default = Phaser.Easing.Linear.None;
+Phaser.Easing.Power0 = Phaser.Easing.Linear.None;
+Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out;
+Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out;
+Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out;
+Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* This is the core internal game clock.
+*
+* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens,
+* and also handles the standard Timer pool.
+*
+* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}.
+*
+* @class Phaser.Time
+* @constructor
+* @param {Phaser.Game} game A reference to the currently running game.
+*/
+Phaser.Time = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    * @protected
+    */
+    this.game = game;
+
+    /**
+    * The `Date.now()` value when the time was last updated.
+    * @property {integer} time
+    * @protected
+    */
+    this.time = 0;
+
+    /**
+    * The `now` when the previous update occurred.
+    * @property {number} prevTime
+    * @protected
+    */
+    this.prevTime = 0;
+
+    /**
+    * An increasing value representing cumulative milliseconds since an undisclosed epoch.
+    *
+    * While this value is in milliseconds and can be used to compute time deltas,
+    * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference.
+    *
+    * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now;
+    * the value can only be relied upon within a particular game instance.
+    *
+    * @property {number} now
+    * @protected
+    */
+    this.now = 0;
+
+    /**
+    * Elapsed time since the last time update, in milliseconds, based on `now`.
+    *
+    * This value _may_ include time that the game is paused/inactive.
+    *
+    * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done.
+    * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
+    *
+    * @property {number} elapsed
+    * @see Phaser.Time.time
+    * @protected
+    */
+    this.elapsed = 0;
+
+    /**
+    * The time in ms since the last time update, in milliseconds, based on `time`.
+    *
+    * This value is corrected for game pauses and will be "about zero" after a game is resumed.
+    *
+    * _Note:_ This is updated once per game loop - even if multiple logic update steps are done.
+    * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
+    *
+    * @property {integer} elapsedMS
+    * @protected
+    */
+    this.elapsedMS = 0;
+
+    /**
+    * The physics update delta, in fractional seconds.
+    *
+    * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`)
+    * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system
+    * is unable to consistently maintain the desired FPS.
+    *
+    * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`.
+    *
+    * @property {number} physicsElapsed
+    */
+    this.physicsElapsed = 0;
+
+    /**
+    * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`.
+    *
+    * @property {number} physicsElapsedMS
+    */
+    this.physicsElapsedMS = 0;
+
+    /**
+    * The desired frame rate of the game.
+    *
+    * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates.
+    *
+    * @property {number} desiredFps
+    * @default
+    */
+    this.desiredFps = 60;
+
+    /**
+    * The suggested frame rate for your game, based on an averaged real frame rate.
+    * This value is only populated if `Time.advancedTiming` is enabled.
+    *
+    * _Note:_ This is not available until after a few frames have passed; use it after a few seconds (eg. after the menus)
+    *
+    * @property {number} suggestedFps
+    * @default
+    */
+    this.suggestedFps = null;
+
+    /**
+    * Scaling factor to make the game move smoothly in slow motion
+    * - 1.0 = normal speed
+    * - 2.0 = half speed
+    * @property {number} slowMotion
+    * @default
+    */
+    this.slowMotion = 1.0;
+
+    /**
+    * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated.
+    * @property {boolean} advancedTiming
+    * @default
+    */
+    this.advancedTiming = false;
+
+    /**
+    * Advanced timing result: The number of render frames record in the last second.
+    *
+    * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
+    * @property {integer} frames
+    * @readonly
+    */
+    this.frames = 0;
+
+    /**
+    * Advanced timing result: Frames per second.
+    *
+    * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
+    * @property {number} fps
+    * @readonly
+    */
+    this.fps = 0;
+
+    /**
+    * Advanced timing result: The lowest rate the fps has dropped to.
+    *
+    * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
+    * This value can be manually reset.
+    * @property {number} fpsMin
+    */
+    this.fpsMin = 1000;
+
+    /**
+    * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps).
+    *
+    * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
+    * This value can be manually reset.
+    * @property {number} fpsMax
+    */
+    this.fpsMax = 0;
+
+    /**
+    * Advanced timing result: The minimum amount of time the game has taken between consecutive frames.
+    *
+    * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
+    * This value can be manually reset.
+    * @property {number} msMin
+    * @default
+    */
+    this.msMin = 1000;
+
+    /**
+    * Advanced timing result: The maximum amount of time the game has taken between consecutive frames.
+    *
+    * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
+    * This value can be manually reset.
+    * @property {number} msMax
+    */
+    this.msMax = 0;
+
+    /**
+    * Records how long the game was last paused, in milliseconds.
+    * (This is not updated until the game is resumed.)
+    * @property {number} pauseDuration
+    */
+    this.pauseDuration = 0;
+
+    /**
+    * @property {number} timeToCall - The value that setTimeout needs to work out when to next update
+    * @protected
+    */
+    this.timeToCall = 0;
+
+    /**
+    * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop
+    * @protected
+    */
+    this.timeExpected = 0;
+
+    /**
+    * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to.
+    * @property {Phaser.Timer} events
+    */
+    this.events = new Phaser.Timer(this.game, false);
+
+    /**
+    * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated
+    * @private
+    */
+    this._frameCount = 0;
+
+    /**
+    * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated
+    * @private
+    */
+    this._elapsedAccumulator = 0;
+
+    /**
+    * @property {number} _started - The time at which the Game instance started.
+    * @private
+    */
+    this._started = 0;
+
+    /**
+    * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
+    * @private
+    */
+    this._timeLastSecond = 0;
+
+    /**
+    * @property {number} _pauseStarted - The time the game started being paused.
+    * @private
+    */
+    this._pauseStarted = 0;
+
+    /**
+    * @property {boolean} _justResumed - Internal value used to recover from the game pause state.
+    * @private
+    */
+    this._justResumed = false;
+
+    /**
+    * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects.
+    * @private
+    */
+    this._timers = [];
+
+};
+
+Phaser.Time.prototype = {
+
+    /**
+    * Called automatically by Phaser.Game after boot. Should not be called directly.
+    *
+    * @method Phaser.Time#boot
+    * @protected
+    */
+    boot: function () {
+
+        this._started = Date.now();
+        this.time = Date.now();
+        this.events.start();
+
+    },
+
+    /**
+    * Adds an existing Phaser.Timer object to the Timer pool.
+    *
+    * @method Phaser.Time#add
+    * @param {Phaser.Timer} timer - An existing Phaser.Timer object.
+    * @return {Phaser.Timer} The given Phaser.Timer object.
+    */
+    add: function (timer) {
+
+        this._timers.push(timer);
+
+        return timer;
+
+    },
+
+    /**
+    * Creates a new stand-alone Phaser.Timer object.
+    *
+    * @method Phaser.Time#create
+    * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
+    * @return {Phaser.Timer} The Timer object that was created.
+    */
+    create: function (autoDestroy) {
+
+        if (autoDestroy === undefined) { autoDestroy = true; }
+
+        var timer = new Phaser.Timer(this.game, autoDestroy);
+
+        this._timers.push(timer);
+
+        return timer;
+
+    },
+
+    /**
+    * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer.
+    *
+    * @method Phaser.Time#removeAll
+    */
+    removeAll: function () {
+
+        for (var i = 0; i < this._timers.length; i++)
+        {
+            this._timers[i].destroy();
+        }
+
+        this._timers = [];
+
+        this.events.removeAll();
+
+    },
+
+    /**
+    * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game.
+    *
+    * @method Phaser.Time#update
+    * @protected
+    * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}.
+    */
+    update: function (time) {
+
+        if (this.game.raf._isSetTimeOut)
+        {
+            this.updateSetTimeout(time);
+        }
+        else
+        {
+            this.updateRAF(time);
+        }
+
+        if (this.advancedTiming)
+        {
+            this.updateAdvancedTiming();
+        }
+
+        //  Paused but still running?
+        if (!this.game.paused)
+        {
+            //  Our internal Phaser.Timer
+            this.events.update(this.time);
+
+            if (this._timers.length)
+            {
+                this.updateTimers();
+            }
+        }
+
+    },
+
+    /**
+    * setTimeOut specific time update handler.
+    * Called automatically by Time.update.
+    *
+    * @method Phaser.Time#updateSetTimeout
+    * @private
+    * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}.
+    */
+    updateSetTimeout: function (time) {
+
+        //  Set to the old Date.now value
+        var previousDateNow = this.time;
+
+        //  With SetTimeout the time value is always the same as Date.now, so no need to get it again
+        this.time = time;
+
+        //  Adjust accordingly.
+        this.elapsedMS = this.time - previousDateNow;
+
+        // 'now' is currently still holding the time of the last call, move it into prevTime
+        this.prevTime = this.now;
+
+        // update 'now' to hold the current time
+        this.now = time;
+
+        // elapsed time between previous call and now
+        this.elapsed = this.now - this.prevTime;
+
+        // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game
+        this.timeToCall = Math.floor(Math.max(0, (1000.0 / this.desiredFps) - (this.timeCallExpected - time)));
+
+        // time when the next call is expected if using timers
+        this.timeCallExpected = time + this.timeToCall;
+
+        //  Set the physics elapsed time... this will always be 1 / this.desiredFps because we're using fixed time steps in game.update now
+        this.physicsElapsed = 1 / this.desiredFps;
+
+        this.physicsElapsedMS = this.physicsElapsed * 1000;
+
+    },
+
+    /**
+    * raf specific time update handler.
+    * Called automatically by Time.update.
+    *
+    * @method Phaser.Time#updateRAF
+    * @private
+    * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}.
+    */
+    updateRAF: function (time) {
+
+        //  Set to the old Date.now value
+        var previousDateNow = this.time;
+
+        // this.time always holds Date.now, this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now)
+        this.time = Date.now();
+
+        //  Adjust accordingly.
+        this.elapsedMS = this.time - previousDateNow;
+
+        // 'now' is currently still holding the time of the last call, move it into prevTime
+        this.prevTime = this.now;
+
+        // update 'now' to hold the current time
+        this.now = time;
+
+        // elapsed time between previous call and now
+        this.elapsed = this.now - this.prevTime;
+
+        //  Set the physics elapsed time... this will always be 1 / this.desiredFps because we're using fixed time steps in game.update now
+        this.physicsElapsed = 1 / this.desiredFps;
+
+        this.physicsElapsedMS = this.physicsElapsed * 1000;
+
+    },
+
+    /**
+    * Handles the updating of the Phaser.Timers (if any)
+    * Called automatically by Time.update.
+    *
+    * @method Phaser.Time#updateTimers
+    * @private
+    */
+    updateTimers: function () {
+
+        //  Any game level timers
+        var i = 0;
+        var len = this._timers.length;
+
+        while (i < len)
+        {
+            if (this._timers[i].update(this.time))
+            {
+                i++;
+            }
+            else
+            {
+                //  Timer requests to be removed
+                this._timers.splice(i, 1);
+                len--;
+            }
+        }
+
+    },
+
+    /**
+    * Handles the updating of the advanced timing values (if enabled)
+    * Called automatically by Time.update.
+    *
+    * @method Phaser.Time#updateAdvancedTiming
+    * @private
+    */
+    updateAdvancedTiming: function () {
+
+        // count the number of time.update calls
+        this._frameCount++;
+        this._elapsedAccumulator += this.elapsed;
+
+        // occasionally recalculate the suggestedFps based on the accumulated elapsed time
+        if (this._frameCount >= this.desiredFps * 2)
+        {
+            // this formula calculates suggestedFps in multiples of 5 fps
+            this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5;
+            this._frameCount = 0;
+            this._elapsedAccumulator = 0;
+        }
+
+        this.msMin = Math.min(this.msMin, this.elapsed);
+        this.msMax = Math.max(this.msMax, this.elapsed);
+
+        this.frames++;
+
+        if (this.now > this._timeLastSecond + 1000)
+        {
+            this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
+            this.fpsMin = Math.min(this.fpsMin, this.fps);
+            this.fpsMax = Math.max(this.fpsMax, this.fps);
+            this._timeLastSecond = this.now;
+            this.frames = 0;
+        }
+
+    },
+
+    /**
+    * Called when the game enters a paused state.
+    *
+    * @method Phaser.Time#gamePaused
+    * @private
+    */
+    gamePaused: function () {
+
+        this._pauseStarted = Date.now();
+
+        this.events.pause();
+
+        var i = this._timers.length;
+
+        while (i--)
+        {
+            this._timers[i]._pause();
+        }
+
+    },
+
+    /**
+    * Called when the game resumes from a paused state.
+    *
+    * @method Phaser.Time#gameResumed
+    * @private
+    */
+    gameResumed: function () {
+
+        // Set the parameter which stores Date.now() to make sure it's correct on resume
+        this.time = Date.now();
+
+        this.pauseDuration = this.time - this._pauseStarted;
+
+        this.events.resume();
+
+        var i = this._timers.length;
+
+        while (i--)
+        {
+            this._timers[i]._resume();
+        }
+
+    },
+
+    /**
+    * The number of seconds that have elapsed since the game was started.
+    *
+    * @method Phaser.Time#totalElapsedSeconds
+    * @return {number} The number of seconds that have elapsed since the game was started.
+    */
+    totalElapsedSeconds: function() {
+        return (this.time - this._started) * 0.001;
+    },
+
+    /**
+    * How long has passed since the given time.
+    *
+    * @method Phaser.Time#elapsedSince
+    * @param {number} since - The time you want to measure against.
+    * @return {number} The difference between the given time and now.
+    */
+    elapsedSince: function (since) {
+        return this.time - since;
+    },
+
+    /**
+    * How long has passed since the given time (in seconds).
+    *
+    * @method Phaser.Time#elapsedSecondsSince
+    * @param {number} since - The time you want to measure (in seconds).
+    * @return {number} Duration between given time and now (in seconds).
+    */
+    elapsedSecondsSince: function (since) {
+        return (this.time - since) * 0.001;
+    },
+
+    /**
+    * Resets the private _started value to now and removes all currently running Timers.
+    *
+    * @method Phaser.Time#reset
+    */
+    reset: function () {
+
+        this._started = this.time;
+        this.removeAll();
+
+    }
+
+};
+
+Phaser.Time.prototype.constructor = Phaser.Time;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Timer is a way to create small re-usable (or disposable) objects that wait for a specific moment in time,
+* and then run the specified callbacks.
+*
+* You can add many events to a Timer, each with their own delays. A Timer uses milliseconds as its unit of time (there are 1000 ms in 1 second).
+* So a delay to 250 would fire the event every quarter of a second.
+*
+* Timers are based on real-world (not physics) time, adjusted for game pause durations.
+*
+* @class Phaser.Timer
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events).
+*/
+Phaser.Timer = function (game, autoDestroy) {
+
+    if (autoDestroy === undefined) { autoDestroy = true; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    * @protected
+    */
+    this.game = game;
+
+    /**
+    * True if the Timer is actively running.
+    *
+    * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer.
+    * @property {boolean} running
+    * @default
+    * @readonly
+    */
+    this.running = false;
+
+    /**
+    * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events).
+    * @property {boolean} autoDestroy
+    */
+    this.autoDestroy = autoDestroy;
+
+    /**
+    * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending.
+    * @readonly
+    * @default
+    */
+    this.expired = false;
+
+    /**
+    * @property {number} elapsed - Elapsed time since the last frame (in ms).
+    * @protected
+    */
+    this.elapsed = 0;
+
+    /**
+    * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it.
+    */
+    this.events = [];
+
+    /**
+    * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue.
+    *
+    * The signal is supplied with one argument, `timer`, which is this Timer object.
+    *
+    * @property {Phaser.Signal} onComplete
+    */
+    this.onComplete = new Phaser.Signal();
+
+    /**
+    * @property {number} nextTick - The time the next tick will occur.
+    * @readonly
+    * @protected
+    */
+    this.nextTick = 0;
+
+    /**
+    * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations.
+    */
+    this.timeCap = 1000;
+
+    /**
+    * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing.
+    * @readonly
+    * @default
+    */
+    this.paused = false;
+
+    /**
+    * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss?
+    * @private
+    */
+    this._codePaused = false;
+
+    /**
+    * @property {number} _started - The time at which this Timer instance started running.
+    * @private
+    * @default
+    */
+    this._started = 0;
+
+    /**
+    * @property {number} _pauseStarted - The time the game started being paused.
+    * @private
+    */
+    this._pauseStarted = 0;
+
+    /**
+    * @property {number} _pauseTotal - Total paused time.
+    * @private
+    */
+    this._pauseTotal = 0;
+
+    /**
+    * @property {number} _now - The current start-time adjusted time.
+    * @private
+    */
+    this._now = Date.now();
+
+    /**
+    * @property {number} _len - Temp. array length variable.
+    * @private
+    */
+    this._len = 0;
+
+    /**
+    * @property {number} _marked - Temp. counter variable.
+    * @private
+    */
+    this._marked = 0;
+
+    /**
+    * @property {number} _i - Temp. array counter variable.
+    * @private
+    */
+    this._i = 0;
+
+    /**
+    * @property {number} _diff - Internal cache var.
+    * @private
+    */
+    this._diff = 0;
+
+    /**
+    * @property {number} _newTick - Internal cache var.
+    * @private
+    */
+    this._newTick = 0;
+
+};
+
+/**
+* Number of milliseconds in a minute.
+* @constant
+* @type {integer}
+*/
+Phaser.Timer.MINUTE = 60000;
+
+/**
+* Number of milliseconds in a second.
+* @constant
+* @type {integer}
+*/
+Phaser.Timer.SECOND = 1000;
+
+/**
+* Number of milliseconds in half a second.
+* @constant
+* @type {integer}
+*/
+Phaser.Timer.HALF = 500;
+
+/**
+* Number of milliseconds in a quarter of a second.
+* @constant
+* @type {integer}
+*/
+Phaser.Timer.QUARTER = 250;
+
+Phaser.Timer.prototype = {
+
+    /**
+    * Creates a new TimerEvent on this Timer.
+    *
+    * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#add}, or {@link Phaser.Timer#add} methods to create a new event.
+    *
+    * @method Phaser.Timer#create
+    * @private
+    * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback. This value should be an integer, not a float. Math.round() is applied to it by this method.
+    * @param {boolean} loop - Should the event loop or not?
+    * @param {number} repeatCount - The number of times the event will repeat.
+    * @param {function} callback - The callback that will be called when the Timer event occurs.
+    * @param {object} callbackContext - The context in which the callback will be called.
+    * @param {any[]} arguments - The values to be sent to your callback function when it is called.
+    * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
+    */
+    create: function (delay, loop, repeatCount, callback, callbackContext, args) {
+
+        delay = Math.round(delay);
+
+        var tick = delay;
+
+        if (this._now === 0)
+        {
+            tick += this.game.time.time;
+        }
+        else
+        {
+            tick += this._now;
+        }
+
+        var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args);
+
+        this.events.push(event);
+
+        this.order();
+
+        this.expired = false;
+
+        return event;
+
+    },
+
+    /**
+    * Adds a new Event to this Timer.
+    *
+    * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
+    * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
+    *
+    * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
+    *
+    * @method Phaser.Timer#add
+    * @param {number} delay - The number of milliseconds that should elapse before the callback is invoked.
+    * @param {function} callback - The callback that will be called when the Timer event occurs.
+    * @param {object} callbackContext - The context in which the callback will be called.
+    * @param {...*} arguments - Additional arguments that will be supplied to the callback.
+    * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
+    */
+    add: function (delay, callback, callbackContext) {
+
+        return this.create(delay, false, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
+
+    },
+
+    /**
+    * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations.
+    *
+    * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
+    * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
+    *
+    * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
+    *
+    * @method Phaser.Timer#repeat
+    * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
+    * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total.
+    * @param {function} callback - The callback that will be called when the Timer event occurs.
+    * @param {object} callbackContext - The context in which the callback will be called.
+    * @param {...*} arguments - Additional arguments that will be supplied to the callback.
+    * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
+    */
+    repeat: function (delay, repeatCount, callback, callbackContext) {
+
+        return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.splice.call(arguments, 4));
+
+    },
+
+    /**
+    * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped.
+    *
+    * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
+    * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
+    *
+    * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
+    *
+    * @method Phaser.Timer#loop
+    * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
+    * @param {function} callback - The callback that will be called when the Timer event occurs.
+    * @param {object} callbackContext - The context in which the callback will be called.
+    * @param {...*} arguments - Additional arguments that will be supplied to the callback.
+    * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
+    */
+    loop: function (delay, callback, callbackContext) {
+
+        return this.create(delay, true, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
+
+    },
+
+    /**
+    * Starts this Timer running.
+    * @method Phaser.Timer#start
+    * @param {number} [delay=0] - The number of milliseconds that should elapse before the Timer will start.
+    */
+    start: function (delay) {
+
+        if (this.running)
+        {
+            return;
+        }
+
+        this._started = this.game.time.time + (delay || 0);
+
+        this.running = true;
+
+        for (var i = 0; i < this.events.length; i++)
+        {
+            this.events[i].tick = this.events[i].delay + this._started;
+        }
+
+    },
+
+    /**
+    * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true.
+    * @method Phaser.Timer#stop
+    * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain.
+    */
+    stop: function (clearEvents) {
+
+        this.running = false;
+
+        if (clearEvents === undefined) { clearEvents = true; }
+
+        if (clearEvents)
+        {
+            this.events.length = 0;
+        }
+
+    },
+
+    /**
+    * Removes a pending TimerEvent from the queue.
+    * @param {Phaser.TimerEvent} event - The event to remove from the queue.
+    * @method Phaser.Timer#remove
+    */
+    remove: function (event) {
+
+        for (var i = 0; i < this.events.length; i++)
+        {
+            if (this.events[i] === event)
+            {
+                this.events[i].pendingDelete = true;
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Orders the events on this Timer so they are in tick order.
+    * This is called automatically when new events are created.
+    * @method Phaser.Timer#order
+    * @protected
+    */
+    order: function () {
+
+        if (this.events.length > 0)
+        {
+            //  Sort the events so the one with the lowest tick is first
+            this.events.sort(this.sortHandler);
+
+            this.nextTick = this.events[0].tick;
+        }
+
+    },
+
+    /**
+    * Sort handler used by Phaser.Timer.order.
+    * @method Phaser.Timer#sortHandler
+    * @private
+    */
+    sortHandler: function (a, b) {
+
+        if (a.tick < b.tick)
+        {
+            return -1;
+        }
+        else if (a.tick > b.tick)
+        {
+            return 1;
+        }
+
+        return 0;
+
+    },
+
+    /**
+    * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values.
+    *
+    * @method Phaser.Timer#clearPendingEvents
+    * @protected
+    */
+    clearPendingEvents: function () {
+
+        this._i = this.events.length;
+
+        while (this._i--)
+        {
+            if (this.events[this._i].pendingDelete)
+            {
+                this.events.splice(this._i, 1);
+            }
+        }
+
+        this._len = this.events.length;
+        this._i = 0;
+
+    },
+
+    /**
+    * The main Timer update event, called automatically by Phaser.Time.update.
+    *
+    * @method Phaser.Timer#update
+    * @protected
+    * @param {number} time - The time from the core game clock.
+    * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed.
+    */
+    update: function (time) {
+
+        if (this.paused)
+        {
+            return true;
+        }
+
+        this.elapsed = time - this._now;
+        this._now = time;
+
+        //  spike-dislike
+        if (this.elapsed > this.timeCap)
+        {
+            //  For some reason the time between now and the last time the game was updated was larger than our timeCap.
+            //  This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause.
+            //  In this case we need to adjust the TimerEvents and nextTick.
+            this.adjustEvents(time - this.elapsed);
+        }
+
+        this._marked = 0;
+
+        //  Clears events marked for deletion and resets _len and _i to 0.
+        this.clearPendingEvents();
+
+        if (this.running && this._now >= this.nextTick && this._len > 0)
+        {
+            while (this._i < this._len && this.running)
+            {
+                if (this._now >= this.events[this._i].tick && !this.events[this._i].pendingDelete)
+                {
+                    //  (now + delay) - (time difference from last tick to now)
+                    this._newTick = (this._now + this.events[this._i].delay) - (this._now - this.events[this._i].tick);
+
+                    if (this._newTick < 0)
+                    {
+                        this._newTick = this._now + this.events[this._i].delay;
+                    }
+
+                    if (this.events[this._i].loop === true)
+                    {
+                        this.events[this._i].tick = this._newTick;
+                        this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
+                    }
+                    else if (this.events[this._i].repeatCount > 0)
+                    {
+                        this.events[this._i].repeatCount--;
+                        this.events[this._i].tick = this._newTick;
+                        this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
+                    }
+                    else
+                    {
+                        this._marked++;
+                        this.events[this._i].pendingDelete = true;
+                        this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
+                    }
+
+                    this._i++;
+                }
+                else
+                {
+                    break;
+                }
+            }
+
+            //  Are there any events left?
+            if (this.events.length > this._marked)
+            {
+                this.order();
+            }
+            else
+            {
+                this.expired = true;
+                this.onComplete.dispatch(this);
+            }
+        }
+
+        if (this.expired && this.autoDestroy)
+        {
+            return false;
+        }
+        else
+        {
+            return true;
+        }
+
+    },
+
+    /**
+    * Pauses the Timer and all events in the queue.
+    * @method Phaser.Timer#pause
+    */
+    pause: function () {
+
+        if (!this.running)
+        {
+            return;
+        }
+
+        this._codePaused = true;
+
+        if (this.paused)
+        {
+            return;
+        }
+
+        this._pauseStarted = this.game.time.time;
+
+        this.paused = true;
+
+    },
+
+    /**
+    * Internal pause/resume control - user code should use Timer.pause instead.
+    * @method Phaser.Timer#_pause
+    * @private
+    */
+    _pause: function () {
+
+        if (this.paused || !this.running)
+        {
+            return;
+        }
+
+        this._pauseStarted = this.game.time.time;
+
+        this.paused = true;
+
+    },
+
+    /**
+    * Adjusts the time of all pending events and the nextTick by the given baseTime.
+    *
+    * @method Phaser.Timer#adjustEvents
+    * @protected
+    */
+    adjustEvents: function (baseTime) {
+
+        for (var i = 0; i < this.events.length; i++)
+        {
+            if (!this.events[i].pendingDelete)
+            {
+                //  Work out how long there would have been from when the game paused until the events next tick
+                var t = this.events[i].tick - baseTime;
+
+                if (t < 0)
+                {
+                    t = 0;
+                }
+
+                //  Add the difference on to the time now
+                this.events[i].tick = this._now + t;
+            }
+        }
+
+        var d = this.nextTick - baseTime;
+
+        if (d < 0)
+        {
+            this.nextTick = this._now;
+        }
+        else
+        {
+            this.nextTick = this._now + d;
+        }
+
+    },
+
+    /**
+    * Resumes the Timer and updates all pending events.
+    *
+    * @method Phaser.Timer#resume
+    */
+    resume: function () {
+
+        if (!this.paused)
+        {
+            return;
+        }
+
+        var now = this.game.time.time;
+        this._pauseTotal += now - this._now;
+        this._now = now;
+
+        this.adjustEvents(this._pauseStarted);
+
+        this.paused = false;
+        this._codePaused = false;
+
+    },
+
+    /**
+    * Internal pause/resume control - user code should use Timer.resume instead.
+    * @method Phaser.Timer#_resume
+    * @private
+    */
+    _resume: function () {
+
+        if (this._codePaused)
+        {
+            return;
+        }
+        else
+        {
+            this.resume();
+        }
+
+    },
+
+    /**
+    * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running.    
+    * The onComplete callbacks won't be called.
+    *
+    * @method Phaser.Timer#removeAll
+    */
+    removeAll: function () {
+
+        this.onComplete.removeAll();
+        this.events.length = 0;
+        this._len = 0;
+        this._i = 0;
+
+    },
+
+    /**
+    * Destroys this Timer. Any pending Events are not dispatched.
+    * The onComplete callbacks won't be called.
+    *
+    * @method Phaser.Timer#destroy
+    */
+    destroy: function () {
+
+        this.onComplete.removeAll();
+        this.running = false;
+        this.events = [];
+        this._len = 0;
+        this._i = 0;
+
+    }
+
+};
+
+/**
+* @name Phaser.Timer#next
+* @property {number} next - The time at which the next event will occur.
+* @readonly
+*/
+Object.defineProperty(Phaser.Timer.prototype, "next", {
+
+    get: function () {
+        return this.nextTick;
+    }
+
+});
+
+/**
+* @name Phaser.Timer#duration
+* @property {number} duration - The duration in ms remaining until the next event will occur.
+* @readonly
+*/
+Object.defineProperty(Phaser.Timer.prototype, "duration", {
+
+    get: function () {
+
+        if (this.running && this.nextTick > this._now)
+        {
+            return this.nextTick - this._now;
+        }
+        else
+        {
+            return 0;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Timer#length
+* @property {number} length - The number of pending events in the queue.
+* @readonly
+*/
+Object.defineProperty(Phaser.Timer.prototype, "length", {
+
+    get: function () {
+        return this.events.length;
+    }
+
+});
+
+/**
+* @name Phaser.Timer#ms
+* @property {number} ms - The duration in milliseconds that this Timer has been running for.
+* @readonly
+*/
+Object.defineProperty(Phaser.Timer.prototype, "ms", {
+
+    get: function () {
+
+        if (this.running)
+        {
+            return this._now - this._started - this._pauseTotal;
+        }
+        else
+        {
+            return 0;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Timer#seconds
+* @property {number} seconds - The duration in seconds that this Timer has been running for.
+* @readonly
+*/
+Object.defineProperty(Phaser.Timer.prototype, "seconds", {
+
+    get: function () {
+
+        if (this.running)
+        {
+            return this.ms * 0.001;
+        }
+        else
+        {
+            return 0;
+        }
+
+    }
+
+});
+
+Phaser.Timer.prototype.constructor = Phaser.Timer;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A TimerEvent is a single event that is processed by a Phaser.Timer.
+*
+* It consists of a delay, which is a value in milliseconds after which the event will fire.
+* When the event fires it calls a specific callback with the specified arguments.
+*
+* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#add}, or {@link Phaser.Timer#add} methods to create a new event.
+*
+* @class Phaser.TimerEvent
+* @constructor
+* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
+* @param {number} delay - The delay in ms at which this TimerEvent fires.
+* @param {number} tick - The tick is the next game clock time that this event will fire at.
+* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times.
+* @param {boolean} loop - True if this TimerEvent loops, otherwise false.
+* @param {function} callback - The callback that will be called when the TimerEvent occurs.
+* @param {object} callbackContext - The context in which the callback will be called.
+* @param {any[]} arguments - Additional arguments to be passed to the callback.
+*/
+Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) {
+
+    /**
+    * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
+    * @protected
+    * @readonly
+    */
+    this.timer = timer;
+
+    /**
+    * @property {number} delay - The delay in ms at which this TimerEvent fires.
+    */
+    this.delay = delay;
+
+    /**
+    * @property {number} tick - The tick is the next game clock time that this event will fire at.
+    */
+    this.tick = tick;
+
+    /**
+    * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times.
+    */
+    this.repeatCount = repeatCount - 1;
+
+    /**
+    * @property {boolean} loop - True if this TimerEvent loops, otherwise false.
+    */
+    this.loop = loop;
+
+    /**
+    * @property {function} callback - The callback that will be called when the TimerEvent occurs.
+    */
+    this.callback = callback;
+
+    /**
+    * @property {object} callbackContext - The context in which the callback will be called.
+    */
+    this.callbackContext = callbackContext;
+
+    /**
+    * @property {any[]} arguments - Additional arguments to be passed to the callback.
+    */
+    this.args = args;
+
+    /**
+    * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion.
+    * @protected
+    */
+    this.pendingDelete = false;
+
+};
+
+Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Animation Manager is used to add, play and update Phaser Animations.
+* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
+*
+* @class Phaser.AnimationManager
+* @constructor
+* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
+*/
+Phaser.AnimationManager = function (sprite) {
+
+    /**
+    * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
+    */
+    this.sprite = sprite;
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = sprite.game;
+
+    /**
+    * The currently displayed Frame of animation, if any.
+    * This property is only set once an Animation starts playing. Until that point it remains set as `null`.
+    * 
+    * @property {Phaser.Frame} currentFrame
+    * @default
+    */
+    this.currentFrame = null;
+
+    /**
+    * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any.
+    * @default
+    */
+    this.currentAnim = null;
+
+    /**
+    * @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
+    * @default
+    */
+    this.updateIfVisible = true;
+
+    /**
+    * @property {boolean} isLoaded - Set to true once animation data has been loaded.
+    * @default
+    */
+    this.isLoaded = false;
+
+    /**
+    * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
+    * @private
+    * @default
+    */
+    this._frameData = null;
+
+    /**
+    * @property {object} _anims - An internal object that stores all of the Animation instances.
+    * @private
+    */
+    this._anims = {};
+
+    /**
+    * @property {object} _outputFrames - An internal object to help avoid gc.
+    * @private
+    */
+    this._outputFrames = [];
+
+};
+
+Phaser.AnimationManager.prototype = {
+
+    /**
+    * Loads FrameData into the internal temporary vars and resets the frame index to zero.
+    * This is called automatically when a new Sprite is created.
+    *
+    * @method Phaser.AnimationManager#loadFrameData
+    * @private
+    * @param {Phaser.FrameData} frameData - The FrameData set to load.
+    * @param {string|number} frame - The frame to default to.
+    * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
+    */
+    loadFrameData: function (frameData, frame) {
+
+        if (frameData === undefined)
+        {
+            return false;
+        }
+
+        if (this.isLoaded)
+        {
+            //   We need to update the frameData that the animations are using
+            for (var anim in this._anims)
+            {
+                this._anims[anim].updateFrameData(frameData);
+            }
+        }
+
+        this._frameData = frameData;
+
+        if (frame === undefined || frame === null)
+        {
+            this.frame = 0;
+        }
+        else
+        {
+            if (typeof frame === 'string')
+            {
+                this.frameName = frame;
+            }
+            else
+            {
+                this.frame = frame;
+            }
+        }
+
+        this.isLoaded = true;
+
+        return true;
+    },
+
+    /**
+    * Loads FrameData into the internal temporary vars and resets the frame index to zero.
+    * This is called automatically when a new Sprite is created.
+    *
+    * @method Phaser.AnimationManager#copyFrameData
+    * @private
+    * @param {Phaser.FrameData} frameData - The FrameData set to load.
+    * @param {string|number} frame - The frame to default to.
+    * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
+    */
+    copyFrameData: function (frameData, frame) {
+
+        this._frameData = frameData.clone();
+
+        if (this.isLoaded)
+        {
+            //   We need to update the frameData that the animations are using
+            for (var anim in this._anims)
+            {
+                this._anims[anim].updateFrameData(this._frameData);
+            }
+        }
+
+        if (frame === undefined || frame === null)
+        {
+            this.frame = 0;
+        }
+        else
+        {
+            if (typeof frame === 'string')
+            {
+                this.frameName = frame;
+            }
+            else
+            {
+                this.frame = frame;
+            }
+        }
+
+        this.isLoaded = true;
+
+        return true;
+    },
+
+    /**
+    * Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
+    * Animations added in this way are played back with the play function.
+    *
+    * @method Phaser.AnimationManager#add
+    * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
+    * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used.
+    * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
+    * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
+    * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
+    * @return {Phaser.Animation} The Animation object that was created.
+    */
+    add: function (name, frames, frameRate, loop, useNumericIndex) {
+
+        frames = frames || [];
+        frameRate = frameRate || 60;
+
+        if (loop === undefined) { loop = false; }
+
+        //  If they didn't set the useNumericIndex then let's at least try and guess it
+        if (useNumericIndex === undefined)
+        {
+            if (frames && typeof frames[0] === 'number')
+            {
+                useNumericIndex = true;
+            }
+            else
+            {
+                useNumericIndex = false;
+            }
+        }
+
+        this._outputFrames = [];
+
+        this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
+
+        this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
+
+        this.currentAnim = this._anims[name];
+
+        //  This shouldn't be set until the Animation is played, surely?
+        // this.currentFrame = this.currentAnim.currentFrame;
+
+        if (this.sprite.tilingTexture)
+        {
+            this.sprite.refreshTexture = true;
+        }
+
+        return this._anims[name];
+
+    },
+
+    /**
+    * Check whether the frames in the given array are valid and exist.
+    *
+    * @method Phaser.AnimationManager#validateFrames
+    * @param {Array} frames - An array of frames to be validated.
+    * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
+    * @return {boolean} True if all given Frames are valid, otherwise false.
+    */
+    validateFrames: function (frames, useNumericIndex) {
+
+        if (useNumericIndex === undefined) { useNumericIndex = true; }
+
+        for (var i = 0; i < frames.length; i++)
+        {
+            if (useNumericIndex === true)
+            {
+                if (frames[i] > this._frameData.total)
+                {
+                    return false;
+                }
+            }
+            else
+            {
+                if (this._frameData.checkFrameName(frames[i]) === false)
+                {
+                    return false;
+                }
+            }
+        }
+
+        return true;
+
+    },
+
+    /**
+    * Play an animation based on the given key. The animation should previously have been added via `animations.add`
+    * 
+    * If the requested animation is already playing this request will be ignored. 
+    * If you need to reset an already running animation do so directly on the Animation object itself.
+    *
+    * @method Phaser.AnimationManager#play
+    * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
+    * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
+    * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
+    * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
+    * @return {Phaser.Animation} A reference to playing Animation instance.
+    */
+    play: function (name, frameRate, loop, killOnComplete) {
+
+        if (this._anims[name])
+        {
+            if (this.currentAnim === this._anims[name])
+            {
+                if (this.currentAnim.isPlaying === false)
+                {
+                    this.currentAnim.paused = false;
+                    return this.currentAnim.play(frameRate, loop, killOnComplete);
+                }
+
+                return this.currentAnim;
+            }
+            else
+            {
+                if (this.currentAnim && this.currentAnim.isPlaying)
+                {
+                    this.currentAnim.stop();
+                }
+
+                this.currentAnim = this._anims[name];
+                this.currentAnim.paused = false;
+                this.currentFrame = this.currentAnim.currentFrame;
+                return this.currentAnim.play(frameRate, loop, killOnComplete);
+            }
+        }
+
+    },
+
+    /**
+    * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
+    * The currentAnim property of the AnimationManager is automatically set to the animation given.
+    *
+    * @method Phaser.AnimationManager#stop
+    * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped.
+    * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false)
+    */
+    stop: function (name, resetFrame) {
+
+        if (resetFrame === undefined) { resetFrame = false; }
+
+        if (typeof name === 'string')
+        {
+            if (this._anims[name])
+            {
+                this.currentAnim = this._anims[name];
+                this.currentAnim.stop(resetFrame);
+            }
+        }
+        else
+        {
+            if (this.currentAnim)
+            {
+                this.currentAnim.stop(resetFrame);
+            }
+        }
+
+    },
+
+    /**
+    * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
+    *
+    * @method Phaser.AnimationManager#update
+    * @protected
+    * @return {boolean} True if a new animation frame has been set, otherwise false.
+    */
+    update: function () {
+
+        if (this.updateIfVisible && !this.sprite.visible)
+        {
+            return false;
+        }
+
+        if (this.currentAnim && this.currentAnim.update())
+        {
+            this.currentFrame = this.currentAnim.currentFrame;
+            return true;
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Advances by the given number of frames in the current animation, taking the loop value into consideration.
+    *
+    * @method Phaser.AnimationManager#next
+    * @param {number} [quantity=1] - The number of frames to advance.
+    */
+    next: function (quantity) {
+
+        if (this.currentAnim)
+        {
+            this.currentAnim.next(quantity);
+            this.currentFrame = this.currentAnim.currentFrame;
+        }
+
+    },
+
+    /**
+    * Moves backwards the given number of frames in the current animation, taking the loop value into consideration.
+    *
+    * @method Phaser.AnimationManager#previous
+    * @param {number} [quantity=1] - The number of frames to move back.
+    */
+    previous: function (quantity) {
+
+        if (this.currentAnim)
+        {
+            this.currentAnim.previous(quantity);
+            this.currentFrame = this.currentAnim.currentFrame;
+        }
+
+    },
+
+    /**
+    * Returns an animation that was previously added by name.
+    *
+    * @method Phaser.AnimationManager#getAnimation
+    * @param {string} name - The name of the animation to be returned, e.g. "fire".
+    * @return {Phaser.Animation} The Animation instance, if found, otherwise null.
+    */
+    getAnimation: function (name) {
+
+        if (typeof name === 'string')
+        {
+            if (this._anims[name])
+            {
+                return this._anims[name];
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Refreshes the current frame data back to the parent Sprite and also resets the texture data.
+    *
+    * @method Phaser.AnimationManager#refreshFrame
+    */
+    refreshFrame: function () {
+
+        //  TODO
+        this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
+
+    },
+
+    /**
+    * Destroys all references this AnimationManager contains.
+    * Iterates through the list of animations stored in this manager and calls destroy on each of them.
+    *
+    * @method Phaser.AnimationManager#destroy
+    */
+    destroy: function () {
+
+        var anim = null;
+
+        for (var anim in this._anims)
+        {
+            if (this._anims.hasOwnProperty(anim))
+            {
+                this._anims[anim].destroy();
+            }
+        }
+
+        this._anims = {};
+        this._outputFrames = [];
+        this._frameData = null;
+        this.currentAnim = null;
+        this.currentFrame = null;
+        this.sprite = null;
+        this.game = null;
+
+    }
+
+};
+
+Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager;
+
+/**
+* @name Phaser.AnimationManager#frameData
+* @property {Phaser.FrameData} frameData - The current animations FrameData.
+* @readonly
+*/
+Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
+
+    get: function () {
+        return this._frameData;
+    }
+
+});
+
+/**
+* @name Phaser.AnimationManager#frameTotal
+* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
+* @readonly
+*/
+Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
+
+    get: function () {
+
+        return this._frameData.total;
+    }
+
+});
+
+/**
+* @name Phaser.AnimationManager#paused
+* @property {boolean} paused - Gets and sets the paused state of the current animation.
+*/
+Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
+
+    get: function () {
+
+        return this.currentAnim.isPaused;
+
+    },
+
+    set: function (value) {
+
+        this.currentAnim.paused = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.AnimationManager#name
+* @property {string} name - Gets the current animation name, if set.
+*/
+Object.defineProperty(Phaser.AnimationManager.prototype, 'name', {
+
+    get: function () {
+
+        if (this.currentAnim)
+        {
+            return this.currentAnim.name;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.AnimationManager#frame
+* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
+*/
+Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
+
+    get: function () {
+
+        if (this.currentFrame)
+        {
+            return this.currentFrame.index;
+        }
+
+    },
+
+    set: function (value) {
+
+        if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
+        {
+            this.currentFrame = this._frameData.getFrame(value);
+
+            if (this.currentFrame)
+            {
+                this.sprite.setFrame(this.currentFrame);
+            }
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.AnimationManager#frameName
+* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
+*/
+Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
+
+    get: function () {
+
+        if (this.currentFrame)
+        {
+            return this.currentFrame.name;
+        }
+
+    },
+
+    set: function (value) {
+
+        if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
+        {
+            this.currentFrame = this._frameData.getFrameByName(value);
+
+            if (this.currentFrame)
+            {
+                this._frameIndex = this.currentFrame.index;
+
+                this.sprite.setFrame(this.currentFrame);
+            }
+        }
+        else
+        {
+            console.warn('Cannot set frameName: ' + value);
+        }
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* An Animation instance contains a single animation and the controls to play it.
+* 
+* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
+*
+* @class Phaser.Animation
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
+* @param {string} name - The unique name for this animation, used in playback commands.
+* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
+* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order.
+* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
+* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
+* @param {boolean} loop - Should this animation loop when it reaches the end or play through once.
+*/
+Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) {
+
+    if (loop === undefined) { loop = false; }
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
+    * @private
+    */
+    this._parent = parent;
+
+    /**
+    * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
+    * @private
+    */
+    this._frameData = frameData;
+
+    /**
+    * @property {string} name - The user defined name given to this Animation.
+    */
+    this.name = name;
+
+    /**
+    * @property {array} _frames
+    * @private
+    */
+    this._frames = [];
+    this._frames = this._frames.concat(frames);
+
+    /**
+    * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate.
+    */
+    this.delay = 1000 / frameRate;
+
+    /**
+    * @property {boolean} loop - The loop state of the Animation.
+    */
+    this.loop = loop;
+
+    /**
+    * @property {number} loopCount - The number of times the animation has looped since it was last started.
+    */
+    this.loopCount = 0;
+
+    /**
+    * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
+    * @default
+    */
+    this.killOnComplete = false;
+
+    /**
+    * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
+    * @default
+    */
+    this.isFinished = false;
+
+    /**
+    * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
+    * @default
+    */
+    this.isPlaying = false;
+
+    /**
+    * @property {boolean} isPaused - The paused state of the Animation.
+    * @default
+    */
+    this.isPaused = false;
+
+    /**
+    * @property {boolean} _pauseStartTime - The time the animation paused.
+    * @private
+    * @default
+    */
+    this._pauseStartTime = 0;
+
+    /**
+    * @property {number} _frameIndex
+    * @private
+    * @default
+    */
+    this._frameIndex = 0;
+
+    /**
+    * @property {number} _frameDiff
+    * @private
+    * @default
+    */
+    this._frameDiff = 0;
+
+    /**
+    * @property {number} _frameSkip
+    * @private
+    * @default
+    */
+    this._frameSkip = 1;
+
+    /**
+    * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
+    */
+    this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
+
+    /**
+    * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
+    */
+    this.onStart = new Phaser.Signal();
+
+    /**
+    * This event is dispatched when the Animation changes frame. 
+    * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`.
+    * @property {Phaser.Signal|null} onUpdate
+    * @default
+    */
+    this.onUpdate = null;
+
+    /**
+    * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onAnimationLoop instead.
+    */
+    this.onComplete = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
+    */
+    this.onLoop = new Phaser.Signal();
+
+    //  Set-up some event listeners
+    this.game.onPause.add(this.onPause, this);
+    this.game.onResume.add(this.onResume, this);
+
+};
+
+Phaser.Animation.prototype = {
+
+    /**
+    * Plays this animation.
+    *
+    * @method Phaser.Animation#play
+    * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
+    * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
+    * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
+    * @return {Phaser.Animation} - A reference to this Animation instance.
+    */
+    play: function (frameRate, loop, killOnComplete) {
+
+        if (typeof frameRate === 'number')
+        {
+            //  If they set a new frame rate then use it, otherwise use the one set on creation
+            this.delay = 1000 / frameRate;
+        }
+
+        if (typeof loop === 'boolean')
+        {
+            //  If they set a new loop value then use it, otherwise use the one set on creation
+            this.loop = loop;
+        }
+
+        if (typeof killOnComplete !== 'undefined')
+        {
+            //  Remove the parent sprite once the animation has finished?
+            this.killOnComplete = killOnComplete;
+        }
+
+        this.isPlaying = true;
+        this.isFinished = false;
+        this.paused = false;
+        this.loopCount = 0;
+
+        this._timeLastFrame = this.game.time.time;
+        this._timeNextFrame = this.game.time.time + this.delay;
+
+        this._frameIndex = 0;
+        this.updateCurrentFrame(false, true);
+
+        this._parent.events.onAnimationStart$dispatch(this._parent, this);
+
+        this.onStart.dispatch(this._parent, this);
+
+        this._parent.animations.currentAnim = this;
+        this._parent.animations.currentFrame = this.currentFrame;
+
+        return this;
+
+    },
+
+    /**
+    * Sets this animation back to the first frame and restarts the animation.
+    *
+    * @method Phaser.Animation#restart
+    */
+    restart: function () {
+
+        this.isPlaying = true;
+        this.isFinished = false;
+        this.paused = false;
+        this.loopCount = 0;
+
+        this._timeLastFrame = this.game.time.time;
+        this._timeNextFrame = this.game.time.time + this.delay;
+
+        this._frameIndex = 0;
+
+        this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
+
+        this._parent.setFrame(this.currentFrame);
+
+        this._parent.animations.currentAnim = this;
+        this._parent.animations.currentFrame = this.currentFrame;
+
+        this.onStart.dispatch(this._parent, this);
+
+    },
+
+    /**
+    * Sets this animations playback to a given frame with the given ID.
+    *
+    * @method Phaser.Animation#setFrame
+    * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index.
+    * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation.
+    */
+    setFrame: function(frameId, useLocalFrameIndex) {
+
+        var frameIndex;
+
+        if (useLocalFrameIndex === undefined)
+        {
+            useLocalFrameIndex = false;
+        }
+
+        //  Find the index to the desired frame.
+        if (typeof frameId === "string")
+        {
+            for (var i = 0; i < this._frames.length; i++)
+            {
+                if (this._frameData.getFrame(this._frames[i]).name === frameId)
+                {
+                    frameIndex = i;
+                }
+            }
+        }
+        else if (typeof frameId === "number")
+        {
+            if (useLocalFrameIndex)
+            {
+                frameIndex = frameId;
+            }
+            else
+            {
+                for (var i = 0; i < this._frames.length; i++)
+                {
+                    if (this._frames[i] === frameIndex)
+                    {
+                        frameIndex = i;
+                    }
+                }
+            }
+        }
+
+        if (frameIndex)
+        {
+            //  Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update.
+            this._frameIndex = frameIndex - 1;
+
+            //  Make the animation update at next update
+            this._timeNextFrame = this.game.time.time;
+
+            this.update();
+        }
+
+    },
+
+    /**
+    * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation.
+    * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
+    *
+    * @method Phaser.Animation#stop
+    * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
+    * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
+    */
+    stop: function (resetFrame, dispatchComplete) {
+
+        if (resetFrame === undefined) { resetFrame = false; }
+        if (dispatchComplete === undefined) { dispatchComplete = false; }
+
+        this.isPlaying = false;
+        this.isFinished = true;
+        this.paused = false;
+
+        if (resetFrame)
+        {
+            this.currentFrame = this._frameData.getFrame(this._frames[0]);
+            this._parent.setFrame(this.currentFrame);
+        }
+
+        if (dispatchComplete)
+        {
+            this._parent.events.onAnimationComplete$dispatch(this._parent, this);
+            this.onComplete.dispatch(this._parent, this);
+        }
+
+    },
+
+    /**
+    * Called when the Game enters a paused state.
+    *
+    * @method Phaser.Animation#onPause
+    */
+    onPause: function () {
+
+        if (this.isPlaying)
+        {
+            this._frameDiff = this._timeNextFrame - this.game.time.time;
+        }
+
+    },
+
+    /**
+    * Called when the Game resumes from a paused state.
+    *
+    * @method Phaser.Animation#onResume
+    */
+    onResume: function () {
+
+        if (this.isPlaying)
+        {
+            this._timeNextFrame = this.game.time.time + this._frameDiff;
+        }
+
+    },
+
+    /**
+    * Updates this animation. Called automatically by the AnimationManager.
+    *
+    * @method Phaser.Animation#update
+    */
+    update: function () {
+
+        if (this.isPaused)
+        {
+            return false;
+        }
+
+        if (this.isPlaying && this.game.time.time >= this._timeNextFrame)
+        {
+            this._frameSkip = 1;
+
+            //  Lagging?
+            this._frameDiff = this.game.time.time - this._timeNextFrame;
+
+            this._timeLastFrame = this.game.time.time;
+
+            if (this._frameDiff > this.delay)
+            {
+                //  We need to skip a frame, work out how many
+                this._frameSkip = Math.floor(this._frameDiff / this.delay);
+                this._frameDiff -= (this._frameSkip * this.delay);
+            }
+
+            //  And what's left now?
+            this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff);
+
+            this._frameIndex += this._frameSkip;
+
+            if (this._frameIndex >= this._frames.length)
+            {
+                if (this.loop)
+                {
+                    // Update current state before event callback
+                    this._frameIndex %= this._frames.length;
+                    this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
+
+                    //  Instead of calling updateCurrentFrame we do it here instead
+                    if (this.currentFrame)
+                    {
+                        this._parent.setFrame(this.currentFrame);
+                    }
+
+                    this.loopCount++;
+                    this._parent.events.onAnimationLoop$dispatch(this._parent, this);
+                    this.onLoop.dispatch(this._parent, this);
+
+                    if (this.onUpdate)
+                    {
+                        this.onUpdate.dispatch(this, this.currentFrame);
+
+                        // False if the animation was destroyed from within a callback
+                        return !!this._frameData;
+                    }
+                    else
+                    {
+                        return true;
+                    }
+                }
+                else
+                {
+                    this.complete();
+                    return false;
+                }
+            }
+            else
+            {
+                return this.updateCurrentFrame(true);
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Changes the currentFrame per the _frameIndex, updates the display state,
+    * and triggers the update signal.
+    *
+    * Returns true if the current frame update was 'successful', false otherwise.
+    *
+    * @method Phaser.Animation#updateCurrentFrame
+    * @private
+    * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched.
+    * @param {boolean} fromPlay - Was this call made from the playing of a new animation?
+    * @return {boolean} True if the current frame was updated, otherwise false.
+    */
+    updateCurrentFrame: function (signalUpdate, fromPlay) {
+
+        if (fromPlay === undefined) { fromPlay = false; }
+
+        if (!this._frameData)
+        {
+            // The animation is already destroyed, probably from a callback
+            return false;
+        }
+            
+        //  Previous index
+        var idx = this.currentFrame.index;
+
+        this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
+
+        if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index)))
+        {
+            this._parent.setFrame(this.currentFrame);
+        }
+
+        if (this.onUpdate && signalUpdate)
+        {
+            this.onUpdate.dispatch(this, this.currentFrame);
+
+            // False if the animation was destroyed from within a callback
+            return !!this._frameData;
+        }
+        else
+        {
+            return true;
+        }
+
+    },
+
+    /**
+    * Advances by the given number of frames in the Animation, taking the loop value into consideration.
+    *
+    * @method Phaser.Animation#next
+    * @param {number} [quantity=1] - The number of frames to advance.
+    */
+    next: function (quantity) {
+
+        if (quantity === undefined) { quantity = 1; }
+
+        var frame = this._frameIndex + quantity;
+
+        if (frame >= this._frames.length)
+        {
+            if (this.loop)
+            {
+                frame %= this._frames.length;
+            }
+            else
+            {
+                frame = this._frames.length - 1;
+            }
+        }
+
+        if (frame !== this._frameIndex)
+        {
+            this._frameIndex = frame;
+            this.updateCurrentFrame(true);
+        }
+
+    },
+
+    /**
+    * Moves backwards the given number of frames in the Animation, taking the loop value into consideration.
+    *
+    * @method Phaser.Animation#previous
+    * @param {number} [quantity=1] - The number of frames to move back.
+    */
+    previous: function (quantity) {
+
+        if (quantity === undefined) { quantity = 1; }
+
+        var frame = this._frameIndex - quantity;
+
+        if (frame < 0)
+        {
+            if (this.loop)
+            {
+                frame = this._frames.length + frame;
+            }
+            else
+            {
+                frame++;
+            }
+        }
+
+        if (frame !== this._frameIndex)
+        {
+            this._frameIndex = frame;
+            this.updateCurrentFrame(true);
+        }
+
+    },
+
+    /**
+    * Changes the FrameData object this Animation is using.
+    *
+    * @method Phaser.Animation#updateFrameData
+    * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
+    */
+    updateFrameData: function (frameData) {
+
+        this._frameData = frameData;
+        this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null;
+
+    },
+
+    /**
+    * Cleans up this animation ready for deletion. Nulls all values and references.
+    *
+    * @method Phaser.Animation#destroy
+    */
+    destroy: function () {
+
+        if (!this._frameData)
+        {
+            // Already destroyed
+            return;
+        }
+
+        this.game.onPause.remove(this.onPause, this);
+        this.game.onResume.remove(this.onResume, this);
+
+        this.game = null;
+        this._parent = null;
+        this._frames = null;
+        this._frameData = null;
+        this.currentFrame = null;
+        this.isPlaying = false;
+
+        this.onStart.dispose();
+        this.onLoop.dispose();
+        this.onComplete.dispose();
+
+        if (this.onUpdate)
+        {
+            this.onUpdate.dispose();
+        }
+
+    },
+
+    /**
+    * Called internally when the animation finishes playback.
+    * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
+    *
+    * @method Phaser.Animation#complete
+    */
+    complete: function () {
+
+        this._frameIndex = this._frames.length - 1;
+        this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
+
+        this.isPlaying = false;
+        this.isFinished = true;
+        this.paused = false;
+
+        this._parent.events.onAnimationComplete$dispatch(this._parent, this);
+
+        this.onComplete.dispatch(this._parent, this);
+
+        if (this.killOnComplete)
+        {
+            this._parent.kill();
+        }
+
+    }
+
+};
+
+Phaser.Animation.prototype.constructor = Phaser.Animation;
+
+/**
+* @name Phaser.Animation#paused
+* @property {boolean} paused - Gets and sets the paused state of this Animation.
+*/
+Object.defineProperty(Phaser.Animation.prototype, 'paused', {
+
+    get: function () {
+
+        return this.isPaused;
+
+    },
+
+    set: function (value) {
+
+        this.isPaused = value;
+
+        if (value)
+        {
+            //  Paused
+            this._pauseStartTime = this.game.time.time;
+        }
+        else
+        {
+            //  Un-paused
+            if (this.isPlaying)
+            {
+                this._timeNextFrame = this.game.time.time + this.delay;
+            }
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Animation#frameTotal
+* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
+* @readonly
+*/
+Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
+
+    get: function () {
+        return this._frames.length;
+    }
+
+});
+
+/**
+* @name Phaser.Animation#frame
+* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
+*/
+Object.defineProperty(Phaser.Animation.prototype, 'frame', {
+
+    get: function () {
+
+        if (this.currentFrame !== null)
+        {
+            return this.currentFrame.index;
+        }
+        else
+        {
+            return this._frameIndex;
+        }
+
+    },
+
+    set: function (value) {
+
+        this.currentFrame = this._frameData.getFrame(this._frames[value]);
+
+        if (this.currentFrame !== null)
+        {
+            this._frameIndex = value;
+            this._parent.setFrame(this.currentFrame);
+
+            if (this.onUpdate)
+            {
+                this.onUpdate.dispatch(this, this.currentFrame);
+            }
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Animation#speed
+* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Minimum value is 1.
+*/
+Object.defineProperty(Phaser.Animation.prototype, 'speed', {
+
+    get: function () {
+
+        return Math.round(1000 / this.delay);
+
+    },
+
+    set: function (value) {
+
+        if (value >= 1)
+        {
+            this.delay = 1000 / value;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Animation#enableUpdate
+* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame.
+*/
+Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', {
+
+    get: function () {
+
+        return (this.onUpdate !== null);
+
+    },
+
+    set: function (value) {
+
+        if (value && this.onUpdate === null)
+        {
+            this.onUpdate = new Phaser.Signal();
+        }
+        else if (!value && this.onUpdate !== null)
+        {
+            this.onUpdate.dispose();
+            this.onUpdate = null;
+        }
+
+    }
+
+});
+
+/**
+* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
+* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
+* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
+*
+* @method Phaser.Animation.generateFrameNames
+* @static
+* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
+* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
+* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
+* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
+* @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
+* @return {string[]} An array of framenames.
+*/
+Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
+
+    if (suffix === undefined) { suffix = ''; }
+
+    var output = [];
+    var frame = '';
+
+    if (start < stop)
+    {
+        for (var i = start; i <= stop; i++)
+        {
+            if (typeof zeroPad === 'number')
+            {
+                //  str, len, pad, dir
+                frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
+            }
+            else
+            {
+                frame = i.toString();
+            }
+
+            frame = prefix + frame + suffix;
+
+            output.push(frame);
+        }
+    }
+    else
+    {
+        for (var i = start; i >= stop; i--)
+        {
+            if (typeof zeroPad === 'number')
+            {
+                //  str, len, pad, dir
+                frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
+            }
+            else
+            {
+                frame = i.toString();
+            }
+
+            frame = prefix + frame + suffix;
+
+            output.push(frame);
+        }
+    }
+
+    return output;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Frame is a single frame of an animation and is part of a FrameData collection.
+*
+* @class Phaser.Frame
+* @constructor
+* @param {number} index - The index of this Frame within the FrameData set it is being added to.
+* @param {number} x - X position of the frame within the texture image.
+* @param {number} y - Y position of the frame within the texture image.
+* @param {number} width - Width of the frame within the texture image.
+* @param {number} height - Height of the frame within the texture image.
+* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
+*/
+Phaser.Frame = function (index, x, y, width, height, name) {
+
+    /**
+    * @property {number} index - The index of this Frame within the FrameData set it is being added to.
+    */
+    this.index = index;
+
+    /**
+    * @property {number} x - X position within the image to cut from.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - Y position within the image to cut from.
+    */
+    this.y = y;
+
+    /**
+    * @property {number} width - Width of the frame.
+    */
+    this.width = width;
+
+    /**
+    * @property {number} height - Height of the frame.
+    */
+    this.height = height;
+
+    /**
+    * @property {string} name - Useful for Texture Atlas files (is set to the filename value).
+    */
+    this.name = name;
+
+    /**
+    * @property {number} centerX - Center X position within the image to cut from.
+    */
+    this.centerX = Math.floor(width / 2);
+
+    /**
+    * @property {number} centerY - Center Y position within the image to cut from.
+    */
+    this.centerY = Math.floor(height / 2);
+
+    /**
+    * @property {number} distance - The distance from the top left to the bottom-right of this Frame.
+    */
+    this.distance = Phaser.Math.distance(0, 0, width, height);
+
+    /**
+    * @property {boolean} rotated - Rotated? (not yet implemented)
+    * @default
+    */
+    this.rotated = false;
+
+    /**
+    * @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
+    * @default 'cw'
+    */
+    this.rotationDirection = 'cw';
+
+    /**
+    * @property {boolean} trimmed - Was it trimmed when packed?
+    * @default
+    */
+    this.trimmed = false;
+
+    /**
+    * @property {number} sourceSizeW - Width of the original sprite before it was trimmed.
+    */
+    this.sourceSizeW = width;
+
+    /**
+    * @property {number} sourceSizeH - Height of the original sprite before it was trimmed.
+    */
+    this.sourceSizeH = height;
+
+    /**
+    * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
+    * @default
+    */
+    this.spriteSourceSizeX = 0;
+
+    /**
+    * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
+    * @default
+    */
+    this.spriteSourceSizeY = 0;
+
+    /**
+    * @property {number} spriteSourceSizeW - Width of the trimmed sprite.
+    * @default
+    */
+    this.spriteSourceSizeW = 0;
+
+    /**
+    * @property {number} spriteSourceSizeH - Height of the trimmed sprite.
+    * @default
+    */
+    this.spriteSourceSizeH = 0;
+
+    /**
+    * @property {number} right - The right of the Frame (x + width).
+    */
+    this.right = this.x + this.width;
+
+    /**
+    * @property {number} bottom - The bottom of the frame (y + height).
+    */
+    this.bottom = this.y + this.height;
+
+};
+
+Phaser.Frame.prototype = {
+
+    /**
+    * Adjusts of all the Frame properties based on the given width and height values.
+    *
+    * @method Phaser.Frame#resize
+    * @param {integer} width - The new width of the Frame.
+    * @param {integer} height - The new height of the Frame.
+    */
+    resize: function (width, height) {
+
+        this.width = width;
+        this.height = height;
+        this.centerX = Math.floor(width / 2);
+        this.centerY = Math.floor(height / 2);
+        this.distance = Phaser.Math.distance(0, 0, width, height);
+        this.sourceSizeW = width;
+        this.sourceSizeH = height;
+        this.right = this.x + width;
+        this.bottom = this.y + height;
+
+    },
+
+    /**
+    * If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
+    *
+    * @method Phaser.Frame#setTrim
+    * @param {boolean} trimmed - If this frame was trimmed or not.
+    * @param {number} actualWidth - The width of the frame before being trimmed.
+    * @param {number} actualHeight - The height of the frame before being trimmed.
+    * @param {number} destX - The destination X position of the trimmed frame for display.
+    * @param {number} destY - The destination Y position of the trimmed frame for display.
+    * @param {number} destWidth - The destination width of the trimmed frame for display.
+    * @param {number} destHeight - The destination height of the trimmed frame for display.
+    */
+    setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
+
+        this.trimmed = trimmed;
+
+        if (trimmed)
+        {
+            this.sourceSizeW = actualWidth;
+            this.sourceSizeH = actualHeight;
+            this.centerX = Math.floor(actualWidth / 2);
+            this.centerY = Math.floor(actualHeight / 2);
+            this.spriteSourceSizeX = destX;
+            this.spriteSourceSizeY = destY;
+            this.spriteSourceSizeW = destWidth;
+            this.spriteSourceSizeH = destHeight;
+        }
+
+    },
+
+    /**
+     * Clones this Frame into a new Phaser.Frame object and returns it.
+     * Note that all properties are cloned, including the name, index and UUID.
+     *
+     * @method Phaser.Frame#clone
+     * @return {Phaser.Frame} An exact copy of this Frame object.
+     */
+    clone: function () {
+
+        var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name);
+
+        for (var prop in this)
+        {
+            if (this.hasOwnProperty(prop))
+            {
+                output[prop] = this[prop];
+            }
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Returns a Rectangle set to the dimensions of this Frame.
+    *
+    * @method Phaser.Frame#getRect
+    * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to.
+    * @return {Phaser.Rectangle} A rectangle.
+    */
+    getRect: function (out) {
+
+        if (out === undefined)
+        {
+            out = new Phaser.Rectangle(this.x, this.y, this.width, this.height);
+        }
+        else
+        {
+            out.setTo(this.x, this.y, this.width, this.height);
+        }
+
+        return out;
+
+    }
+
+};
+
+Phaser.Frame.prototype.constructor = Phaser.Frame;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
+*
+* @class Phaser.FrameData
+* @constructor
+*/
+Phaser.FrameData = function () {
+
+    /**
+    * @property {Array} _frames - Local array of frames.
+    * @private
+    */
+    this._frames = [];
+
+    /**
+    * @property {Array} _frameNames - Local array of frame names for name to index conversions.
+    * @private
+    */
+    this._frameNames = [];
+
+};
+
+Phaser.FrameData.prototype = {
+
+    /**
+    * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
+    *
+    * @method Phaser.FrameData#addFrame
+    * @param {Phaser.Frame} frame - The frame to add to this FrameData set.
+    * @return {Phaser.Frame} The frame that was just added.
+    */
+    addFrame: function (frame) {
+
+        frame.index = this._frames.length;
+
+        this._frames.push(frame);
+
+        if (frame.name !== '')
+        {
+            this._frameNames[frame.name] = frame.index;
+        }
+
+        return frame;
+
+    },
+
+    /**
+    * Get a Frame by its numerical index.
+    *
+    * @method Phaser.FrameData#getFrame
+    * @param {number} index - The index of the frame you want to get.
+    * @return {Phaser.Frame} The frame, if found.
+    */
+    getFrame: function (index) {
+
+        if (index >= this._frames.length)
+        {
+            index = 0;
+        }
+
+        return this._frames[index];
+
+    },
+
+    /**
+    * Get a Frame by its frame name.
+    *
+    * @method Phaser.FrameData#getFrameByName
+    * @param {string} name - The name of the frame you want to get.
+    * @return {Phaser.Frame} The frame, if found.
+    */
+    getFrameByName: function (name) {
+
+        if (typeof this._frameNames[name] === 'number')
+        {
+            return this._frames[this._frameNames[name]];
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Check if there is a Frame with the given name.
+    *
+    * @method Phaser.FrameData#checkFrameName
+    * @param {string} name - The name of the frame you want to check.
+    * @return {boolean} True if the frame is found, otherwise false.
+    */
+    checkFrameName: function (name) {
+
+        if (this._frameNames[name] == null)
+        {
+            return false;
+        }
+
+        return true;
+
+    },
+
+    /**
+     * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains.
+     *
+     * @method Phaser.FrameData#clone
+     * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains.
+     */
+    clone: function () {
+
+        var output = new Phaser.FrameData();
+
+        //  No input array, so we loop through all frames
+        for (var i = 0; i < this._frames.length; i++)
+        {
+            output._frames.push(this._frames[i].clone());
+        }
+
+        for (var p in this._frameNames)
+        {
+            if (this._frameNames.hasOwnProperty(p))
+            {
+                output._frameNames.push(this._frameNames[p]);
+            }
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
+    *
+    * @method Phaser.FrameData#getFrameRange
+    * @param {number} start - The starting frame index.
+    * @param {number} end - The ending frame index.
+    * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
+    * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
+    */
+    getFrameRange: function (start, end, output) {
+
+        if (output === undefined) { output = []; }
+
+        for (var i = start; i <= end; i++)
+        {
+            output.push(this._frames[i]);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Returns all of the Frames in this FrameData set where the frame index is found in the input array.
+    * The frames are returned in the output array, or if none is provided in a new Array object.
+    *
+    * @method Phaser.FrameData#getFrames
+    * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned.
+    * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
+    * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
+    * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
+    */
+    getFrames: function (frames, useNumericIndex, output) {
+
+        if (useNumericIndex === undefined) { useNumericIndex = true; }
+        if (output === undefined) { output = []; }
+
+        if (frames === undefined || frames.length === 0)
+        {
+            //  No input array, so we loop through all frames
+            for (var i = 0; i < this._frames.length; i++)
+            {
+                //  We only need the indexes
+                output.push(this._frames[i]);
+            }
+        }
+        else
+        {
+            //  Input array given, loop through that instead
+            for (var i = 0; i < frames.length; i++)
+            {
+                //  Does the input array contain names or indexes?
+                if (useNumericIndex)
+                {
+                    //  The actual frame
+                    output.push(this.getFrame(frames[i]));
+                }
+                else
+                {
+                    //  The actual frame
+                    output.push(this.getFrameByName(frames[i]));
+                }
+            }
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Returns all of the Frame indexes in this FrameData set.
+    * The frames indexes are returned in the output array, or if none is provided in a new Array object.
+    *
+    * @method Phaser.FrameData#getFrameIndexes
+    * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned.
+    * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
+    * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
+    * @return {Array} An array of all Frame indexes matching the given names or IDs.
+    */
+    getFrameIndexes: function (frames, useNumericIndex, output) {
+
+        if (useNumericIndex === undefined) { useNumericIndex = true; }
+        if (output === undefined) { output = []; }
+
+        if (frames === undefined || frames.length === 0)
+        {
+            //  No frames array, so we loop through all frames
+            for (var i = 0; i < this._frames.length; i++)
+            {
+                output.push(this._frames[i].index);
+            }
+        }
+        else
+        {
+            //  Input array given, loop through that instead
+            for (var i = 0; i < frames.length; i++)
+            {
+                //  Does the frames array contain names or indexes?
+                if (useNumericIndex)
+                {
+                    output.push(this._frames[frames[i]].index);
+                }
+                else
+                {
+                    if (this.getFrameByName(frames[i]))
+                    {
+                        output.push(this.getFrameByName(frames[i]).index);
+                    }
+                }
+            }
+        }
+
+        return output;
+
+    }
+
+};
+
+Phaser.FrameData.prototype.constructor = Phaser.FrameData;
+
+/**
+* @name Phaser.FrameData#total
+* @property {number} total - The total number of frames in this FrameData set.
+* @readonly
+*/
+Object.defineProperty(Phaser.FrameData.prototype, "total", {
+
+    get: function () {
+        return this._frames.length;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
+*
+* @class Phaser.AnimationParser
+* @static
+*/
+Phaser.AnimationParser = {
+
+    /**
+    * Parse a Sprite Sheet and extract the animation frame data from it.
+    *
+    * @method Phaser.AnimationParser.spriteSheet
+    * @param {Phaser.Game} game - A reference to the currently running game.
+    * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element.
+    * @param {number} frameWidth - The fixed width of each frame of the animation.
+    * @param {number} frameHeight - The fixed height of each frame of the animation.
+    * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames".
+    * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
+    * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
+    * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
+    */
+    spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing) {
+
+        var img = key;
+
+        if (typeof key === 'string')
+        {
+            img = game.cache.getImage(key);
+        }
+
+        if (img === null)
+        {
+            return null;
+        }
+
+        var width = img.width;
+        var height = img.height;
+
+        if (frameWidth <= 0)
+        {
+            frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
+        }
+
+        if (frameHeight <= 0)
+        {
+            frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
+        }
+
+        var row = Math.floor((width - margin) / (frameWidth + spacing));
+        var column = Math.floor((height - margin) / (frameHeight + spacing));
+        var total = row * column;
+
+        if (frameMax !== -1)
+        {
+            total = frameMax;
+        }
+
+        //  Zero or smaller than frame sizes?
+        if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
+        {
+            console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight");
+            return null;
+        }
+
+        //  Let's create some frames then
+        var data = new Phaser.FrameData();
+        var x = margin;
+        var y = margin;
+
+        for (var i = 0; i < total; i++)
+        {
+            data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, ''));
+
+            x += frameWidth + spacing;
+
+            if (x + frameWidth > width)
+            {
+                x = margin;
+                y += frameHeight + spacing;
+            }
+        }
+
+        return data;
+
+    },
+
+    /**
+    * Parse the JSON data and extract the animation frame data from it.
+    *
+    * @method Phaser.AnimationParser.JSONData
+    * @param {Phaser.Game} game - A reference to the currently running game.
+    * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format.
+    * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
+    */
+    JSONData: function (game, json) {
+
+        //  Malformed?
+        if (!json['frames'])
+        {
+            console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
+            console.log(json);
+            return;
+        }
+
+        //  Let's create some frames then
+        var data = new Phaser.FrameData();
+
+        //  By this stage frames is a fully parsed array
+        var frames = json['frames'];
+        var newFrame;
+
+        for (var i = 0; i < frames.length; i++)
+        {
+            newFrame = data.addFrame(new Phaser.Frame(
+                i,
+                frames[i].frame.x,
+                frames[i].frame.y,
+                frames[i].frame.w,
+                frames[i].frame.h,
+                frames[i].filename
+            ));
+
+            if (frames[i].trimmed)
+            {
+                newFrame.setTrim(
+                    frames[i].trimmed,
+                    frames[i].sourceSize.w,
+                    frames[i].sourceSize.h,
+                    frames[i].spriteSourceSize.x,
+                    frames[i].spriteSourceSize.y,
+                    frames[i].spriteSourceSize.w,
+                    frames[i].spriteSourceSize.h
+                );
+            }
+        }
+
+        return data;
+
+    },
+
+    /**
+    * Parse the JSON data and extract the animation frame data from it.
+    *
+    * @method Phaser.AnimationParser.JSONDataHash
+    * @param {Phaser.Game} game - A reference to the currently running game.
+    * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
+    * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
+    */
+    JSONDataHash: function (game, json) {
+
+        //  Malformed?
+        if (!json['frames'])
+        {
+            console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
+            console.log(json);
+            return;
+        }
+
+        //  Let's create some frames then
+        var data = new Phaser.FrameData();
+
+        //  By this stage frames is a fully parsed array
+        var frames = json['frames'];
+        var newFrame;
+        var i = 0;
+
+        for (var key in frames)
+        {
+            newFrame = data.addFrame(new Phaser.Frame(
+                i,
+                frames[key].frame.x,
+                frames[key].frame.y,
+                frames[key].frame.w,
+                frames[key].frame.h,
+                key
+            ));
+
+            if (frames[key].trimmed)
+            {
+                newFrame.setTrim(
+                    frames[key].trimmed,
+                    frames[key].sourceSize.w,
+                    frames[key].sourceSize.h,
+                    frames[key].spriteSourceSize.x,
+                    frames[key].spriteSourceSize.y,
+                    frames[key].spriteSourceSize.w,
+                    frames[key].spriteSourceSize.h
+                );
+            }
+
+            i++;
+        }
+
+        return data;
+
+    },
+
+    /**
+    * Parse the XML data and extract the animation frame data from it.
+    *
+    * @method Phaser.AnimationParser.XMLData
+    * @param {Phaser.Game} game - A reference to the currently running game.
+    * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
+    * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
+    */
+    XMLData: function (game, xml) {
+
+        //  Malformed?
+        if (!xml.getElementsByTagName('TextureAtlas'))
+        {
+            console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
+            return;
+        }
+
+        //  Let's create some frames then
+        var data = new Phaser.FrameData();
+        var frames = xml.getElementsByTagName('SubTexture');
+        var newFrame;
+
+        var name;
+        var frame;
+        var x;
+        var y;
+        var width;
+        var height;
+        var frameX;
+        var frameY;
+        var frameWidth;
+        var frameHeight;
+
+        for (var i = 0; i < frames.length; i++)
+        {
+            frame = frames[i].attributes;
+            
+            name = frame.name.value;
+            x = parseInt(frame.x.value, 10);
+            y = parseInt(frame.y.value, 10);
+            width = parseInt(frame.width.value, 10);
+            height = parseInt(frame.height.value, 10);
+
+            frameX = null;
+            frameY = null;
+
+            if (frame.frameX)
+            {
+                frameX = Math.abs(parseInt(frame.frameX.value, 10));
+                frameY = Math.abs(parseInt(frame.frameY.value, 10));
+                frameWidth = parseInt(frame.frameWidth.value, 10);
+                frameHeight = parseInt(frame.frameHeight.value, 10);
+            }
+
+            newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name));
+
+            //  Trimmed?
+            if (frameX !== null || frameY !== null)
+            {
+                newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
+            }
+        }
+
+        return data;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser has one single cache in which it stores all assets.
+* 
+* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using
+* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the
+* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file,
+* because they are unique data types.
+* 
+* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets
+* such as images they are automatically placed into their respective cache. Most common Game Objects, such as
+* Sprites and Videos automatically query the cache to extract the assets they need on instantiation.
+*
+* You can access the cache from within a State via `this.cache`. From here you can call any public method it has,
+* including adding new entries to it, deleting them or querying them.
+*
+* Understand that almost without exception when you get an item from the cache it will return a reference to the
+* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original
+* object in the cache will also be updated, even if you don't put it back into the cache again.
+*
+* By default when you change State the cache is _not_ cleared, although there is an option to clear it should
+* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and
+* then used as an asset store.
+*
+* @class Phaser.Cache
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Cache = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method.
+    * @property {boolean} autoResolveURL
+    */
+    this.autoResolveURL = false;
+
+    /**
+    * The main cache object into which all resources are placed.
+    * @property {object} _cache
+    * @private
+    */
+    this._cache = {
+        canvas: {},
+        image: {},
+        texture: {},
+        sound: {},
+        video: {},
+        text: {},
+        json: {},
+        xml: {},
+        physics: {},
+        tilemap: {},
+        binary: {},
+        bitmapData: {},
+        bitmapFont: {},
+        shader: {},
+        renderTexture: {}
+    };
+
+    /**
+    * @property {object} _urlMap - Maps URLs to resources.
+    * @private
+    */
+    this._urlMap = {};
+
+    /**
+    * @property {Image} _urlResolver - Used to resolve URLs to the absolute path.
+    * @private
+    */
+    this._urlResolver = new Image();
+
+    /**
+    * @property {string} _urlTemp - Temporary variable to hold a resolved url.
+    * @private
+    */
+    this._urlTemp = null;
+
+    /**
+    * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices.
+    */
+    this.onSoundUnlock = new Phaser.Signal();
+
+    /**
+    * @property {array} _cacheMap - Const to cache object look-up array.
+    * @private
+    */
+    this._cacheMap = [];
+
+    this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas;
+    this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image;
+    this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture;
+    this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound;
+    this._cacheMap[Phaser.Cache.TEXT] = this._cache.text;
+    this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics;
+    this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap;
+    this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary;
+    this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData;
+    this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont;
+    this._cacheMap[Phaser.Cache.JSON] = this._cache.json;
+    this._cacheMap[Phaser.Cache.XML] = this._cache.xml;
+    this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video;
+    this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader;
+    this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture;
+
+    this.addDefaultImage();
+    this.addMissingImage();
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.CANVAS = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.IMAGE = 2;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.TEXTURE = 3;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.SOUND = 4;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.TEXT = 5;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.PHYSICS = 6;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.TILEMAP = 7;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.BINARY = 8;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.BITMAPDATA = 9;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.BITMAPFONT = 10;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.JSON = 11;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.XML = 12;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.VIDEO = 13;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.SHADER = 14;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Cache.RENDER_TEXTURE = 15;
+
+Phaser.Cache.prototype = {
+
+    //////////////////
+    //  Add Methods //
+    //////////////////
+
+    /**
+    * Add a new canvas object in to the cache.
+    *
+    * @method Phaser.Cache#addCanvas
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {HTMLCanvasElement} canvas - The Canvas DOM element.
+    * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`.
+    */
+    addCanvas: function (key, canvas, context) {
+
+        if (context === undefined) { context = canvas.getContext('2d'); }
+
+        this._cache.canvas[key] = { canvas: canvas, context: context };
+
+    },
+
+    /**
+    * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM.
+    * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place.
+    *
+    * @method Phaser.Cache#addImage
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra image data.
+    * @return {object} The full image object that was added to the cache.
+    */
+    addImage: function (key, url, data) {
+
+        if (this.checkImageKey(key))
+        {
+            this.removeImage(key);
+        }
+
+        var img = {
+            key: key,
+            url: url,
+            data: data,
+            base: new PIXI.BaseTexture(data),
+            frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key),
+            frameData: new Phaser.FrameData()
+        };
+
+        img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url));
+
+        this._cache.image[key] = img;
+
+        this._resolveURL(url, img);
+
+        return img;
+
+    },
+
+    /**
+    * Adds a default image to be used in special cases such as WebGL Filters.
+    * It uses the special reserved key of `__default`.
+    * This method is called automatically when the Cache is created.
+    * This image is skipped when `Cache.destroy` is called due to its internal requirements.
+    *
+    * @method Phaser.Cache#addDefaultImage
+    * @protected
+    */
+    addDefaultImage: function () {
+
+        var img = new Image();
+
+        img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";
+
+        var obj = this.addImage('__default', null, img);
+
+        PIXI.TextureCache['__default'] = new PIXI.Texture(obj.base);
+
+    },
+
+    /**
+    * Adds an image to be used when a key is wrong / missing.
+    * It uses the special reserved key of `__missing`.
+    * This method is called automatically when the Cache is created.
+    * This image is skipped when `Cache.destroy` is called due to its internal requirements.
+    *
+    * @method Phaser.Cache#addMissingImage
+    * @protected
+    */
+    addMissingImage: function () {
+
+        var img = new Image();
+
+        img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";
+
+        var obj = this.addImage('__missing', null, img);
+
+        PIXI.TextureCache['__missing'] = new PIXI.Texture(obj.base);
+
+    },
+
+    /**
+    * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
+    *
+    * @method Phaser.Cache#addSound
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra sound data.
+    * @param {boolean} webAudio - True if the file is using web audio.
+    * @param {boolean} audioTag - True if the file is using legacy HTML audio.
+    */
+    addSound: function (key, url, data, webAudio, audioTag) {
+
+        if (webAudio === undefined) { webAudio = true; audioTag = false; }
+        if (audioTag === undefined) { webAudio = false; audioTag = true; }
+
+        var decoded = false;
+
+        if (audioTag)
+        {
+            decoded = true;
+        }
+
+        this._cache.sound[key] = {
+            url: url,
+            data: data,
+            isDecoding: false,
+            decoded: decoded,
+            webAudio: webAudio,
+            audioTag: audioTag,
+            locked: this.game.sound.touchLocked
+        };
+
+        this._resolveURL(url, this._cache.sound[key]);
+
+    },
+
+    /**
+    * Add a new text data.
+    *
+    * @method Phaser.Cache#addText
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra text data.
+    */
+    addText: function (key, url, data) {
+
+        this._cache.text[key] = { url: url, data: data };
+
+        this._resolveURL(url, this._cache.text[key]);
+
+    },
+
+    /**
+    * Add a new physics data object to the Cache.
+    *
+    * @method Phaser.Cache#addPhysicsData
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} JSONData - The physics data object (a JSON file).
+    * @param {number} format - The format of the physics data.
+    */
+    addPhysicsData: function (key, url, JSONData, format) {
+
+        this._cache.physics[key] = { url: url, data: JSONData, format: format };
+
+        this._resolveURL(url, this._cache.physics[key]);
+
+    },
+
+    /**
+    * Add a new tilemap to the Cache.
+    *
+    * @method Phaser.Cache#addTilemap
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} mapData - The tilemap data object (either a CSV or JSON file).
+    * @param {number} format - The format of the tilemap data.
+    */
+    addTilemap: function (key, url, mapData, format) {
+
+        this._cache.tilemap[key] = { url: url, data: mapData, format: format };
+
+        this._resolveURL(url, this._cache.tilemap[key]);
+
+    },
+
+    /**
+    * Add a binary object in to the cache.
+    *
+    * @method Phaser.Cache#addBinary
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {object} binaryData - The binary object to be added to the cache.
+    */
+    addBinary: function (key, binaryData) {
+
+        this._cache.binary[key] = binaryData;
+
+    },
+
+    /**
+    * Add a BitmapData object to the cache.
+    *
+    * @method Phaser.Cache#addBitmapData
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache.
+    * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created.
+    * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache.
+    */
+    addBitmapData: function (key, bitmapData, frameData) {
+
+        bitmapData.key = key;
+
+        if (frameData === undefined)
+        {
+            frameData = new Phaser.FrameData();
+            frameData.addFrame(bitmapData.textureFrame);
+        }
+
+        this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData };
+
+        return bitmapData;
+
+    },
+
+    /**
+    * Add a new Bitmap Font to the Cache.
+    *
+    * @method Phaser.Cache#addBitmapFont
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra font data.
+    * @param {object} atlasData - Texture atlas frames data.
+    * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
+    * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
+    */
+    addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) {
+
+        var obj = {
+            url: url,
+            data: data,
+            font: null,
+            base: new PIXI.BaseTexture(data)
+        };
+
+        if (atlasType === 'json')
+        {
+            obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing);
+        }
+        else
+        {
+            obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing);
+        }
+
+        this._cache.bitmapFont[key] = obj;
+
+        this._resolveURL(url, obj);
+
+    },
+
+    /**
+    * Add a new json object into the cache.
+    *
+    * @method Phaser.Cache#addJSON
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra json data.
+    */
+    addJSON: function (key, url, data) {
+
+        this._cache.json[key] = { url: url, data: data };
+
+        this._resolveURL(url, this._cache.json[key]);
+
+    },
+
+    /**
+    * Add a new xml object into the cache.
+    *
+    * @method Phaser.Cache#addXML
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra text data.
+    */
+    addXML: function (key, url, data) {
+
+        this._cache.xml[key] = { url: url, data: data };
+
+        this._resolveURL(url, this._cache.xml[key]);
+
+    },
+
+    /**
+    * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
+    *
+    * @method Phaser.Cache#addVideo
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra video data.
+    * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead.
+    */
+    addVideo: function (key, url, data, isBlob) {
+
+        this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true };
+
+        this._resolveURL(url, this._cache.video[key]);
+
+    },
+
+    /**
+    * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader.
+    *
+    * @method Phaser.Cache#addShader
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra shader data.
+    */
+    addShader: function (key, url, data) {
+
+        this._cache.shader[key] = { url: url, data: data };
+
+        this._resolveURL(url, this._cache.shader[key]);
+
+    },
+
+    /**
+    * Add a new Phaser.RenderTexture in to the cache.
+    *
+    * @method Phaser.Cache#addRenderTexture
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture.
+    */
+    addRenderTexture: function (key, texture) {
+
+        this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') };
+
+    },
+
+    /**
+    * Add a new sprite sheet in to the cache.
+    *
+    * @method Phaser.Cache#addSpriteSheet
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra sprite sheet data.
+    * @param {number} frameWidth - Width of the sprite sheet.
+    * @param {number} frameHeight - Height of the sprite sheet.
+    * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly.
+    * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
+    * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
+    */
+    addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing) {
+
+        var obj = {
+            key: key,
+            url: url,
+            data: data,
+            frameWidth: frameWidth,
+            frameHeight: frameHeight,
+            margin: margin,
+            spacing: spacing,
+            base: new PIXI.BaseTexture(data),
+            frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing)
+        };
+
+        this._cache.image[key] = obj;
+
+        this._resolveURL(url, obj);
+
+    },
+
+    /**
+    * Add a new texture atlas to the Cache.
+    *
+    * @method Phaser.Cache#addTextureAtlas
+    * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
+    * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
+    * @param {object} data - Extra texture atlas data.
+    * @param {object} atlasData  - Texture atlas frames data.
+    * @param {number} format - The format of the texture atlas.
+    */
+    addTextureAtlas: function (key, url, data, atlasData, format) {
+
+        var obj = {
+            key: key,
+            url: url,
+            data: data,
+            base: new PIXI.BaseTexture(data)
+        };
+
+        if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
+        {
+            obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key);
+        }
+        else
+        {
+            //  Let's just work it out from the frames array
+            if (Array.isArray(atlasData.frames))
+            {
+                obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key);
+            }
+            else
+            {
+                obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key);
+            }
+        }
+
+        this._cache.image[key] = obj;
+
+        this._resolveURL(url, obj);
+
+    },
+
+    ////////////////////////////
+    //  Sound Related Methods //
+    ////////////////////////////
+
+    /**
+    * Reload a Sound file from the server.
+    *
+    * @method Phaser.Cache#reloadSound
+    * @param {string} key - The key of the asset within the cache.
+    */
+    reloadSound: function (key) {
+
+        var _this = this;
+
+        var sound = this.getSound(key);
+
+        if (sound)
+        {
+            sound.data.src = sound.url;
+
+            sound.data.addEventListener('canplaythrough', function () {
+                return _this.reloadSoundComplete(key);
+            }, false);
+
+            sound.data.load();
+        }
+
+    },
+
+    /**
+    * Fires the onSoundUnlock event when the sound has completed reloading.
+    *
+    * @method Phaser.Cache#reloadSoundComplete
+    * @param {string} key - The key of the asset within the cache.
+    */
+    reloadSoundComplete: function (key) {
+
+        var sound = this.getSound(key);
+
+        if (sound)
+        {
+            sound.locked = false;
+            this.onSoundUnlock.dispatch(key);
+        }
+
+    },
+
+    /**
+    * Updates the sound object in the cache.
+    *
+    * @method Phaser.Cache#updateSound
+    * @param {string} key - The key of the asset within the cache.
+    */
+    updateSound: function (key, property, value) {
+
+        var sound = this.getSound(key);
+
+        if (sound)
+        {
+            sound[property] = value;
+        }
+
+    },
+
+    /**
+    * Add a new decoded sound.
+    *
+    * @method Phaser.Cache#decodedSound
+    * @param {string} key - The key of the asset within the cache.
+    * @param {object} data - Extra sound data.
+    */
+    decodedSound: function (key, data) {
+
+        var sound = this.getSound(key);
+
+        sound.data = data;
+        sound.decoded = true;
+        sound.isDecoding = false;
+
+    },
+
+    /**
+    * Check if the given sound has finished decoding.
+    *
+    * @method Phaser.Cache#isSoundDecoded
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} The decoded state of the Sound object.
+    */
+    isSoundDecoded: function (key) {
+
+        var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded');
+
+        if (sound)
+        {
+            return sound.decoded;
+        }
+
+    },
+
+    /**
+    * Check if the given sound is ready for playback.
+    * A sound is considered ready when it has finished decoding and the device is no longer touch locked.
+    *
+    * @method Phaser.Cache#isSoundReady
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the sound is decoded and the device is not touch locked.
+    */
+    isSoundReady: function (key) {
+
+        var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded');
+
+        if (sound)
+        {
+            return (sound.decoded && !this.game.sound.touchLocked);
+        }
+
+    },
+
+    ////////////////////////
+    //  Check Key Methods //
+    ////////////////////////
+
+    /**
+    * Checks if a key for the given cache object type exists.
+    *
+    * @method Phaser.Cache#checkKey
+    * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists, otherwise false.
+    */
+    checkKey: function (cache, key) {
+
+        if (this._cacheMap[cache][key])
+        {
+            return true;
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Checks if the given URL has been loaded into the Cache.
+    * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place.
+    * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox
+    * which may cause double-load instances.
+    *
+    * @method Phaser.Cache#checkURL
+    * @param {string} url - The url to check for in the cache.
+    * @return {boolean} True if the url exists, otherwise false.
+    */
+    checkURL: function (url) {
+
+        if (this._urlMap[this._resolveURL(url)])
+        {
+            return true;
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Checks if the given key exists in the Canvas Cache.
+    *
+    * @method Phaser.Cache#checkCanvasKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkCanvasKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.CANVAS, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts.
+    *
+    * @method Phaser.Cache#checkImageKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkImageKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.IMAGE, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Texture Cache.
+    *
+    * @method Phaser.Cache#checkTextureKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkTextureKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.TEXTURE, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Sound Cache.
+    *
+    * @method Phaser.Cache#checkSoundKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkSoundKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.SOUND, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Text Cache.
+    *
+    * @method Phaser.Cache#checkTextKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkTextKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.TEXT, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Physics Cache.
+    *
+    * @method Phaser.Cache#checkPhysicsKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkPhysicsKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.PHYSICS, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Tilemap Cache.
+    *
+    * @method Phaser.Cache#checkTilemapKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkTilemapKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.TILEMAP, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Binary Cache.
+    *
+    * @method Phaser.Cache#checkBinaryKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkBinaryKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.BINARY, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the BitmapData Cache.
+    *
+    * @method Phaser.Cache#checkBitmapDataKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkBitmapDataKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.BITMAPDATA, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the BitmapFont Cache.
+    *
+    * @method Phaser.Cache#checkBitmapFontKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkBitmapFontKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.BITMAPFONT, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the JSON Cache.
+    *
+    * @method Phaser.Cache#checkJSONKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkJSONKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.JSON, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the XML Cache.
+    *
+    * @method Phaser.Cache#checkXMLKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkXMLKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.XML, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Video Cache.
+    *
+    * @method Phaser.Cache#checkVideoKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkVideoKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.VIDEO, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Fragment Shader Cache.
+    *
+    * @method Phaser.Cache#checkShaderKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkShaderKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.SHADER, key);
+
+    },
+
+    /**
+    * Checks if the given key exists in the Render Texture Cache.
+    *
+    * @method Phaser.Cache#checkRenderTextureKey
+    * @param {string} key - The key of the asset within the cache.
+    * @return {boolean} True if the key exists in the cache, otherwise false.
+    */
+    checkRenderTextureKey: function (key) {
+
+        return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key);
+
+    },
+
+    ////////////////
+    //  Get Items //
+    ////////////////
+
+    /**
+    * Get an item from a cache based on the given key and property.
+    * 
+    * This method is mostly used internally by other Cache methods such as `getImage` but is exposed
+    * publicly for your own use as well.
+    *
+    * @method Phaser.Cache#getItem
+    * @param {string} key - The key of the asset within the cache.
+    * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
+    * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output.
+    * @param {string} [property] - If you require a specific property from the cache item, specify it here.
+    * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output.
+    */
+    getItem: function (key, cache, method, property) {
+
+        if (!this.checkKey(cache, key))
+        {
+            if (method)
+            {
+                console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.');
+            }
+        }
+        else
+        {
+            if (property === undefined)
+            {
+                return this._cacheMap[cache][key];
+            }
+            else
+            {
+                return this._cacheMap[cache][key][property];
+            }
+        }
+        
+        return null;
+
+    },
+
+    /**
+    * Gets a Canvas object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getCanvas
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {object} The canvas object or `null` if no item could be found matching the given key.
+    */
+    getCanvas: function (key) {
+
+        return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas');
+
+    },
+
+    /**
+    * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    * 
+    * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases.
+    * 
+    * If you need the image used by a bitmap font or similar then please use those respective 'get' methods.
+    *
+    * @method Phaser.Cache#getImage
+    * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image.
+    * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned.
+    * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned.
+    */
+    getImage: function (key, full) {
+
+        if (key === undefined || key === null)
+        {
+            key = '__default';
+        }
+
+        if (full === undefined) { full = false; }
+
+        var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage');
+
+        if (img === null)
+        {
+            img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage');
+        }
+
+        if (full)
+        {
+            return img;
+        }
+        else
+        {
+            return img.data;
+        }
+
+    },
+
+    /**
+    * Get a single texture frame by key.
+    * 
+    * You'd only do this to get the default Frame created for a non-atlas / spritesheet image.
+    *
+    * @method Phaser.Cache#getTextureFrame
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {Phaser.Frame} The frame data.
+    */
+    getTextureFrame: function (key) {
+
+        return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame');
+
+    },
+
+    /**
+    * Gets a Phaser.Sound object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getSound
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {Phaser.Sound} The sound object.
+    */
+    getSound: function (key) {
+
+        return this.getItem(key, Phaser.Cache.SOUND, 'getSound');
+
+    },
+
+    /**
+    * Gets a raw Sound data object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getSoundData
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {object} The sound data.
+    */
+    getSoundData: function (key) {
+
+        return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data');
+
+    },
+
+    /**
+    * Gets a Text object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getText
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {object} The text data.
+    */
+    getText: function (key) {
+
+        return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data');
+
+    },
+
+    /**
+    * Gets a Physics Data object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    * 
+    * You can get either the entire data set, a single object or a single fixture of an object from it.
+    *
+    * @method Phaser.Cache#getPhysicsData
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all.
+    * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter.
+    * @return {object} The requested physics object data if found.
+    */
+    getPhysicsData: function (key, object, fixtureKey) {
+
+        var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data');
+
+        if (data === null || object === undefined || object === null)
+        {
+            return data;
+        }
+        else
+        {
+            if (data[object])
+            {
+                var fixtures = data[object];
+
+                //  Try to find a fixture by its fixture key if given
+                if (fixtures && fixtureKey)
+                {
+                    for (var fixture in fixtures)
+                    {
+                        //  This contains the fixture data of a polygon or a circle
+                        fixture = fixtures[fixture];
+
+                        //  Test the key
+                        if (fixture.fixtureKey === fixtureKey)
+                        {
+                            return fixture;
+                        }
+                    }
+
+                    //  We did not find the requested fixture
+                    console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"');
+                }
+                else
+                {
+                    return fixtures;
+                }
+            }
+            else
+            {
+                console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"');
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getTilemapData
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {object} The raw tilemap data in CSV or JSON format.
+    */
+    getTilemapData: function (key) {
+
+        return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData');
+
+    },
+
+    /**
+    * Gets a binary object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getBinary
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {object} The binary data object.
+    */
+    getBinary: function (key) {
+
+        return this.getItem(key, Phaser.Cache.BINARY, 'getBinary');
+
+    },
+
+    /**
+    * Gets a BitmapData object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getBitmapData
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not.
+    */
+    getBitmapData: function (key) {
+
+        return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data');
+
+    },
+
+    /**
+    * Gets a Bitmap Font object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getBitmapFont
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not.
+    */
+    getBitmapFont: function (key) {
+
+        return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont');
+
+    },
+
+    /**
+    * Gets a JSON object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    * 
+    * You can either return the object by reference (the default), or return a clone
+    * of it by setting the `clone` argument to `true`.
+    *
+    * @method Phaser.Cache#getJSON
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false)
+    * @return {object} The JSON object.
+    */
+    getJSON: function (key, clone) {
+
+        var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data');
+
+        if (data)
+        {
+            if (clone)
+            {
+                return Phaser.Utils.extend(true, data);
+            }
+            else
+            {
+                return data;
+            }
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Gets an XML object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getXML
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {object} The XML object.
+    */
+    getXML: function (key) {
+
+        return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data');
+
+    },
+
+    /**
+    * Gets a Phaser.Video object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getVideo
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {Phaser.Video} The video object.
+    */
+    getVideo: function (key) {
+
+        return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo');
+
+    },
+
+    /**
+    * Gets a fragment shader object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getShader
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {string} The shader object.
+    */
+    getShader: function (key) {
+
+        return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data');
+
+    },
+
+    /**
+    * Gets a RenderTexture object from the cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getRenderTexture
+    * @param {string} key - The key of the asset to retrieve from the cache.
+    * @return {Phaser.RenderTexture} The RenderTexture object.
+    */
+    getRenderTexture: function (key) {
+
+        return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture');
+
+    },
+
+    ////////////////////////////
+    //  Frame Related Methods //
+    ////////////////////////////
+
+    /**
+    * Gets a PIXI.BaseTexture by key from the given Cache.
+    *
+    * @method Phaser.Cache#getBaseTexture
+    * @param {string} key - Asset key of the image for which you want the BaseTexture for.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
+    * @return {PIXI.BaseTexture} The BaseTexture object.
+    */
+    getBaseTexture: function (key, cache) {
+
+        if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
+
+        return this.getItem(key, cache, 'getBaseTexture', 'base');
+
+    },
+
+    /**
+    * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
+    *
+    * @method Phaser.Cache#getFrame
+    * @param {string} key - Asset key of the frame data to retrieve from the Cache.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
+    * @return {Phaser.Frame} The frame data.
+    */
+    getFrame: function (key, cache) {
+
+        if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
+
+        return this.getItem(key, cache, 'getFrame', 'frame');
+
+    },
+
+    /**
+    * Get the total number of frames contained in the FrameData object specified by the given key.
+    *
+    * @method Phaser.Cache#getFrameCount
+    * @param {string} key - Asset key of the FrameData you want.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
+    * @return {number} Then number of frames. 0 if the image is not found.
+    */
+    getFrameCount: function (key, cache) {
+
+        var data = this.getFrameData(key, cache);
+
+        if (data)
+        {
+            return data.total;
+        }
+        else
+        {
+            return 0;
+        }
+
+    },
+
+    /**
+    * Gets a Phaser.FrameData object from the Image Cache.
+    * 
+    * The object is looked-up based on the key given.
+    * 
+    * Note: If the object cannot be found a `console.warn` message is displayed.
+    *
+    * @method Phaser.Cache#getFrameData
+    * @param {string} key - Asset key of the frame data to retrieve from the Cache.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
+    * @return {Phaser.FrameData} The frame data.
+    */
+    getFrameData: function (key, cache) {
+
+        if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
+
+        return this.getItem(key, cache, 'getFrameData', 'frameData');
+
+    },
+
+    /**
+    * Check if the FrameData for the given key exists in the Image Cache.
+    *
+    * @method Phaser.Cache#hasFrameData
+    * @param {string} key - Asset key of the frame data to retrieve from the Cache.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
+    * @return {boolean} True if the given key has frameData in the cache, otherwise false.
+    */
+    hasFrameData: function (key, cache) {
+
+        if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
+
+        return (this.getItem(key, cache, '', 'frameData') !== null);
+
+    },
+
+    /**
+    * Replaces a set of frameData with a new Phaser.FrameData object.
+    *
+    * @method Phaser.Cache#updateFrameData
+    * @param {string} key - The unique key by which you will reference this object.
+    * @param {number} frameData - The new FrameData.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
+    */
+    updateFrameData: function (key, frameData, cache) {
+
+        if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
+
+        if (this._cacheMap[cache][key])
+        {
+            this._cacheMap[cache][key].frameData = frameData;
+        }
+
+    },
+
+    /**
+    * Get a single frame out of a frameData set by key.
+    *
+    * @method Phaser.Cache#getFrameByIndex
+    * @param {string} key - Asset key of the frame data to retrieve from the Cache.
+    * @param {number} index - The index of the frame you want to get.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
+    * @return {Phaser.Frame} The frame object.
+    */
+    getFrameByIndex: function (key, index, cache) {
+
+        var data = this.getFrameData(key, cache);
+
+        if (data)
+        {
+            return data.getFrame(index);
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Get a single frame out of a frameData set by key.
+    *
+    * @method Phaser.Cache#getFrameByName
+    * @param {string} key - Asset key of the frame data to retrieve from the Cache.
+    * @param {string} name - The name of the frame you want to get.
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
+    * @return {Phaser.Frame} The frame object.
+    */
+    getFrameByName: function (key, name, cache) {
+
+        var data = this.getFrameData(key, cache);
+
+        if (data)
+        {
+            return data.getFrameByName(name);
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Gets a PIXI.Texture by key from the PIXI.TextureCache.
+    *
+    * If the texture isn't found in the cache, then it searches the Phaser Image Cache and
+    * creates a new PIXI.Texture object which is then returned.
+    *
+    * @method Phaser.Cache#getPixiTexture
+    * @deprecated
+    * @param {string} key - Asset key of the Texture to retrieve from the Cache.
+    * @return {PIXI.Texture} The Texture object.
+    */
+    getPixiTexture: function (key) {
+
+        if (PIXI.TextureCache[key])
+        {
+            return PIXI.TextureCache[key];
+        }
+        else
+        {
+            var base = this.getPixiBaseTexture(key);
+
+            if (base)
+            {
+                return new PIXI.Texture(base);
+            }
+            else
+            {
+                return null;
+            }
+        }
+
+    },
+
+    /**
+    * Gets a PIXI.BaseTexture by key from the PIXI.BaseTextureCache.
+    * 
+    * If the texture isn't found in the cache, then it searches the Phaser Image Cache.
+    *
+    * @method Phaser.Cache#getPixiBaseTexture
+    * @deprecated
+    * @param {string} key - Asset key of the BaseTexture to retrieve from the Cache.
+    * @return {PIXI.BaseTexture} The BaseTexture object or null if not found.
+    */
+    getPixiBaseTexture: function (key) {
+
+        if (PIXI.BaseTextureCache[key])
+        {
+            return PIXI.BaseTextureCache[key];
+        }
+        else
+        {
+            var img = this.getItem(key, Phaser.Cache.IMAGE, 'getPixiBaseTexture');
+
+            if (img !== null)
+            {
+                return img.base;
+            }
+            else
+            {
+                return null;
+            }
+        }
+
+    },
+
+    /**
+    * Get a cached object by the URL.
+    * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets.
+    * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices.
+    *
+    * @method Phaser.Cache#getURL
+    * @param {string} url - The url for the object loaded to get from the cache.
+    * @return {object} The cached object.
+    */
+    getURL: function (url) {
+
+        var url = this._resolveURL(url);
+
+        if (url)
+        {
+            return this._urlMap[url];
+        }
+        else
+        {
+            console.warn('Phaser.Cache.getUrl: Invalid url: "' + url  + '" or Cache.autoResolveURL was false');
+            return null;
+        }
+
+    },
+
+    /**
+    * Gets all keys used in the requested Cache.
+    *
+    * @method Phaser.Cache#getKeys
+    * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc.
+    * @return {Array} The array of keys in the requested cache.
+    */
+    getKeys: function (cache) {
+
+        if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
+
+        var out = [];
+
+        if (this._cacheMap[cache])
+        {
+            for (var key in this._cacheMap[cache])
+            {
+                if (key !== '__default' && key !== '__missing')
+                {
+                    out.push(key);
+                }
+            }
+        }
+
+        return out;
+
+    },
+
+    /////////////////////
+    //  Remove Methods //
+    /////////////////////
+
+    /**
+    * Removes a canvas from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeCanvas
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeCanvas: function (key) {
+
+        delete this._cache.canvas[key];
+
+    },
+
+    /**
+    * Removes an image from the cache.
+    * 
+    * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it.
+    *
+    * Note that this only removes it from the Phaser and PIXI Caches. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeImage
+    * @param {string} key - Key of the asset you want to remove.
+    * @param {boolean} [removeFromPixi=true] - Should this image also be destroyed? Removing it from the PIXI.BaseTextureCache?
+    */
+    removeImage: function (key, removeFromPixi) {
+
+        if (removeFromPixi === undefined) { removeFromPixi = true; }
+
+        var img = this.getImage(key, true);
+
+        if (removeFromPixi && img.base)
+        {
+            img.base.destroy();
+        }
+
+        delete this._cache.image[key];
+
+    },
+
+    /**
+    * Removes a sound from the cache.
+    *
+    * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will
+    * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then
+    * you must finish your house-keeping and destroy them all yourself first, before calling this method.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeSound
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeSound: function (key) {
+
+        delete this._cache.sound[key];
+
+    },
+
+    /**
+    * Removes a text file from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeText
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeText: function (key) {
+
+        delete this._cache.text[key];
+
+    },
+
+    /**
+    * Removes a physics data file from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removePhysics
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removePhysics: function (key) {
+
+        delete this._cache.physics[key];
+
+    },
+
+    /**
+    * Removes a tilemap from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeTilemap
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeTilemap: function (key) {
+
+        delete this._cache.tilemap[key];
+
+    },
+
+    /**
+    * Removes a binary file from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeBinary
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeBinary: function (key) {
+
+        delete this._cache.binary[key];
+
+    },
+
+    /**
+    * Removes a bitmap data from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeBitmapData
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeBitmapData: function (key) {
+
+        delete this._cache.bitmapData[key];
+
+    },
+
+    /**
+    * Removes a bitmap font from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeBitmapFont
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeBitmapFont: function (key) {
+
+        delete this._cache.bitmapFont[key];
+
+    },
+
+    /**
+    * Removes a json object from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeJSON
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeJSON: function (key) {
+
+        delete this._cache.json[key];
+
+    },
+
+    /**
+    * Removes a xml object from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeXML
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeXML: function (key) {
+
+        delete this._cache.xml[key];
+
+    },
+
+    /**
+    * Removes a video from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeVideo
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeVideo: function (key) {
+
+        delete this._cache.video[key];
+
+    },
+
+    /**
+    * Removes a shader from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeShader
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeShader: function (key) {
+
+        delete this._cache.shader[key];
+
+    },
+
+    /**
+    * Removes a Render Texture from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeRenderTexture
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeRenderTexture: function (key) {
+
+        delete this._cache.renderTexture[key];
+
+    },
+
+    /**
+    * Removes a Sprite Sheet from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeSpriteSheet
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeSpriteSheet: function (key) {
+
+        delete this._cache.spriteSheet[key];
+
+    },
+
+    /**
+    * Removes a Texture Atlas from the cache.
+    *
+    * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
+    * then it will persist in memory.
+    *
+    * @method Phaser.Cache#removeTextureAtlas
+    * @param {string} key - Key of the asset you want to remove.
+    */
+    removeTextureAtlas: function (key) {
+
+        delete this._cache.atlas[key];
+
+    },
+
+    /**
+    * Empties out all of the GL Textures from Images stored in the cache.
+    * This is called automatically when the WebGL context is lost and then restored.
+    *
+    * @method Phaser.Cache#clearGLTextures
+    * @protected
+    */
+    clearGLTextures: function () {
+
+        for (var key in this.cache.image)
+        {
+            this.cache.image[key].base._glTextures = [];
+        }
+
+    },
+
+    /**
+    * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`.
+    * This is then looked-up by the Cache.getURL and Cache.checkURL calls.
+    *
+    * @method Phaser.Cache#_resolveURL
+    * @private
+    * @param {string} url - The URL to resolve. This is appended to Loader.baseURL.
+    * @param {object} [data] - The data associated with the URL to be stored to the URL Map.
+    * @return {string} The resolved URL.
+    */
+    _resolveURL: function (url, data) {
+
+        if (!this.autoResolveURL)
+        {
+            return null;
+        }
+
+        this._urlResolver.src = this.game.load.baseURL + url;
+
+        this._urlTemp = this._urlResolver.src;
+
+        //  Ensure no request is actually made
+        this._urlResolver.src = '';
+
+        //  Record the URL to the map
+        if (data)
+        {
+            this._urlMap[this._urlTemp] = data;
+        }
+
+        return this._urlTemp;
+
+    },
+
+    /**
+    * Clears the cache. Removes every local cache object reference.
+    * If an object in the cache has a `destroy` method it will also be called.
+    *
+    * @method Phaser.Cache#destroy
+    */
+    destroy: function () {
+
+        for (var i = 0; i < this._cacheMap.length; i++)
+        {
+            var cache = this._cacheMap[i];
+
+            for (var key in cache)
+            {
+                if (key !== '__default' && key !== '__missing')
+                {
+                    if (cache[key]['destroy'])
+                    {
+                        cache[key].destroy();
+                    }
+
+                    delete cache[key];
+                }
+            }
+        }
+
+        this._urlMap = null;
+        this._urlResolver = null;
+        this._urlTemp = null;
+
+    }
+
+};
+
+Phaser.Cache.prototype.constructor = Phaser.Cache;
+
+/* jshint wsh:true */
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
+*
+* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks.
+*
+* Parallel loading (see {@link #enableParallel}) is supported and enabled by default.
+* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}.
+*
+* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and
+* [Shoebox](http://renderhjs.net/shoebox/)
+*
+* @class Phaser.Loader
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Loader = function (game) {
+
+    /**
+    * Local reference to game.
+    * @property {Phaser.Game} game
+    * @protected
+    */
+    this.game = game;
+
+    /**
+    * Local reference to the Phaser.Cache.
+    * @property {Phaser.Cache} cache
+    * @protected
+    */
+    this.cache = game.cache;
+
+    /**
+    * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state.
+    * @property {boolean} resetLocked
+    * @default
+    */
+    this.resetLocked = false;
+
+    /**
+    * True if the Loader is in the process of loading the queue.
+    * @property {boolean} isLoading
+    * @default
+    */
+    this.isLoading = false;
+
+    /**
+    * True if all assets in the queue have finished loading.
+    * @property {boolean} hasLoaded
+    * @default
+    */
+    this.hasLoaded = false;
+
+    /**
+    * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}.
+    *
+    * This property is an object containing: sprite, rect, direction, width and height
+    *
+    * @property {?object} preloadSprite
+    * @protected
+    */
+    this.preloadSprite = null;
+
+    /**
+    * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'.
+    * @property {boolean|string} crossOrigin
+    * @default
+    */
+    this.crossOrigin = false;
+
+    /**
+    * If you want to append a URL before the path of any asset you can set this here.
+    * Useful if allowing the asset base url to be configured outside of the game code.
+    * The string _must_ end with a "/".
+    *
+    * @property {string} baseURL
+    */
+    this.baseURL = '';
+
+    /**
+    * The value of `path`, if set, is placed before any _relative_ file path given. For example:
+    * 
+    * `load.path = "images/sprites/";
+    * load.image("ball", "ball.png");
+    * load.image("tree", "level1/oaktree.png");
+    * load.image("boom", "http://server.com/explode.png");`
+    *
+    * Would load the `ball` file from `images/sprites/ball.png` and the tree from 
+    * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL 
+    * given as it's an absolute URL.
+    *
+    * Please note that the path is added before the filename but *after* the baseURL (if set.)
+    * 
+    * The string _must_ end with a "/".
+    *
+    * @property {string} path
+    */
+    this.path = '';
+
+    /**
+    * This event is dispatched when the loading process starts: before the first file has been requested,
+    * but after all the initial packs have been loaded.
+    *
+    * @property {Phaser.Signal} onLoadStart
+    */
+    this.onLoadStart = new Phaser.Signal();
+
+    /**
+    * This event is dispatched when the final file in the load queue has either loaded or failed.
+    *
+    * @property {Phaser.Signal} onLoadComplete
+    */
+    this.onLoadComplete = new Phaser.Signal();
+
+    /**
+    * This event is dispatched when an asset pack has either loaded or failed to load.
+    *
+    * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue.
+    *
+    * Params: `(pack key, success?, total packs loaded, total packs)`
+    *
+    * @property {Phaser.Signal} onPackComplete
+    */
+    this.onPackComplete = new Phaser.Signal();
+
+    /**
+    * This event is dispatched immediately before a file starts loading.
+    * It's possible the file may fail (eg. download error, invalid format) after this event is sent.
+    *
+    * Params: `(progress, file key, file url)`
+    *
+    * @property {Phaser.Signal} onFileStart
+    */
+    this.onFileStart = new Phaser.Signal();
+
+    /**
+    * This event is dispatched when a file has either loaded or failed to load.
+    *
+    * Any function bound to this will receive the following parameters:
+    *
+    * progress, file key, success?, total loaded files, total files
+    *
+    * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load.
+    * 
+    * @property {Phaser.Signal} onFileComplete
+    */
+    this.onFileComplete = new Phaser.Signal();
+   
+    /**
+    * This event is dispatched when a file (or pack) errors as a result of the load request.
+    *
+    * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`.
+    *
+    * Params: `(file key, file)`
+    *
+    * @property {Phaser.Signal} onFileError
+    */
+    this.onFileError = new Phaser.Signal();
+
+    /**
+    * If true and if the browser supports XDomainRequest, it will be used in preference for XHR.
+    *
+    * This is only relevant for IE 9 and should _only_ be enabled for IE 9 clients when required by the server/CDN.
+    *
+    * @property {boolean} useXDomainRequest
+    * @deprecated This is only relevant for IE 9.
+    */
+    this.useXDomainRequest = false;
+
+    /**
+    * @private
+    * @property {boolean} _warnedAboutXDomainRequest - Control number of warnings for using XDR outside of IE 9.
+    */
+    this._warnedAboutXDomainRequest = false;
+
+    /**
+    * If true (the default) then parallel downloading will be enabled.
+    *
+    * To disable all parallel downloads this must be set to false prior to any resource being loaded.
+    *
+    * @property {integer} enableParallel
+    */
+    this.enableParallel = true;
+
+    /**
+    * The number of concurrent / parallel resources to try and fetch at once.
+    *
+    * Many current browsers limit 6 requests per domain; this is slightly conservative.
+    *
+    * @property {integer} maxParallelDownloads
+    * @protected
+    */
+    this.maxParallelDownloads = 4;
+
+    /**
+    * A counter: if more than zero, files will be automatically added as a synchronization point.
+    * @property {integer} _withSyncPointDepth;
+    */
+    this._withSyncPointDepth = 0;
+
+    /**
+    * Contains all the information for asset files (including packs) to load.
+    *
+    * File/assets are only removed from the list after all loading completes.
+    *
+    * @property {file[]} _fileList
+    * @private
+    */
+    this._fileList = [];
+
+    /**
+    * Inflight files (or packs) that are being fetched/processed.
+    *
+    * This means that if there are any files in the flight queue there should still be processing
+    * going on; it should only be empty before or after loading.
+    *
+    * The files in the queue may have additional properties added to them,
+    * including `requestObject` which is normally the associated XHR.
+    *
+    * @property {file[]} _flightQueue
+    * @private
+    */
+    this._flightQueue = [];
+
+    /**
+    * The offset into the fileList past all the complete (loaded or error) entries.
+    *
+    * @property {integer} _processingHead
+    * @private
+    */
+    this._processingHead = 0;
+
+    /**
+    * True when the first file (not pack) has loading started.
+    * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded.
+    *
+    * @property {boolean} _initialPacksLoaded
+    * @private
+    */
+    this._fileLoadStarted = false;
+
+    /**
+    * Total packs seen - adjusted when a pack is added.
+    * @property {integer} _totalPackCount
+    * @private
+    */
+    this._totalPackCount = 0;
+
+    /**
+    * Total files seen - adjusted when a file is added.
+    * @property {integer} _totalFileCount
+    * @private
+    */
+    this._totalFileCount = 0;
+    
+    /**
+    * Total packs loaded - adjusted just prior to `onPackComplete`.
+    * @property {integer} _loadedPackCount
+    * @private
+    */
+    this._loadedPackCount = 0;
+
+    /**
+    * Total files loaded - adjusted just prior to `onFileComplete`.
+    * @property {integer} _loadedFileCount
+    * @private
+    */
+    this._loadedFileCount = 0;
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Loader.PHYSICS_PHASER_JSON = 4;
+
+Phaser.Loader.prototype = {
+
+    /**
+    * Set a Sprite to be a "preload" sprite by passing it to this method.
+    *
+    * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
+    * This allows you to easily make loading bars for games.
+    *
+    * The sprite will automatically be made visible when calling this.
+    *
+    * @method Phaser.Loader#setPreloadSprite
+    * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load.
+    * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically.
+    */
+    setPreloadSprite: function (sprite, direction) {
+
+        direction = direction || 0;
+
+        this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null };
+
+        if (direction === 0)
+        {
+            //  Horizontal rect
+            this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height);
+        }
+        else
+        {
+            //  Vertical rect
+            this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1);
+        }
+
+        sprite.crop(this.preloadSprite.rect);
+
+        sprite.visible = true;
+
+    },
+
+    /**
+    * Called automatically by ScaleManager when the game resizes in RESIZE scalemode.
+    *
+    * This can be used to adjust the preloading sprite size, eg.
+    *
+    * @method Phaser.Loader#resize
+    * @protected
+    */
+    resize: function () {
+
+        if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height)
+        {
+            this.preloadSprite.rect.height = this.preloadSprite.sprite.height;
+        }
+
+    },
+
+    /**
+    * Check whether a file/asset with a specific key is queued to be loaded.
+    *
+    * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey}
+    *
+    * @method Phaser.Loader#checkKeyExists
+    * @param {string} type - The type asset you want to check.
+    * @param {string} key - Key of the asset you want to check.
+    * @return {boolean} Return true if exists, otherwise return false.
+    */
+    checkKeyExists: function (type, key) {
+
+        return this.getAssetIndex(type, key) > -1;
+
+    },
+
+    /**
+    * Get the queue-index of the file/asset with a specific key.
+    *
+    * Only assets in the download file queue will be found.
+    *
+    * @method Phaser.Loader#getAssetIndex
+    * @param {string} type - The type asset you want to check.
+    * @param {string} key - Key of the asset you want to check.
+    * @return {number} The index of this key in the filelist, or -1 if not found.
+    *     The index may change and should only be used immediately following this call
+    */
+    getAssetIndex: function (type, key) {
+
+        var bestFound = -1;
+
+        for (var i = 0; i < this._fileList.length; i++)
+        {
+            var file = this._fileList[i];
+
+            if (file.type === type && file.key === key)
+            {
+                bestFound = i;
+
+                // An already loaded/loading file may be superceded.
+                if (!file.loaded && !file.loading)
+                {
+                    break;
+                }
+            }
+        }
+
+        return bestFound;
+
+    },
+
+    /**
+    * Find a file/asset with a specific key.
+    *
+    * Only assets in the download file queue will be found.
+    *
+    * @method Phaser.Loader#getAsset
+    * @param {string} type - The type asset you want to check.
+    * @param {string} key - Key of the asset you want to check.
+    * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned.
+    *     The index may change and should only be used immediately following this call.
+    */
+    getAsset: function (type, key) {
+
+        var fileIndex = this.getAssetIndex(type, key);
+
+        if (fileIndex > -1)
+        {
+            return { index: fileIndex, file: this._fileList[fileIndex] };
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort.
+    *
+    * This will abort any loading and clear any queued assets.
+    *
+    * Optionally you can clear any associated events.
+    *
+    * @method Phaser.Loader#reset
+    * @protected
+    * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared.
+    * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them.
+    */
+    reset: function (hard, clearEvents) {
+
+        if (clearEvents === undefined) { clearEvents = false; }
+
+        if (this.resetLocked)
+        {
+            return;
+        }
+
+        if (hard)
+        {
+            this.preloadSprite = null;
+        }
+
+        this.isLoading = false;
+
+        this._processingHead = 0;
+        this._fileList.length = 0;
+        this._flightQueue.length = 0;
+
+        this._fileLoadStarted = false;
+        this._totalFileCount = 0;
+        this._totalPackCount = 0;
+        this._loadedPackCount = 0;
+        this._loadedFileCount = 0;
+
+        if (clearEvents)
+        {
+            this.onLoadStart.removeAll();
+            this.onLoadComplete.removeAll();
+            this.onPackComplete.removeAll();
+            this.onFileStart.removeAll();
+            this.onFileComplete.removeAll();
+            this.onFileError.removeAll();
+        }
+
+    },
+
+    /**
+    * Internal function that adds a new entry to the file list. Do not call directly.
+    *
+    * @method Phaser.Loader#addToFileList
+    * @protected
+    * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
+    * @param {string} key - The unique Cache ID key of this resource.
+    * @param {string} [url] - The URL the asset will be loaded from.
+    * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults.
+    * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead.
+    * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension.
+    * @return {Phaser.Loader} This instance of the Phaser Loader.
+    */
+    addToFileList: function (type, key, url, properties, overwrite, extension) {
+
+        if (overwrite === undefined) { overwrite = false; }
+        
+        if (key === undefined || key === '')
+        {
+            console.warn("Phaser.Loader: Invalid or no key given of type " + type);
+            return this;
+        }
+
+        if (url === undefined || url === null)
+        {
+            if (extension)
+            {
+                url = key + extension;
+            }
+            else
+            {
+                console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key);
+                return this;
+            }
+        }
+
+        var file = {
+            type: type,
+            key: key,
+            path: this.path,
+            url: url,
+            syncPoint: this._withSyncPointDepth > 0,
+            data: null,
+            loading: false,
+            loaded: false,
+            error: false
+        };
+
+        if (properties)
+        {
+            for (var prop in properties)
+            {
+                file[prop] = properties[prop];
+            }
+        }
+
+        var fileIndex = this.getAssetIndex(type, key);
+        
+        if (overwrite && fileIndex > -1)
+        {
+            var currentFile = this._fileList[fileIndex];
+
+            if (!currentFile.loading && !currentFile.loaded)
+            {
+                this._fileList[fileIndex] = file;
+            }
+            else
+            {
+                this._fileList.push(file);
+                this._totalFileCount++;
+            }
+        }
+        else if (fileIndex === -1)
+        {
+            this._fileList.push(file);
+            this._totalFileCount++;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
+    *
+    * @method Phaser.Loader#replaceInFileList
+    * @protected
+    * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
+    * @param {string} key - The unique Cache ID key of this resource.
+    * @param {string} url - The URL the asset will be loaded from.
+    * @param {object} properties - Any additional properties needed to load the file.
+    */
+    replaceInFileList: function (type, key, url, properties) {
+
+        return this.addToFileList(type, key, url, properties, true);
+
+    },
+
+    /**
+    * Add a JSON resource pack ('packfile') to the Loader.
+    *
+    * A packfile is a JSON file that contains a list of assets to the be loaded.
+    * Please see the example 'loader/asset pack' in the Phaser Examples repository.
+    *
+    * Packs are always put before the first non-pack file that is not loaded / loading.
+    * 
+    * This means that all packs added before any loading has started are added to the front
+    * of the file queue, in the order added.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    *
+    * @method Phaser.Loader#pack
+    * @param {string} key - Unique asset key of this resource pack.
+    * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter.
+    * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO
+    * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    pack: function (key, url, data, callbackContext) {
+
+        if (url === undefined) { url = null; }
+        if (data === undefined) { data = null; }
+        if (callbackContext === undefined) { callbackContext = null; }
+
+        if (!url && !data)
+        {
+            console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.');
+
+            return this;
+        }
+
+        var pack = {
+            type: 'packfile',
+            key: key,
+            url: url,
+            path: this.path,
+            syncPoint: true,
+            data: null,
+            loading: false,
+            loaded: false,
+            error: false,
+            callbackContext: callbackContext
+        };
+
+        //  A data object has been given
+        if (data)
+        {
+            if (typeof data === 'string')
+            {
+                data = JSON.parse(data);
+            }
+            
+            pack.data = data || {};
+
+            //  Already consider 'loaded'
+            pack.loaded = true;
+        }
+        
+        // Add before first non-pack/no-loaded ~ last pack from start prior to loading
+        // (Read one past for splice-to-end)
+        for (var i = 0; i < this._fileList.length + 1; i++)
+        {
+            var file = this._fileList[i];
+
+            if (!file || (!file.loaded && !file.loading && file.type !== 'packfile'))
+            {
+                this._fileList.splice(i, 1, pack);
+                this._totalPackCount++;
+                break;
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Adds an Image to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the image via `Cache.getImage(key)`
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * @method Phaser.Loader#image
+    * @param {string} key - Unique asset key of this image file.
+    * @param {string} [url] - URL of an image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
+    * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    image: function (key, url, overwrite) {
+
+        return this.addToFileList('image', key, url, undefined, overwrite, '.png');
+
+    },
+
+    /**
+    * Adds a Text file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getText(key)`
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * @method Phaser.Loader#text
+    * @param {string} key - Unique asset key of the text file.
+    * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
+    * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    text: function (key, url, overwrite) {
+
+        return this.addToFileList('text', key, url, undefined, overwrite, '.txt');
+
+    },
+
+    /**
+    * Adds a JSON file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
+    * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * @method Phaser.Loader#json
+    * @param {string} key - Unique asset key of the json file.
+    * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
+    * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    json: function (key, url, overwrite) {
+
+        return this.addToFileList('json', key, url, undefined, overwrite, '.json');
+
+    },
+
+    /**
+    * Adds a fragment shader file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getShader(key)`.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur"
+    * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * @method Phaser.Loader#shader
+    * @param {string} key - Unique asset key of the fragment file.
+    * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `<key>.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag".
+    * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    shader: function (key, url, overwrite) {
+
+        return this.addToFileList('shader', key, url, undefined, overwrite, '.frag');
+
+    },
+
+    /**
+    * Adds an XML file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getXML(key)`.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * @method Phaser.Loader#xml
+    * @param {string} key - Unique asset key of the xml file.
+    * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `<key>.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml".
+    * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    xml: function (key, url, overwrite) {
+
+        return this.addToFileList('xml', key, url, undefined, overwrite, '.xml');
+
+    },
+
+    /**
+    * Adds a JavaScript file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load!
+    *
+    * A callback, which will be invoked as the script tag has been created, can also be specified.
+    * The callback must return relevant `data`.
+    *
+    * @method Phaser.Loader#script
+    * @param {string} key - Unique asset key of the script file.
+    * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `<key>.js`, i.e. if `key` was "alien" then the URL will be "alien.js".
+    * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing.
+    * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    script: function (key, url, callback, callbackContext) {
+
+        if (callback === undefined) { callback = false; }
+
+        if (callback !== false && callbackContext === undefined) { callbackContext = this; }
+
+        return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js');
+
+    },
+
+    /**
+    * Adds a binary file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getBinary(key)`.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load.
+    * When the callback is called it will be passed 2 parameters: the key of the file and the file data.
+    *
+    * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it.
+    *
+    * @method Phaser.Loader#binary
+    * @param {string} key - Unique asset key of the binary file.
+    * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `<key>.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin".
+    * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it.
+    * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    binary: function (key, url, callback, callbackContext) {
+
+        if (callback === undefined) { callback = false; }
+
+        // Why is the default callback context the ..callback?
+        if (callback !== false && callbackContext === undefined) { callbackContext = callback; }
+
+        return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin');
+
+    },
+
+    /**
+    * Adds a Sprite Sheet to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    *
+    * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal
+    * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. 
+    * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas.
+    * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming
+    * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets.
+    * If you've got an atlas then use `Loader.atlas` instead.
+    * 
+    * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
+    * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
+    * If you do not desire this action then provide a URL.
+    *
+    * @method Phaser.Loader#spritesheet
+    * @param {string} key - Unique asset key of the sheet file.
+    * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
+    * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet.
+    * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet.
+    * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames.
+    * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
+    * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing) {
+
+        if (frameMax === undefined) { frameMax = -1; }
+        if (margin === undefined) { margin = 0; }
+        if (spacing === undefined) { spacing = 0; }
+
+        return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing }, false, '.png');
+
+    },
+
+    /**
+    * Adds an audio file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getSound(key)`.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    *
+    * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio.
+    * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system.
+    * The solution is to use a lower encoding rate such as 44100 Hz.
+    *
+    * @method Phaser.Loader#audio
+    * @param {string} key - Unique asset key of the audio file.
+    * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`.
+    *    If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected.
+    *    For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp3']`.
+    *    BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource.
+    * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
+    *    Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    audio: function (key, urls, autoDecode) {
+
+        if (this.game.sound.noAudio)
+        {
+            return this;
+        }
+
+        if (autoDecode === undefined) { autoDecode = true; }
+
+        if (typeof urls === 'string')
+        {
+            urls = [urls];
+        }
+
+        return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode });
+
+    },
+
+    /**
+    * Adds an audio sprite file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Audio Sprites are a combination of audio files and a JSON configuration.
+    * 
+    * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
+    * 
+    * Retrieve the file via `Cache.getSoundData(key)`.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    *
+    * @method Phaser.Loader#audiosprite
+    * @param {string} key - Unique asset key of the audio file.
+    * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL.
+    * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null.
+    * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null.
+    * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
+    *    Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    audiosprite: function(key, urls, jsonURL, jsonData, autoDecode) {
+
+        if (this.game.sound.noAudio)
+        {
+            return this;
+        }
+
+        if (jsonURL === undefined) { jsonURL = null; }
+        if (jsonData === undefined) { jsonData = null; }
+        if (autoDecode === undefined) { autoDecode = true; }
+
+        this.audio(key, urls, autoDecode);
+
+        if (jsonURL)
+        {
+            this.json(key + '-audioatlas', jsonURL);
+        }
+        else if (jsonData)
+        {
+            if (typeof jsonData === 'string')
+            {
+                jsonData = JSON.parse(jsonData);
+            }
+
+            this.cache.addJSON(key + '-audioatlas', '', jsonData);
+        }
+        else
+        {
+            console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object');
+        }
+
+        return this;
+
+    },
+
+
+    /**
+    * Adds a video file to the current load queue.
+    * 
+    * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getVideo(key)`.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    *
+    * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details.
+    *
+    * @method Phaser.Loader#video
+    * @param {string} key - Unique asset key of the video file.
+    * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`.
+    *    If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected.
+    *    For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp4']`.
+    *    BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource.
+    * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete.
+    *    'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion.
+    *    'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish.
+    *    'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the
+    *    browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`.
+    * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set.
+    *    Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2.
+    *    If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    video: function (key, urls, loadEvent, asBlob) {
+
+        if (loadEvent === undefined)
+        {
+            if (this.game.device.firefox)
+            {
+                loadEvent = 'loadeddata';
+            }
+            else
+            {
+                loadEvent = 'canplaythrough';
+            }
+        }
+
+        if (asBlob === undefined) { asBlob = false; }
+
+        if (typeof urls === 'string')
+        {
+            urls = [urls];
+        }
+
+        return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent });
+
+    },
+
+    /**
+    * Adds a Tile Map data file to the current load queue.
+    *
+    * You can choose to either load the data externally, by providing a URL to a json file.
+    * Or you can pass in a JSON object or String via the `data` parameter.
+    * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
+    * 
+    * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    * 
+    * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load.
+    * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that.
+    * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json".
+    * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead.
+    * 
+    * If you do not desire this action then provide a URL or data object.
+    *
+    * @method Phaser.Loader#tilemap
+    * @param {string} key - Unique asset key of the tilemap data.
+    * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "level1" then the URL will be "level1.json".
+    * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead.
+    * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    tilemap: function (key, url, data, format) {
+
+        if (url === undefined) { url = null; }
+        if (data === undefined) { data = null; }
+        if (format === undefined) { format = Phaser.Tilemap.CSV; }
+
+        if (!url && !data)
+        {
+            if (format === Phaser.Tilemap.CSV)
+            {
+                url = key + '.csv';
+            }
+            else
+            {
+                url = key + '.json';
+            }
+        }
+
+        //  A map data object has been given
+        if (data)
+        {
+            switch (format)
+            {
+                //  A csv string or object has been given
+                case Phaser.Tilemap.CSV:
+                    break;
+
+                //  A json string or object has been given
+                case Phaser.Tilemap.TILED_JSON:
+
+                    if (typeof data === 'string')
+                    {
+                        data = JSON.parse(data);
+                    }
+                    break;
+            }
+
+            this.cache.addTilemap(key, null, data, format);
+        }
+        else
+        {
+            this.addToFileList('tilemap', key, url, { format: format });
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Adds a physics data file to the current load queue.
+    *
+    * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively.
+    * 
+    * You can choose to either load the data externally, by providing a URL to a json file.
+    * Or you can pass in a JSON object or String via the `data` parameter.
+    * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
+    * 
+    * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    *
+    * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
+    * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
+    * 
+    * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that.
+    * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json".
+    * It will always use `.json` as the extension.
+    * 
+    * If you do not desire this action then provide a URL or data object.
+    *
+    * @method Phaser.Loader#physics
+    * @param {string} key - Unique asset key of the physics json data.
+    * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
+    * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead.
+    * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    physics: function (key, url, data, format) {
+
+        if (url === undefined) { url = null; }
+        if (data === undefined) { data = null; }
+        if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; }
+
+        if (!url && !data)
+        {
+            url = key + '.json';
+        }
+
+        //  A map data object has been given
+        if (data)
+        {
+            if (typeof data === 'string')
+            {
+                data = JSON.parse(data);
+            }
+
+            this.cache.addPhysicsData(key, null, data, format);
+        }
+        else
+        {
+            this.addToFileList('physics', key, url, { format: format });
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Adds Bitmap Font files to the current load queue.
+    * 
+    * To create the Bitmap Font files you can use:
+    *
+    * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
+    * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
+    * Littera (Web-based, free): http://kvazars.com/littera/
+    *
+    * You can choose to either load the data externally, by providing a URL to an xml file.
+    * Or you can pass in an XML object or String via the `xmlData` parameter.
+    * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache.
+    * 
+    * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    * 
+    * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load.
+    * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed.
+    * 
+    * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
+    * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png".
+    * The same is true for the xmlURL. If xmlURL isn't specified and no xmlData has been provided then the Loader will
+    * set the xmlURL to be the key. For example if the key is "megaFont" the xmlURL will be set to "megaFont.xml".
+    * 
+    * If you do not desire this action then provide URLs and / or a data object.
+    *
+    * @method Phaser.Loader#bitmapFont
+    * @param {string} key - Unique asset key of the bitmap font.
+    * @param {string} textureURL -  URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png".
+    * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json).
+    * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json).
+    * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
+    * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) {
+        if (textureURL === undefined || textureURL === null)
+        {
+            textureURL = key + '.png';
+        }
+
+        if (atlasURL === undefined) { atlasURL = null; }
+        if (atlasData === undefined) { atlasData = null; }
+        if (xSpacing === undefined) { xSpacing = 0; }
+        if (ySpacing === undefined) { ySpacing = 0; }
+
+        //  A URL to a json/xml atlas has been given
+        if (atlasURL)
+        {
+            this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing });
+        }
+        else
+        {
+            //  A stringified xml/json atlas has been given
+            if (typeof atlasData === 'string')
+            {
+                var json, xml;
+
+                try
+                {
+                    json = JSON.parse(atlasData);
+                }
+                catch ( e )
+                {
+                    xml = this.parseXml(atlasData);
+                }
+
+                if (!xml && !json)
+                {
+                    throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");
+                }
+
+                this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml,
+                    atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing });
+            }
+        }
+
+        return this;
+    },
+
+    /**
+    * Adds a Texture Atlas file to the current load queue.
+    *
+    * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format.
+    * 
+    * To create the Texture Atlas you can use tools such as:
+    *
+    * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
+    * [Shoebox](http://renderhjs.net/shoebox/)
+    * 
+    * If using Texture Packer we recommend you enable "Trim sprite names".
+    * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
+    *
+    * You can choose to either load the data externally, by providing a URL to a json file.
+    * Or you can pass in a JSON object or String via the `atlasData` parameter.
+    * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
+    * 
+    * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    * 
+    * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
+    * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
+    * 
+    * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
+    * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
+    * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
+    * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
+    * 
+    * If you do not desire this action then provide URLs and / or a data object.
+    *
+    * @method Phaser.Loader#atlasJSONArray
+    * @param {string} key - Unique asset key of the texture atlas file.
+    * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
+    * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
+    * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    atlasJSONArray: function (key, textureURL, atlasURL, atlasData) {
+
+        return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
+
+    },
+
+    /**
+    * Adds a Texture Atlas file to the current load queue.
+    *
+    * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format.
+    * 
+    * To create the Texture Atlas you can use tools such as:
+    *
+    * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
+    * [Shoebox](http://renderhjs.net/shoebox/)
+    * 
+    * If using Texture Packer we recommend you enable "Trim sprite names".
+    * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
+    *
+    * You can choose to either load the data externally, by providing a URL to a json file.
+    * Or you can pass in a JSON object or String via the `atlasData` parameter.
+    * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
+    * 
+    * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    * 
+    * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
+    * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
+    * 
+    * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
+    * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
+    * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
+    * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
+    * 
+    * If you do not desire this action then provide URLs and / or a data object.
+    *
+    * @method Phaser.Loader#atlasJSONHash
+    * @param {string} key - Unique asset key of the texture atlas file.
+    * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
+    * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
+    * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    atlasJSONHash: function (key, textureURL, atlasURL, atlasData) {
+
+        return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
+
+    },
+
+    /**
+    * Adds a Texture Atlas file to the current load queue.
+    *
+    * This call expects the atlas data to be in the Starling XML data format.
+    * 
+    * To create the Texture Atlas you can use tools such as:
+    *
+    * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
+    * [Shoebox](http://renderhjs.net/shoebox/)
+    *
+    * If using Texture Packer we recommend you enable "Trim sprite names".
+    * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
+    * 
+    * You can choose to either load the data externally, by providing a URL to an xml file.
+    * Or you can pass in an XML object or String via the `atlasData` parameter.
+    * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache.
+    * 
+    * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    * 
+    * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load.
+    * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed.
+    * 
+    * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
+    * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
+    * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
+    * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml".
+    * 
+    * If you do not desire this action then provide URLs and / or a data object.
+    *
+    * @method Phaser.Loader#atlasXML
+    * @param {string} key - Unique asset key of the texture atlas file.
+    * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
+    * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.xml".
+    * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    atlasXML: function (key, textureURL, atlasURL, atlasData) {
+
+        if (atlasURL === undefined) { atlasURL = null; }
+        if (atlasData === undefined) { atlasData = null; }
+
+        if (!atlasURL && !atlasData)
+        {
+            atlasURL = key + '.xml';
+        }
+
+        return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING);
+
+    },
+
+    /**
+    * Adds a Texture Atlas file to the current load queue.
+    *
+    * To create the Texture Atlas you can use tools such as:
+    *
+    * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
+    * [Shoebox](http://renderhjs.net/shoebox/)
+    *
+    * If using Texture Packer we recommend you enable "Trim sprite names".
+    * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
+    *
+    * You can choose to either load the data externally, by providing a URL to a json file.
+    * Or you can pass in a JSON object or String via the `atlasData` parameter.
+    * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
+    * 
+    * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
+    * 
+    * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
+    * 
+    * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
+    * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
+    * 
+    * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
+    * 
+    * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
+    * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
+    * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
+    * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
+    * 
+    * If you do not desire this action then provide URLs and / or a data object.
+    *
+    * @method Phaser.Loader#atlas
+    * @param {string} key - Unique asset key of the texture atlas file.
+    * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
+    * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
+    * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
+    * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    atlas: function (key, textureURL, atlasURL, atlasData, format) {
+
+        if (textureURL === undefined || textureURL === null)
+        {
+            textureURL = key + '.png';
+        }
+
+        if (atlasURL === undefined) { atlasURL = null; }
+        if (atlasData === undefined) { atlasData = null; }
+        if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; }
+
+        if (!atlasURL && !atlasData)
+        {
+            if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
+            {
+                atlasURL = key + '.xml';
+            }
+            else
+            {
+                atlasURL = key + '.json';
+            }
+        }
+
+        //  A URL to a json/xml file has been given
+        if (atlasURL)
+        {
+            this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format });
+        }
+        else
+        {
+            switch (format)
+            {
+                //  A json string or object has been given
+                case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY:
+
+                    if (typeof atlasData === 'string')
+                    {
+                        atlasData = JSON.parse(atlasData);
+                    }
+                    break;
+
+                //  An xml string or object has been given
+                case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING:
+
+                    if (typeof atlasData === 'string')
+                    {
+                        var xml = this.parseXml(atlasData);
+
+                        if (!xml)
+                        {
+                            throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
+                        }
+
+                        atlasData = xml;
+                    }
+                    break;
+            }
+
+            this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format });
+
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Add a synchronization point to the assets/files added within the supplied callback.
+    *
+    * A synchronization point denotes that an asset _must_ be completely loaded before
+    * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait
+    * for previous assets to load (unless they are sync-points). Resources, such as packs, may still
+    * be downloaded around sync-points, as long as they do not finalize loading.
+    *
+    * @method Phaser.Loader#withSyncPoints
+    * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader.
+    * @param {object} [callbackContext=(loader)] - Context for the callback.
+    * @return {Phaser.Loader} This Loader instance.
+    */
+    withSyncPoint: function (callback, callbackContext) {
+
+        this._withSyncPointDepth++;
+
+        try {
+            callback.call(callbackContext || this, this);
+        } finally {
+            this._withSyncPointDepth--;
+        }
+
+        return this;
+    },
+
+    /**
+    * Add a synchronization point to a specific file/asset in the load queue.
+    *
+    * This has no effect on already loaded assets.    
+    *
+    * @method Phaser.Loader#addSyncPoint
+    * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc).
+    * @param {string} key - Key of the file you want to turn into a sync point.
+    * @return {Phaser.Loader} This Loader instance.
+    * @see {@link Phaser.Loader#withSyncPoint withSyncPoint}
+    */
+    addSyncPoint: function (type, key) {
+
+        var asset = this.getAsset(type, key);
+
+        if (asset)
+        {
+            asset.file.syncPoint = true;
+        }
+
+        return this;
+    },
+
+    /**
+    * Remove a file/asset from the loading queue.
+    *
+    * A file that is loaded or has started loading cannot be removed.
+    *
+    * @method Phaser.Loader#removeFile
+    * @protected
+    * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
+    * @param {string} key - Key of the file you want to remove.
+    */
+    removeFile: function (type, key) {
+
+        var asset = this.getAsset(type, key);
+
+        if (asset)
+        {
+            if (!asset.loaded && !asset.loading)
+            {
+                this._fileList.splice(asset.index, 1);
+            }
+        }
+
+    },
+
+    /**
+    * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead.
+    *
+    * @method Phaser.Loader#removeAll
+    * @protected
+    */
+    removeAll: function () {
+
+        this._fileList.length = 0;
+        this._flightQueue.length = 0;
+
+    },
+
+    /**
+    * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so.
+    *
+    * @method Phaser.Loader#start
+    */
+    start: function () {
+
+        if (this.isLoading)
+        {
+            return;
+        }
+
+        this.hasLoaded = false;
+        this.isLoading = true;
+
+        this.updateProgress();
+
+        this.processLoadQueue();
+
+    },
+
+    /**
+    * Process the next item(s) in the file/asset queue.
+    *
+    * Process the queue and start loading enough items to fill up the inflight queue.
+    *
+    * If a sync-file is encountered then subsequent asset processing is delayed until it completes.
+    * The exception to this rule is that packfiles can be downloaded (but not processed) even if
+    * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel.
+    * such as during the start phaser.
+    *
+    * @method Phaser.Loader#processLoadQueue
+    * @private
+    */
+    processLoadQueue: function () {
+
+        if (!this.isLoading)
+        {
+            console.warn('Phaser.Loader - active loading canceled / reset');
+            this.finishedLoading(true);
+            return;
+        }
+
+        // Empty the flight queue as applicable
+        for (var i = 0; i < this._flightQueue.length; i++)
+        {
+            var file = this._flightQueue[i];
+            
+            if (file.loaded || file.error)
+            {
+                this._flightQueue.splice(i, 1);
+                i--;
+
+                file.loading = false;
+                file.requestUrl = null;
+                file.requestObject = null;
+
+                if (file.error)
+                {
+                    this.onFileError.dispatch(file.key, file);
+                }
+
+                if (file.type !== 'packfile')
+                {
+                    this._loadedFileCount++;
+                    this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount);
+                }
+                else if (file.type === 'packfile' && file.error)
+                {
+                    // Non-error pack files are handled when processing the file queue
+                    this._loadedPackCount++;
+                    this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount);
+                }
+
+            }
+        }
+
+        // When true further non-pack file downloads are suppressed
+        var syncblock = false;
+
+        var inflightLimit = this.enableParallel ? Phaser.Math.clamp(this.maxParallelDownloads, 1, 12) : 1;
+
+        for (var i = this._processingHead; i < this._fileList.length; i++)
+        {
+            var file = this._fileList[i];
+
+            // Pack is fetched (ie. has data) and is currently at the start of the process queue.
+            if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead)
+            {
+                // Processing the pack / adds more files
+                this.processPack(file);
+
+                this._loadedPackCount++;
+                this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount);
+            }
+
+            if (file.loaded || file.error)
+            {
+                // Item at the start of file list finished, can skip it in future
+                if (i === this._processingHead)
+                {
+                    this._processingHead = i + 1;
+                }
+            }
+            else if (!file.loading && this._flightQueue.length < inflightLimit)
+            {
+                // -> not loaded/failed, not loading
+                if (file.type === 'packfile' && !file.data)
+                {
+                    // Fetches the pack data: the pack is processed above as it reaches queue-start.
+                    // (Packs do not trigger onLoadStart or onFileStart.)
+                    this._flightQueue.push(file);
+                    file.loading = true;
+
+                    this.loadFile(file);
+                }
+                else if (!syncblock)
+                {
+                    if (!this._fileLoadStarted)
+                    {
+                        this._fileLoadStarted = true;
+                        this.onLoadStart.dispatch();
+                    }
+
+                    this._flightQueue.push(file);
+                    file.loading = true;
+                    this.onFileStart.dispatch(this.progress, file.key, file.url);
+                    
+                    this.loadFile(file);
+                }
+            }
+
+            if (!file.loaded && file.syncPoint)
+            {
+                syncblock = true;
+            }
+
+            // Stop looking if queue full - or if syncblocked and there are no more packs.
+            // (As only packs can be loaded around a syncblock)
+            if (this._flightQueue.length >= inflightLimit ||
+                (syncblock && this._loadedPackCount === this._totalPackCount))
+            {
+                break;
+            }
+        }
+
+        this.updateProgress();
+
+        // True when all items in the queue have been advanced over
+        // (There should be no inflight items as they are complete - loaded/error.)
+        if (this._processingHead >= this._fileList.length)
+        {
+            this.finishedLoading();
+        }
+        else if (!this._flightQueue.length)
+        {
+            // Flight queue is empty but file list is not done being processed.
+            // This indicates a critical internal error with no known recovery.
+            console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");
+
+            var _this = this;
+
+            setTimeout(function () {
+                _this.finishedLoading(true);
+            }, 2000);
+        }
+
+    },
+
+    /**
+    * The loading is all finished.
+    *
+    * @method Phaser.Loader#finishedLoading
+    * @private
+    * @param {boolean} [abnormal=true] - True if the loading finished abnormally.
+    */
+    finishedLoading: function (abnormal) {
+
+        if (this.hasLoaded)
+        {
+            return;
+        }
+
+        this.hasLoaded = true;
+        this.isLoading = false;
+
+        // If there were no files make sure to trigger the event anyway, for consistency
+        if (!abnormal && !this._fileLoadStarted)
+        {
+            this._fileLoadStarted = true;
+            this.onLoadStart.dispatch();
+        }
+
+        this.onLoadComplete.dispatch();
+
+        this.reset();
+
+        this.game.state.loadComplete();
+
+    },
+
+    /**
+    * Informs the loader that the given file resource has been fetched and processed;
+    * or such a request has failed.
+    *
+    * @method Phaser.Loader#asyncComplete
+    * @private
+    * @param {object} file
+    * @param {string} [error=''] - The error message, if any. No message implies no error.
+    */
+    asyncComplete: function (file, errorMessage) {
+
+        if (errorMessage === undefined) { errorMessage = ''; }
+
+        file.loaded = true;
+        file.error = !!errorMessage;
+
+        if (errorMessage)
+        {
+            file.errorMessage = errorMessage;
+
+            console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage);
+            // debugger;
+        }
+
+        this.processLoadQueue();
+
+    },
+
+    /**
+    * Process pack data. This will usually modify the file list.
+    *
+    * @method Phaser.Loader#processPack
+    * @private
+    * @param {object} pack
+    */
+    processPack: function (pack) {
+
+        var packData = pack.data[pack.key];
+
+        if (!packData)
+        {
+            console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key');
+            return;
+        }
+
+        for (var i = 0; i < packData.length; i++)
+        {
+            var file = packData[i];
+
+            switch (file.type)
+            {
+                case "image":
+                    this.image(file.key, file.url, file.overwrite);
+                    break;
+
+                case "text":
+                    this.text(file.key, file.url, file.overwrite);
+                    break;
+
+                case "json":
+                    this.json(file.key, file.url, file.overwrite);
+                    break;
+
+                case "xml":
+                    this.xml(file.key, file.url, file.overwrite);
+                    break;
+
+                case "script":
+                    this.script(file.key, file.url, file.callback, pack.callbackContext || this);
+                    break;
+
+                case "binary":
+                    this.binary(file.key, file.url, file.callback, pack.callbackContext || this);
+                    break;
+
+                case "spritesheet":
+                    this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
+                    break;
+
+                case "video":
+                    this.video(file.key, file.urls);
+                    break;
+
+                case "audio":
+                    this.audio(file.key, file.urls, file.autoDecode);
+                    break;
+
+                case "audiosprite":
+                    this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode);
+                    break;
+
+                case "tilemap":
+                    this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]);
+                    break;
+
+                case "physics":
+                    this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]);
+                    break;
+
+                case "bitmapFont":
+                    this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing);
+                    break;
+
+                case "atlasJSONArray":
+                    this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData);
+                    break;
+
+                case "atlasJSONHash":
+                    this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData);
+                    break;
+
+                case "atlasXML":
+                    this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData);
+                    break;
+
+                case "atlas":
+                    this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]);
+                    break;
+
+                case "shader":
+                    this.shader(file.key, file.url, file.overwrite);
+                    break;
+            }
+        }
+
+    },
+
+    /**
+    * Transforms the asset URL.
+    * The default implementation prepends the baseURL if the url doesn't being with http or //
+    *
+    * @method Phaser.Loader#transformUrl
+    * @protected
+    * @param {string} url - The url to transform.
+    * @param {object} file - The file object being transformed.
+    * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead.
+    */
+    transformUrl: function (url, file) {
+
+        if (!url)
+        {
+            return false;
+        }
+
+        if (url.substr(0, 4) === 'http' || url.substr(0, 2) === '//')
+        {
+            return url;
+        }
+        else
+        {
+            return this.baseURL + file.path + url;
+        }
+
+    },
+
+    /**
+    * Start fetching a resource.
+    *
+    * All code paths, async or otherwise, from this function must return to `asyncComplete`.
+    *
+    * @method Phaser.Loader#loadFile
+    * @private
+    * @param {object} file
+    */
+    loadFile: function (file) {
+
+        //  Image or Data?
+        switch (file.type)
+        {
+            case 'packfile':
+                this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete);
+                break;
+
+            case 'image':
+            case 'spritesheet':
+            case 'textureatlas':
+            case 'bitmapfont':
+                this.loadImageTag(file);
+                break;
+
+            case 'audio':
+                file.url = this.getAudioURL(file.url);
+
+                if (file.url)
+                {
+                    //  WebAudio or Audio Tag?
+                    if (this.game.sound.usingWebAudio)
+                    {
+                        this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
+                    }
+                    else if (this.game.sound.usingAudioTag)
+                    {
+                        this.loadAudioTag(file);
+                    }
+                }
+                else
+                {
+                    this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support');
+                }
+                break;
+
+            case 'video':
+                file.url = this.getVideoURL(file.url);
+
+                if (file.url)
+                {
+                    if (file.asBlob)
+                    {
+                        this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
+                    }
+                    else
+                    {
+                        this.loadVideoTag(file);
+                    }
+                }
+                else
+                {
+                    this.fileError(file, null, 'No supported video URL specified or device does not have video playback support');
+                }
+                break;
+
+            case 'json':
+
+                this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete);
+                break;
+
+            case 'xml':
+
+                this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete);
+                break;
+
+            case 'tilemap':
+
+                if (file.format === Phaser.Tilemap.TILED_JSON)
+                {
+                    this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete);
+                }
+                else if (file.format === Phaser.Tilemap.CSV)
+                {
+                    this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete);
+                }
+                else
+                {
+                    this.asyncComplete(file, "invalid Tilemap format: " + file.format);
+                }
+                break;
+
+            case 'text':
+            case 'script':
+            case 'shader':
+            case 'physics':
+                this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete);
+                break;
+
+            case 'binary':
+                this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
+                break;
+        }
+
+    },
+
+    /**
+    * Continue async loading through an Image tag.
+    * @private
+    */
+    loadImageTag: function (file) {
+
+        var _this = this;
+
+        file.data = new Image();
+        file.data.name = file.key;
+
+        if (this.crossOrigin)
+        {
+            file.data.crossOrigin = this.crossOrigin;
+        }
+        
+        file.data.onload = function () {
+            if (file.data.onload)
+            {
+                file.data.onload = null;
+                file.data.onerror = null;
+                _this.fileComplete(file);
+            }
+        };
+        file.data.onerror = function () {
+            if (file.data.onload)
+            {
+                file.data.onload = null;
+                file.data.onerror = null;
+                _this.fileError(file);
+            }
+        };
+
+        file.data.src = this.transformUrl(file.url, file);
+        
+        // Image is immediately-available/cached
+        if (file.data.complete && file.data.width && file.data.height)
+        {
+            file.data.onload = null;
+            file.data.onerror = null;
+            this.fileComplete(file);
+        }
+
+    },
+
+    /**
+    * Continue async loading through a Video tag.
+    * @private
+    */
+    loadVideoTag: function (file) {
+
+        var _this = this;
+
+        file.data = document.createElement("video");
+        file.data.name = file.key;
+        file.data.controls = false;
+        file.data.autoplay = false;
+        
+        var videoLoadEvent = function () {
+
+            file.data.removeEventListener(file.loadEvent, videoLoadEvent, false);
+            file.data.onerror = null;
+            file.data.canplay = true;
+            Phaser.GAMES[_this.game.id].load.fileComplete(file);
+
+        };
+
+        file.data.onerror = function () {
+            file.data.removeEventListener(file.loadEvent, videoLoadEvent, false);
+            file.data.onerror = null;
+            file.data.canplay = false;
+            _this.fileError(file);
+        };
+       
+        file.data.addEventListener(file.loadEvent, videoLoadEvent, false);
+
+        file.data.src = this.transformUrl(file.url, file);
+        file.data.load();
+
+    },
+
+    /**
+    * Continue async loading through an Audio tag.
+    * @private
+    */
+    loadAudioTag: function (file) {
+
+        var _this = this;
+
+        if (this.game.sound.touchLocked)
+        {
+            //  If audio is locked we can't do this yet, so need to queue this load request. Bum.
+            file.data = new Audio();
+            file.data.name = file.key;
+            file.data.preload = 'auto';
+            file.data.src = this.transformUrl(file.url, file);
+
+            this.fileComplete(file);
+        }
+        else
+        {
+            file.data = new Audio();
+            file.data.name = file.key;
+            
+            var playThroughEvent = function () {
+                file.data.removeEventListener('canplaythrough', playThroughEvent, false);
+                file.data.onerror = null;
+                // Why does this cycle through games?
+                Phaser.GAMES[_this.game.id].load.fileComplete(file);
+            };
+            file.data.onerror = function () {
+                file.data.removeEventListener('canplaythrough', playThroughEvent, false);
+                file.data.onerror = null;
+                _this.fileError(file);
+            };
+
+            file.data.preload = 'auto';
+            file.data.src = this.transformUrl(file.url, file);
+            file.data.addEventListener('canplaythrough', playThroughEvent, false);
+            file.data.load();
+        }
+
+    },
+
+    /**
+    * Starts the xhr loader.
+    *
+    * This is designed specifically to use with asset file processing.
+    *
+    * @method Phaser.Loader#xhrLoad
+    * @private
+    * @param {object} file - The file/pack to load.
+    * @param {string} url - The URL of the file.
+    * @param {string} type - The xhr responseType.
+    * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments.
+    * @param {function} [onerror=fileError]  The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments.
+    */
+    xhrLoad: function (file, url, type, onload, onerror) {
+
+        if (this.useXDomainRequest && window.XDomainRequest)
+        {
+            this.xhrLoadWithXDR(file, url, type, onload, onerror);
+            return;
+        }
+
+        var xhr = new XMLHttpRequest();
+        xhr.open("GET", url, true);
+        xhr.responseType = type;
+
+        onerror = onerror || this.fileError;
+
+        var _this = this;
+
+        xhr.onload = function () {
+
+            try {
+
+                return onload.call(_this, file, xhr);
+
+            } catch (e) {
+
+                //  If this was the last file in the queue and an error is thrown in the create method
+                //  then it's caught here, so be sure we don't carry on processing it
+
+                if (!_this.hasLoaded)
+                {
+                    _this.asyncComplete(file, e.message || 'Exception');
+                }
+                else
+                {
+                    if (window['console'])
+                    {
+                        console.error(e);
+                    }
+                }
+            }
+        };
+
+        xhr.onerror = function () {
+
+            try {
+
+                return onerror.call(_this, file, xhr);
+
+            } catch (e) {
+
+                if (!_this.hasLoaded)
+                {
+                    _this.asyncComplete(file, e.message || 'Exception');
+                }
+                else
+                {
+                    if (window['console'])
+                    {
+                        console.error(e);
+                    }
+                }
+
+            }
+        };
+
+        file.requestObject = xhr;
+        file.requestUrl = url;
+
+        xhr.send();
+
+    },
+
+    /**
+    * Starts the xhr loader - using XDomainRequest.
+    * This should _only_ be used with IE 9. Phaser does not support IE 8 and XDR is deprecated in IE 10.
+    * 
+    * This is designed specifically to use with asset file processing.
+    *
+    * @method Phaser.Loader#xhrLoad
+    * @private
+    * @param {object} file - The file/pack to load.
+    * @param {string} url - The URL of the file.
+    * @param {string} type - The xhr responseType.
+    * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments.
+    * @param {function} [onerror=fileError]  The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments.
+    * @deprecated This is only relevant for IE 9.
+    */
+    xhrLoadWithXDR: function (file, url, type, onload, onerror) {
+
+        // Special IE9 magic .. only
+        if (!this._warnedAboutXDomainRequest &&
+            (!this.game.device.ie || this.game.device.ieVersion >= 10))
+        {
+            this._warnedAboutXDomainRequest = true;
+            console.warn("Phaser.Loader - using XDomainRequest outside of IE 9");
+        }
+
+        // Ref: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
+        var xhr = new window.XDomainRequest();
+        xhr.open('GET', url, true);
+        xhr.responseType = type;
+
+        // XDomainRequest has a few quirks. Occasionally it will abort requests
+        // A way to avoid this is to make sure ALL callbacks are set even if not used
+        // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
+        xhr.timeout = 3000;
+
+        onerror = onerror || this.fileError;
+
+        var _this = this;
+
+        xhr.onerror = function () {
+            try {
+                return onerror.call(_this, file, xhr);
+            } catch (e) {
+                _this.asyncComplete(file, e.message || 'Exception');
+            }
+        };
+
+        xhr.ontimeout = function () {
+            try {
+                return onerror.call(_this, file, xhr);
+            } catch (e) {
+                _this.asyncComplete(file, e.message || 'Exception');
+            }
+        };
+
+        xhr.onprogress = function() {};
+
+        xhr.onload = function () {
+            try {
+                return onload.call(_this, file, xhr);
+            } catch (e) {
+                _this.asyncComplete(file, e.message || 'Exception');
+            }
+        };
+
+        file.requestObject = xhr;
+        file.requestUrl = url;
+
+        //  Note: The xdr.send() call is wrapped in a timeout to prevent an issue with the interface where some requests are lost
+        //  if multiple XDomainRequests are being sent at the same time.
+        setTimeout(function () {
+            xhr.send();
+        }, 0);
+
+    },
+
+    /**
+    * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play.
+    *
+    * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs.
+    *
+    * @method Phaser.Loader#getVideoURL
+    * @private
+    * @param {object[]|string[]} urls - See {@link #video} for format.
+    * @return {string} The URL to try and fetch; or null.
+    */
+    getVideoURL: function (urls) {
+
+        for (var i = 0; i < urls.length; i++)
+        {
+            var url = urls[i];
+            var videoType;
+
+            if (url.uri) // {uri: .., type: ..} pair
+            {
+                url = url.uri;
+                videoType = url.type;
+            }
+            else
+            {
+                // Assume direct-data URI can be played if not in a paired form; select immediately
+                if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0)
+                {
+                    return url;
+                }
+
+                if (url.indexOf("?") >= 0) // Remove query from URL
+                {
+                    url = url.substr(0, url.indexOf("?"));
+                }
+
+                var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1);
+
+                videoType = extension.toLowerCase();
+            }
+
+            if (this.game.device.canPlayVideo(videoType))
+            {
+                return urls[i];
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play.
+    *
+    * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs.
+    *
+    * @method Phaser.Loader#getAudioURL
+    * @private
+    * @param {object[]|string[]} urls - See {@link #audio} for format.
+    * @return {string} The URL to try and fetch; or null.
+    */
+    getAudioURL: function (urls) {
+
+        if (this.game.sound.noAudio)
+        {
+            return null;
+        }
+
+        for (var i = 0; i < urls.length; i++)
+        {
+            var url = urls[i];
+            var audioType;
+
+            if (url.uri) // {uri: .., type: ..} pair
+            {
+                url = url.uri;
+                audioType = url.type;
+            }
+            else
+            {
+                // Assume direct-data URI can be played if not in a paired form; select immediately
+                if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0)
+                {
+                    return url;
+                }
+
+                if (url.indexOf("?") >= 0) // Remove query from URL
+                {
+                    url = url.substr(0, url.indexOf("?"));
+                }
+
+                var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1);
+
+                audioType = extension.toLowerCase();
+            }
+
+            if (this.game.device.canPlayAudio(audioType))
+            {
+                return urls[i];
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Error occurred when loading a file.
+    *
+    * @method Phaser.Loader#fileError
+    * @private
+    * @param {object} file
+    * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags)
+    * @param {string} reason
+    */
+    fileError: function (file, xhr, reason) {
+
+        var url = file.requestUrl || this.transformUrl(file.url, file);
+        var message = 'error loading asset from URL ' + url;
+
+        if (!reason && xhr)
+        {
+            reason = xhr.status;
+        }
+
+        if (reason)
+        {
+            message = message + ' (' + reason + ')';
+        }
+
+        this.asyncComplete(file, message);
+
+    },
+
+    /**
+    * Called when a file/resources had been downloaded and needs to be processed further.
+    *
+    * @method Phaser.Loader#fileComplete
+    * @private
+    * @param {object} file - File loaded
+    * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags)
+    */
+    fileComplete: function (file, xhr) {
+
+        var loadNext = true;
+
+        switch (file.type)
+        {
+            case 'packfile':
+                
+                // Pack data must never be false-ish after it is fetched without error
+                var data = JSON.parse(xhr.responseText);
+                file.data = data || {};
+                break;
+
+            case 'image':
+
+                this.cache.addImage(file.key, file.url, file.data);
+                break;
+
+            case 'spritesheet':
+
+                this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
+                break;
+
+            case 'textureatlas':
+
+                if (file.atlasURL == null)
+                {
+                    this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
+                }
+                else
+                {
+                    //  Load the JSON or XML before carrying on with the next file
+                    loadNext = false;
+
+                    if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
+                    {
+                        this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete);
+                    }
+                    else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
+                    {
+                        this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete);
+                    }
+                    else
+                    {
+                        throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format);
+                    }
+                }
+                break;
+
+            case 'bitmapfont':
+
+                if (!file.atlasURL)
+                {
+                    this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing);
+                }
+                else
+                {
+                    //  Load the XML before carrying on with the next file
+                    loadNext = false;
+                    this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) {
+                        var json;
+
+                        try
+                        {
+                            // Try to parse as JSON, if it fails, then it's hopefully XML
+                            json = JSON.parse(xhr.responseText);
+                        }
+                        catch (e) {}
+
+                        if (!!json)
+                        {
+                            file.atlasType = 'json';
+                            this.jsonLoadComplete(file, xhr);
+                        }
+                        else
+                        {
+                            file.atlasType = 'xml';
+                            this.xmlLoadComplete(file, xhr);
+                        }
+                    });
+                }
+                break;
+
+            case 'video':
+
+                if (file.asBlob)
+                {
+                    try
+                    {
+                        file.data = new Blob([new Uint8Array(xhr.response)]);
+                    }
+                    catch (e)
+                    {
+                        throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key);
+                    }
+                }
+                
+                this.cache.addVideo(file.key, file.url, file.data, file.asBlob);
+                break;
+
+            case 'audio':
+
+                if (this.game.sound.usingWebAudio)
+                {
+                    file.data = xhr.response;
+
+                    this.cache.addSound(file.key, file.url, file.data, true, false);
+
+                    if (file.autoDecode)
+                    {
+                        this.game.sound.decode(file.key);
+                    }
+                }
+                else
+                {
+                    this.cache.addSound(file.key, file.url, file.data, false, true);
+                }
+                break;
+
+            case 'text':
+                file.data = xhr.responseText;
+                this.cache.addText(file.key, file.url, file.data);
+                break;
+
+            case 'shader':
+                file.data = xhr.responseText;
+                this.cache.addShader(file.key, file.url, file.data);
+                break;
+
+            case 'physics':
+                var data = JSON.parse(xhr.responseText);
+                this.cache.addPhysicsData(file.key, file.url, data, file.format);
+                break;
+
+            case 'script':
+                file.data = document.createElement('script');
+                file.data.language = 'javascript';
+                file.data.type = 'text/javascript';
+                file.data.defer = false;
+                file.data.text = xhr.responseText;
+                document.head.appendChild(file.data);
+                if (file.callback)
+                {
+                    file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText);
+                }
+                break;
+
+            case 'binary':
+                if (file.callback)
+                {
+                    file.data = file.callback.call(file.callbackContext, file.key, xhr.response);
+                }
+                else
+                {
+                    file.data = xhr.response;
+                }
+
+                this.cache.addBinary(file.key, file.data);
+
+                break;
+        }
+
+        if (loadNext)
+        {
+            this.asyncComplete(file);
+        }
+
+    },
+
+    /**
+    * Successfully loaded a JSON file - only used for certain types.
+    *
+    * @method Phaser.Loader#jsonLoadComplete
+    * @private
+    * @param {object} file - File associated with this request
+    * @param {XMLHttpRequest} xhr
+    */
+    jsonLoadComplete: function (file, xhr) {
+
+        var data = JSON.parse(xhr.responseText);
+
+        if (file.type === 'tilemap')
+        {
+            this.cache.addTilemap(file.key, file.url, data, file.format);
+        }
+        else if (file.type === 'bitmapfont')
+        {
+            this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing);
+        }
+        else if (file.type === 'json')
+        {
+            this.cache.addJSON(file.key, file.url, data);
+        }
+        else
+        {
+            this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
+        }
+
+        this.asyncComplete(file);
+    },
+
+    /**
+    * Successfully loaded a CSV file - only used for certain types.
+    *
+    * @method Phaser.Loader#csvLoadComplete
+    * @private
+    * @param {object} file - File associated with this request
+    * @param {XMLHttpRequest} xhr
+    */
+    csvLoadComplete: function (file, xhr) {
+
+        var data = xhr.responseText;
+
+        this.cache.addTilemap(file.key, file.url, data, file.format);
+
+        this.asyncComplete(file);
+
+    },
+
+    /**
+    * Successfully loaded an XML file - only used for certain types.
+    *
+    * @method Phaser.Loader#xmlLoadComplete
+    * @private
+    * @param {object} file - File associated with this request
+    * @param {XMLHttpRequest} xhr
+    */
+    xmlLoadComplete: function (file, xhr) {
+
+        // Always try parsing the content as XML, regardless of actually response type
+        var data = xhr.responseText;
+        var xml = this.parseXml(data);
+
+        if (!xml)
+        {
+            var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest
+            console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')');
+            this.asyncComplete(file, "invalid XML");
+            return;
+        }
+
+        if (file.type === 'bitmapfont')
+        {
+            this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing);
+        }
+        else if (file.type === 'textureatlas')
+        {
+            this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
+        }
+        else if (file.type === 'xml')
+        {
+            this.cache.addXML(file.key, file.url, xml);
+        }
+
+        this.asyncComplete(file);
+
+    },
+
+    /**
+    * Parses string data as XML.
+    *
+    * @method parseXml
+    * @private
+    * @param {string} data - The XML text to parse
+    * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document.
+    */
+    parseXml: function (data) {
+
+        var xml;
+
+        try
+        {
+            if (window['DOMParser'])
+            {
+                var domparser = new DOMParser();
+                xml = domparser.parseFromString(data, "text/xml");
+            }
+            else
+            {
+                xml = new ActiveXObject("Microsoft.XMLDOM");
+                // Why is this 'false'?
+                xml.async = 'false';
+                xml.loadXML(data);
+            }
+        }
+        catch (e)
+        {
+            xml = null;
+        }
+
+        if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
+        {
+            return null;
+        }
+        else
+        {
+            return xml;
+        }
+
+    },
+
+    /**
+    * Update the loading sprite progress.
+    *
+    * @method Phaser.Loader#nextFile
+    * @private
+    * @param {object} previousFile
+    * @param {boolean} success - Whether the previous asset loaded successfully or not.
+    */
+    updateProgress: function () {
+
+        if (this.preloadSprite)
+        {
+            if (this.preloadSprite.direction === 0)
+            {
+                this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress);
+            }
+            else
+            {
+                this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress);
+            }
+
+            if (this.preloadSprite.sprite)
+            {
+                this.preloadSprite.sprite.updateCrop();
+            }
+            else
+            {
+                //  We seem to have lost our sprite - maybe it was destroyed?
+                this.preloadSprite = null;
+            }
+        }
+
+    },
+
+    /**
+    * Returns the number of files that have already been loaded, even if they errored.
+    *
+    * @method Phaser.Loader#totalLoadedFiles
+    * @protected
+    * @return {number} The number of files that have already been loaded (even if they errored)
+    */
+    totalLoadedFiles: function () {
+
+        return this._loadedFileCount;
+
+    },
+
+    /**
+    * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded.
+    *
+    * @method Phaser.Loader#totalQueuedFiles
+    * @protected
+    * @return {number} The number of files that still remain in the load queue.
+    */
+    totalQueuedFiles: function () {
+
+        return this._totalFileCount - this._loadedFileCount;
+
+    },
+
+    /**
+    * Returns the number of asset packs that have already been loaded, even if they errored.
+    *
+    * @method Phaser.Loader#totalLoadedPacks
+    * @protected
+    * @return {number} The number of asset packs that have already been loaded (even if they errored)
+    */
+    totalLoadedPacks: function () {
+
+        return this._totalPackCount;
+
+    },
+
+    /**
+    * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded.
+    *
+    * @method Phaser.Loader#totalQueuedPacks
+    * @protected
+    * @return {number} The number of asset packs that still remain in the load queue.
+    */
+    totalQueuedPacks: function () {
+
+        return this._totalPackCount - this._loadedPackCount;
+
+    }
+
+};
+
+/**
+* The non-rounded load progress value (from 0.0 to 100.0).
+*
+* A general indicator of the progress.
+* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added.
+*
+* @name Phaser.Loader#progressFloat
+* @property {number}
+*/
+Object.defineProperty(Phaser.Loader.prototype, "progressFloat", {
+
+    get: function () {
+        var progress = (this._loadedFileCount / this._totalFileCount) * 100;
+        return Phaser.Math.clamp(progress || 0, 0, 100);
+    }
+
+});
+
+/**
+* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}.
+*
+* @name Phaser.Loader#progress
+* @property {integer}
+*/
+Object.defineProperty(Phaser.Loader.prototype, "progress", {
+
+    get: function () {
+        return Math.round(this.progressFloat);
+    }
+
+});
+
+Phaser.Loader.prototype.constructor = Phaser.Loader;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
+*
+* @class Phaser.LoaderParser
+*/
+Phaser.LoaderParser = {
+
+    /**
+    * Alias for xmlBitmapFont, for backwards compatibility.
+    * 
+    * @method Phaser.LoaderParser.bitmapFont
+    * @param {object} xml - XML data you want to parse.
+    * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
+    * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
+    * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
+    * @return {object} The parsed Bitmap Font data.
+    */
+    bitmapFont: function (xml, baseTexture, xSpacing, ySpacing) {
+
+        return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing);
+
+    },
+
+    /**
+    * Parse a Bitmap Font from an XML file.
+    *
+    * @method Phaser.LoaderParser.xmlBitmapFont
+    * @param {object} xml - XML data you want to parse.
+    * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
+    * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
+    * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
+    * @return {object} The parsed Bitmap Font data.
+    */
+    xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing) {
+
+        var data = {};
+        var info = xml.getElementsByTagName('info')[0];
+        var common = xml.getElementsByTagName('common')[0];
+
+        data.font = info.getAttribute('face');
+        data.size = parseInt(info.getAttribute('size'), 10);
+        data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
+        data.chars = {};
+
+        var letters = xml.getElementsByTagName('char');
+
+        for (var i = 0; i < letters.length; i++)
+        {
+            var charCode = parseInt(letters[i].getAttribute('id'), 10);
+
+            data.chars[charCode] = {
+                x: parseInt(letters[i].getAttribute('x'), 10),
+                y: parseInt(letters[i].getAttribute('y'), 10),
+                width: parseInt(letters[i].getAttribute('width'), 10),
+                height: parseInt(letters[i].getAttribute('height'), 10),
+                xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
+                yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
+                xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
+                kerning: {}
+            };
+        }
+
+        var kernings = xml.getElementsByTagName('kerning');
+
+        for (i = 0; i < kernings.length; i++)
+        {
+            var first = parseInt(kernings[i].getAttribute('first'), 10);
+            var second = parseInt(kernings[i].getAttribute('second'), 10);
+            var amount = parseInt(kernings[i].getAttribute('amount'), 10);
+
+            data.chars[second].kerning[first] = amount;
+        }
+
+        return this.finalizeBitmapFont(baseTexture, data);
+
+    },
+
+    /**
+    * Parse a Bitmap Font from a JSON file.
+    *
+    * @method Phaser.LoaderParser.jsonBitmapFont
+    * @param {object} json - JSON data you want to parse.
+    * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
+    * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
+    * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
+    * @return {object} The parsed Bitmap Font data.
+    */
+    jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing) {
+
+        var data = {
+            font: json.font.info._face,
+            size: parseInt(json.font.info._size, 10),
+            lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing,
+            chars: {}
+        };
+
+        json.font.chars["char"].forEach(
+
+            function parseChar(letter) {
+
+                var charCode = parseInt(letter._id, 10);
+
+                data.chars[charCode] = {
+                    x: parseInt(letter._x, 10),
+                    y: parseInt(letter._y, 10),
+                    width: parseInt(letter._width, 10),
+                    height: parseInt(letter._height, 10),
+                    xOffset: parseInt(letter._xoffset, 10),
+                    yOffset: parseInt(letter._yoffset, 10),
+                    xAdvance: parseInt(letter._xadvance, 10) + xSpacing,
+                    kerning: {}
+                };
+            }
+
+        );
+
+        if (json.font.kernings && json.font.kernings.kerning) {
+
+            json.font.kernings.kerning.forEach(
+
+                function parseKerning(kerning) {
+
+                    data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10);
+
+                }
+
+            );
+
+        }
+
+        return this.finalizeBitmapFont(baseTexture, data);
+
+    },
+
+    /**
+    * Finalize Bitmap Font parsing.
+    *
+    * @method Phaser.LoaderParser.finalizeBitmapFont
+    * @private
+    * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
+    * @param {object} bitmapFontData - Pre-parsed bitmap font data.
+    * @return {object} The parsed Bitmap Font data.
+    */
+    finalizeBitmapFont: function (baseTexture, bitmapFontData) {
+
+        Object.keys(bitmapFontData.chars).forEach(
+
+            function addTexture(charCode) {
+
+                var letter = bitmapFontData.chars[charCode];
+
+                letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height));
+
+            }
+
+        );
+
+        return bitmapFontData;
+
+    }
+};
+
+/**
+ * @author       Jeremy Dowell <jeremy@codevinsky.com>
+ * @author       Richard Davey <rich@photonstorm.com>
+ * @copyright    2015 Photon Storm Ltd.
+ * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+ */
+
+/**
+ * Audio Sprites are a combination of audio files and a JSON configuration.
+ * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
+ *
+ * @class Phaser.AudioSprite
+ * @constructor
+ * @param {Phaser.Game} game - Reference to the current game instance.
+ * @param {string} key - Asset key for the sound.
+ */
+Phaser.AudioSprite = function (game, key) {
+
+    /**
+    * A reference to the currently running Game.
+    * @property {Phaser.Game} game
+    */
+    this.game = game;
+
+    /**
+     * Asset key for the Audio Sprite.
+     * @property {string} key
+     */
+    this.key = key;
+
+    /**
+     * JSON audio atlas object.
+     * @property {object} config
+     */
+    this.config = this.game.cache.getJSON(key + '-audioatlas');
+
+    /**
+     * If a sound is set to auto play, this holds the marker key of it.
+     * @property {string} autoplayKey
+     */
+    this.autoplayKey = null;
+
+    /**
+     * Is a sound set to autoplay or not?
+     * @property {boolean} autoplay
+     * @default
+     */
+    this.autoplay = false;
+
+    /**
+     * An object containing the Phaser.Sound objects for the Audio Sprite.
+     * @property {object} sounds
+     */
+    this.sounds = {};
+
+    for (var k in this.config.spritemap)
+    {
+        var marker = this.config.spritemap[k];
+        var sound = this.game.add.sound(this.key);
+        
+        sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop);
+        
+        this.sounds[k] = sound;
+    }
+
+    if (this.config.autoplay)
+    {
+        this.autoplayKey = this.config.autoplay;
+        this.play(this.autoplayKey);
+        this.autoplay = this.sounds[this.autoplayKey];
+    }
+
+};
+
+Phaser.AudioSprite.prototype = {
+
+    /**
+     * Play a sound with the given name.
+     * 
+     * @method Phaser.AudioSprite#play
+     * @param {string} [marker] - The name of sound to play
+     * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
+     * @return {Phaser.Sound} This sound instance.
+     */
+    play: function (marker, volume) {
+
+        if (volume === undefined) { volume = 1; }
+
+        return this.sounds[marker].play(marker, null, volume);
+
+    },
+
+    /**
+     * Stop a sound with the given name.
+     * 
+     * @method Phaser.AudioSprite#stop
+     * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite.
+     */
+    stop: function (marker) {
+
+        if (!marker)
+        {
+            for (var key in this.sounds)
+            {
+                this.sounds[key].stop();
+            }
+        }
+        else
+        {
+            this.sounds[marker].stop();
+        }
+
+    },
+
+    /**
+     * Get a sound with the given name.
+     * 
+     * @method Phaser.AudioSprite#get
+     * @param {string} marker - The name of sound to get.
+     * @return {Phaser.Sound} The sound instance.
+     */
+    get: function(marker) {
+
+        return this.sounds[marker];
+
+    }
+
+};
+
+Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Sound class constructor.
+*
+* @class Phaser.Sound
+* @constructor
+* @param {Phaser.Game} game - Reference to the current game instance.
+* @param {string} key - Asset key for the sound.
+* @param {number} [volume=1] - Default value for the volume, between 0 and 1.
+* @param {boolean} [loop=false] - Whether or not the sound will loop.
+*/
+Phaser.Sound = function (game, key, volume, loop, connect) {
+
+    if (volume === undefined) { volume = 1; }
+    if (loop === undefined) { loop = false; }
+    if (connect === undefined) { connect = game.sound.connectToMaster; }
+
+    /**
+    * A reference to the currently running Game.
+    * @property {Phaser.Game} game
+    */
+    this.game = game;
+
+    /**
+    * @property {string} name - Name of the sound.
+    */
+    this.name = key;
+
+    /**
+    * @property {string} key - Asset key for the sound.
+    */
+    this.key = key;
+
+    /**
+    * @property {boolean} loop - Whether or not the sound or current sound marker will loop.
+    */
+    this.loop = loop;
+
+    /**
+    * @property {number} volume - The sound or sound marker volume. A value between 0 (silence) and 1 (full volume).
+    */
+    this.volume = volume;
+
+    /**
+    * @property {object} markers - The sound markers.
+    */
+    this.markers = {};
+
+    /**
+    * @property {AudioContext} context - Reference to the AudioContext instance.
+    */
+    this.context = null;
+
+    /**
+    * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically.
+    */
+    this.autoplay = false;
+
+    /**
+    * @property {number} totalDuration - The total duration of the sound in seconds.
+    */
+    this.totalDuration = 0;
+
+    /**
+    * @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker)
+    * @default
+    */
+    this.startTime = 0;
+
+    /**
+    * @property {number} currentTime - The current time the sound is at.
+    */
+    this.currentTime = 0;
+
+    /**
+    * @property {number} duration - The duration of the current sound marker in seconds.
+    */
+    this.duration = 0;
+
+    /**
+    * @property {number} durationMS - The duration of the current sound marker in ms.
+    */
+    this.durationMS = 0;
+
+    /**
+    * @property {number} position - The position of the current sound marker.
+    */
+    this.position = 0;
+
+    /**
+    * @property {number} stopTime - The time the sound stopped.
+    */
+    this.stopTime = 0;
+
+    /**
+    * @property {boolean} paused - true if the sound is paused, otherwise false.
+    * @default
+    */
+    this.paused = false;
+
+    /**
+    * @property {number} pausedPosition - The position the sound had reached when it was paused.
+    */
+    this.pausedPosition = 0;
+
+    /**
+    * @property {number} pausedTime - The game time at which the sound was paused.
+    */
+    this.pausedTime = 0;
+
+    /**
+    * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false.
+    * @default
+    */
+    this.isPlaying = false;
+
+    /**
+    * @property {string} currentMarker - The string ID of the currently playing marker, if any.
+    * @default
+    */
+    this.currentMarker = '';
+
+    /**
+    * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut.
+    */
+    this.fadeTween = null;
+
+    /**
+    * @property {boolean} pendingPlayback - true if the sound file is pending playback
+    * @readonly
+    */
+    this.pendingPlayback = false;
+
+    /**
+    * @property {boolean} override - if true when you play this sound it will always start from the beginning.
+    * @default
+    */
+    this.override = false;
+
+    /**
+    * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels.
+    * @default
+    */
+    this.allowMultiple = false;
+
+    /**
+    * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
+    * @readonly
+    */
+    this.usingWebAudio = this.game.sound.usingWebAudio;
+
+    /**
+    * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
+    */
+    this.usingAudioTag = this.game.sound.usingAudioTag;
+
+    /**
+    * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode.
+    */
+    this.externalNode = null;
+
+    /**
+    * @property {object} masterGainNode - The master gain node in a Web Audio system.
+    */
+    this.masterGainNode = null;
+
+    /**
+    * @property {object} gainNode - The gain node in a Web Audio system.
+    */
+    this.gainNode = null;
+
+    /**
+    * @property {object} _sound - Internal var.
+    * @private
+    */
+    this._sound = null;
+
+    if (this.usingWebAudio)
+    {
+        this.context = this.game.sound.context;
+        this.masterGainNode = this.game.sound.masterGain;
+
+        if (this.context.createGain === undefined)
+        {
+            this.gainNode = this.context.createGainNode();
+        }
+        else
+        {
+            this.gainNode = this.context.createGain();
+        }
+
+        this.gainNode.gain.value = volume * this.game.sound.volume;
+
+        if (connect)
+        {
+            this.gainNode.connect(this.masterGainNode);
+        }
+    }
+    else if (this.usingAudioTag)
+    {
+        if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key))
+        {
+            this._sound = this.game.cache.getSoundData(key);
+            this.totalDuration = 0;
+
+            if (this._sound.duration)
+            {
+                this.totalDuration = this._sound.duration;
+            }
+        }
+        else
+        {
+            this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this);
+        }
+    }
+
+    /**
+    * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files)
+    */
+    this.onDecoded = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played.
+    */
+    this.onPlay = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused.
+    */
+    this.onPause = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state.
+    */
+    this.onResume = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback.
+    */
+    this.onLoop = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback.
+    */
+    this.onStop = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onMute - The onMouse event is dispatched when this sound is muted.
+    */
+    this.onMute = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback.
+    */
+    this.onMarkerComplete = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out.
+    */
+    this.onFadeComplete = new Phaser.Signal();
+
+    /**
+    * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
+    * @private
+    */
+    this._volume = volume;
+
+    /**
+    * @property {any} _buffer - Decoded data buffer / Audio tag.
+    * @private
+    */
+    this._buffer = null;
+
+    /**
+    * @property {boolean} _muted - Boolean indicating whether the sound is muted or not.
+    * @private
+    */
+    this._muted = false;
+
+    /**
+    * @property {number} _tempMarker - Internal marker var.
+    * @private
+    */
+    this._tempMarker = 0;
+
+    /**
+    * @property {number} _tempPosition - Internal marker var.
+    * @private
+    */
+    this._tempPosition = 0;
+
+    /**
+    * @property {number} _tempVolume - Internal marker var.
+    * @private
+    */
+    this._tempVolume = 0;
+
+    /**
+    * @property {number} _muteVolume - Internal cache var.
+    * @private
+    */
+    this._muteVolume = 0;
+
+    /**
+    * @property {boolean} _tempLoop - Internal cache var.
+    * @private
+    */
+    this._tempLoop = 0;
+
+    /**
+    * @property {boolean} _paused - Was this sound paused via code or a game event?
+    * @private
+    */
+    this._paused = false;
+
+    /**
+    * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched?
+    * @private
+    */
+    this._onDecodedEventDispatched = false;
+
+};
+
+Phaser.Sound.prototype = {
+
+    /**
+    * Called automatically when this sound is unlocked.
+    * @method Phaser.Sound#soundHasUnlocked
+    * @param {string} key - The Phaser.Cache key of the sound file to check for decoding.
+    * @protected
+    */
+    soundHasUnlocked: function (key) {
+
+        if (key === this.key)
+        {
+            this._sound = this.game.cache.getSoundData(this.key);
+            this.totalDuration = this._sound.duration;
+        }
+
+    },
+
+    /**
+    * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration.
+    * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
+    *
+    * @method Phaser.Sound#addMarker
+    * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc.
+    * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
+    * @param {number} duration - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
+    * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume).
+    * @param {boolean} [loop=false] - Sets if the sound will loop or not.
+    */
+    addMarker: function (name, start, duration, volume, loop) {
+
+        if (volume === undefined || volume === null) { volume = 1; }
+        if (loop === undefined) { loop = false; }
+
+        this.markers[name] = {
+            name: name,
+            start: start,
+            stop: start + duration,
+            volume: volume,
+            duration: duration,
+            durationMS: duration * 1000,
+            loop: loop
+        };
+
+    },
+
+    /**
+    * Removes a marker from the sound.
+    * @method Phaser.Sound#removeMarker
+    * @param {string} name - The key of the marker to remove.
+    */
+    removeMarker: function (name) {
+
+        delete this.markers[name];
+
+    },
+
+    /**
+    * Called automatically by the AudioContext when the sound stops playing.
+    * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite.
+    * 
+    * @method Phaser.Sound#onEndedHandler
+    * @protected
+    */
+    onEndedHandler: function () {
+
+        this.isPlaying = false;
+        this.stop();
+
+    },
+
+    /**
+    * Called automatically by Phaser.SoundManager.
+    * @method Phaser.Sound#update
+    * @protected
+    */
+    update: function () {
+
+        if (!this.game.cache.checkSoundKey(this.key))
+        {
+            this.destroy();
+            return;
+        }
+
+        if (this.isDecoded && !this._onDecodedEventDispatched)
+        {
+            this.onDecoded.dispatch(this);
+            this._onDecodedEventDispatched = true;
+        }
+
+        if (this.pendingPlayback && this.game.cache.isSoundReady(this.key))
+        {
+            this.pendingPlayback = false;
+            this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop);
+        }
+
+        if (this.isPlaying)
+        {
+            this.currentTime = this.game.time.time - this.startTime;
+
+            if (this.currentTime >= this.durationMS)
+            {
+                if (this.usingWebAudio)
+                {
+                    if (this.loop)
+                    {
+                        //  won't work with markers, needs to reset the position
+                        this.onLoop.dispatch(this);
+
+                        if (this.currentMarker === '')
+                        {
+                            this.currentTime = 0;
+                            this.startTime = this.game.time.time;
+                        }
+                        else
+                        {
+                            this.onMarkerComplete.dispatch(this.currentMarker, this);
+                            this.play(this.currentMarker, 0, this.volume, true, true);
+                        }
+                    }
+                    else
+                    {
+                        //  Stop if we're using an audio marker, otherwise we let onended handle it
+                        if (this.currentMarker !== '')
+                        {
+                            this.stop();
+                        }
+                    }
+                }
+                else
+                {
+                    if (this.loop)
+                    {
+                        this.onLoop.dispatch(this);
+                        this.play(this.currentMarker, 0, this.volume, true, true);
+                    }
+                    else
+                    {
+                        this.stop();
+                    }
+                }
+            }
+        }
+    },
+
+    /**
+     * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters.
+     *
+     * @method Phaser.Sound#loopFull
+     * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
+     * @return {Phaser.Sound} This sound instance.
+     */
+    loopFull: function (volume) {
+
+        this.play(null, 0, volume, true);
+
+    },
+
+    /**
+    * Play this sound, or a marked section of it.
+    * 
+    * @method Phaser.Sound#play
+    * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
+    * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
+    * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
+    * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based.
+    * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning.
+    * @return {Phaser.Sound} This sound instance.
+    */
+    play: function (marker, position, volume, loop, forceRestart) {
+
+        if (marker === undefined || marker === false || marker === null) { marker = ''; }
+        if (forceRestart === undefined) { forceRestart = true; }
+
+        if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override)
+        {
+            //  Use Restart instead
+            return this;
+        }
+
+        if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart))
+        {
+            if (this.usingWebAudio)
+            {
+                if (this.externalNode)
+                {
+                    this._sound.disconnect(this.externalNode);
+                }
+                else
+                {
+                    this._sound.disconnect(this.gainNode);
+                }
+
+                if (this._sound.stop === undefined)
+                {
+                    this._sound.noteOff(0);
+                }
+                else
+                {
+                    try {
+                        this._sound.stop(0);
+                    }
+                    catch (e) {
+                    }
+                }
+            }
+            else if (this.usingAudioTag)
+            {
+                this._sound.pause();
+                this._sound.currentTime = 0;
+            }
+        }
+
+        if (marker === '' && Object.keys(this.markers).length > 0)
+        {
+            //  If they didn't specify a marker but this is an audio sprite, 
+            //  we should never play the entire thing
+            return this;
+        }
+
+        if (marker !== '')
+        {
+            this.currentMarker = marker;
+
+            if (this.markers[marker])
+            {
+                //  Playing a marker? Then we default to the marker values
+                this.position = this.markers[marker].start;
+                this.volume = this.markers[marker].volume;
+                this.loop = this.markers[marker].loop;
+                this.duration = this.markers[marker].duration;
+                this.durationMS = this.markers[marker].durationMS;
+
+                if (typeof volume !== 'undefined')
+                {
+                    this.volume = volume;
+                }
+
+                if (typeof loop !== 'undefined')
+                {
+                    this.loop = loop;
+                }
+
+                this._tempMarker = marker;
+                this._tempPosition = this.position;
+                this._tempVolume = this.volume;
+                this._tempLoop = this.loop;
+            }
+            else
+            {
+                // console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist");
+                return this;
+            }
+        }
+        else
+        {
+            position = position || 0;
+
+            if (volume === undefined) { volume = this._volume; }
+            if (loop === undefined) { loop = this.loop; }
+
+            this.position = position;
+            this.volume = volume;
+            this.loop = loop;
+            this.duration = 0;
+            this.durationMS = 0;
+
+            this._tempMarker = marker;
+            this._tempPosition = position;
+            this._tempVolume = volume;
+            this._tempLoop = loop;
+        }
+
+        if (this.usingWebAudio)
+        {
+            //  Does the sound need decoding?
+            if (this.game.cache.isSoundDecoded(this.key))
+            {
+                this._sound = this.context.createBufferSource();
+
+                if (this.externalNode)
+                {
+                    this._sound.connect(this.externalNode);
+                }
+                else
+                {
+                    this._sound.connect(this.gainNode);
+                }
+
+                this._buffer = this.game.cache.getSoundData(this.key);
+                this._sound.buffer = this._buffer;
+
+                if (this.loop && marker === '')
+                {
+                    this._sound.loop = true;
+                }
+
+                if (!this.loop && marker === '')
+                {
+                    this._sound.onended = this.onEndedHandler.bind(this);
+                }
+
+                this.totalDuration = this._sound.buffer.duration;
+
+                if (this.duration === 0)
+                {
+                    this.duration = this.totalDuration;
+                    this.durationMS = Math.ceil(this.totalDuration * 1000);
+                }
+
+                //  Useful to cache this somewhere perhaps?
+                if (this._sound.start === undefined)
+                {
+                    this._sound.noteGrainOn(0, this.position, this.duration);
+                }
+                else
+                {
+                    if (this.loop && marker === '')
+                    {
+                        this._sound.start(0, 0);
+                    }
+                    else
+                    {
+                        this._sound.start(0, this.position, this.duration);
+                    }
+                }
+
+                this.isPlaying = true;
+                this.startTime = this.game.time.time;
+                this.currentTime = 0;
+                this.stopTime = this.startTime + this.durationMS;
+                this.onPlay.dispatch(this);
+            }
+            else
+            {
+                this.pendingPlayback = true;
+
+                if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false)
+                {
+                    this.game.sound.decode(this.key, this);
+                }
+            }
+        }
+        else
+        {
+            if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked)
+            {
+                this.game.cache.reloadSound(this.key);
+                this.pendingPlayback = true;
+            }
+            else
+            {
+                if (this._sound && (this.game.device.cocoonJS || this._sound.readyState === 4))
+                {
+                    this._sound.play();
+                    //  This doesn't become available until you call play(), wonderful ...
+                    this.totalDuration = this._sound.duration;
+
+                    if (this.duration === 0)
+                    {
+                        this.duration = this.totalDuration;
+                        this.durationMS = this.totalDuration * 1000;
+                    }
+
+                    this._sound.currentTime = this.position;
+                    this._sound.muted = this._muted;
+
+                    if (this._muted)
+                    {
+                        this._sound.volume = 0;
+                    }
+                    else
+                    {
+                        this._sound.volume = this._volume;
+                    }
+
+                    this.isPlaying = true;
+                    this.startTime = this.game.time.time;
+                    this.currentTime = 0;
+                    this.stopTime = this.startTime + this.durationMS;
+                    this.onPlay.dispatch(this);
+                }
+                else
+                {
+                    this.pendingPlayback = true;
+                }
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Restart the sound, or a marked section of it.
+    *
+    * @method Phaser.Sound#restart
+    * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
+    * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
+    * @param {number} [volume=1] - Volume of the sound you want to play.
+    * @param {boolean} [loop=false] - Loop when it finished playing?
+    */
+    restart: function (marker, position, volume, loop) {
+
+        marker = marker || '';
+        position = position || 0;
+        volume = volume || 1;
+        if (loop === undefined) { loop = false; }
+
+        this.play(marker, position, volume, loop, true);
+
+    },
+
+    /**
+    * Pauses the sound.
+    *
+    * @method Phaser.Sound#pause
+    */
+    pause: function () {
+
+        if (this.isPlaying && this._sound)
+        {
+            this.paused = true;
+            this.pausedPosition = this.currentTime;
+            this.pausedTime = this.game.time.time;
+            this.onPause.dispatch(this);
+            this.stop();
+        }
+
+    },
+
+    /**
+    * Resumes the sound.
+    *
+    * @method Phaser.Sound#resume
+    */
+    resume: function () {
+
+        if (this.paused && this._sound)
+        {
+            if (this.usingWebAudio)
+            {
+                var p = this.position + (this.pausedPosition / 1000);
+
+                this._sound = this.context.createBufferSource();
+                this._sound.buffer = this._buffer;
+
+                if (this.externalNode)
+                {
+                    this._sound.connect(this.externalNode);
+                }
+                else
+                {
+                    this._sound.connect(this.gainNode);
+                }
+
+                if (this.loop)
+                {
+                    this._sound.loop = true;
+                }
+
+                if (!this.loop && this.currentMarker === '')
+                {
+                    this._sound.onended = this.onEndedHandler.bind(this);
+                }
+
+                var duration = this.duration - (this.pausedPosition / 1000);
+
+                if (this._sound.start === undefined)
+                {
+                    this._sound.noteGrainOn(0, p, duration);
+                    //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
+                }
+                else
+                {
+                    if (this.loop && this.game.device.chrome)
+                    {
+                        //  Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099
+                        if (this.game.device.chromeVersion === 42)
+                        {
+                            this._sound.start(0);
+                        }
+                        else
+                        {
+                            this._sound.start(0, p);
+                        }
+                    }
+                    else
+                    {
+                        this._sound.start(0, p, duration);
+                    }
+                }
+            }
+            else
+            {
+                this._sound.play();
+            }
+
+            this.isPlaying = true;
+            this.paused = false;
+            this.startTime += (this.game.time.time - this.pausedTime);
+            this.onResume.dispatch(this);
+        }
+
+    },
+
+    /**
+    * Stop playing this sound.
+    *
+    * @method Phaser.Sound#stop
+    */
+    stop: function () {
+
+        if (this.isPlaying && this._sound)
+        {
+            if (this.usingWebAudio)
+            {
+                if (this.externalNode)
+                {
+                    this._sound.disconnect(this.externalNode);
+                }
+                else
+                {
+                    this._sound.disconnect(this.gainNode);
+                }
+
+                if (this._sound.stop === undefined)
+                {
+                    this._sound.noteOff(0);
+                }
+                else
+                {
+                    try {
+                        this._sound.stop(0);
+                    }
+                    catch (e)
+                    {
+                        //  Thanks Android 4.4
+                    }
+                }
+            }
+            else if (this.usingAudioTag)
+            {
+                this._sound.pause();
+                this._sound.currentTime = 0;
+            }
+        }
+
+        this.pendingPlayback = false;
+        this.isPlaying = false;
+        var prevMarker = this.currentMarker;
+
+        if (this.currentMarker !== '')
+        {
+            this.onMarkerComplete.dispatch(this.currentMarker, this);
+        }
+
+        this.currentMarker = '';
+
+        if (this.fadeTween !== null)
+        {
+            this.fadeTween.stop();
+        }
+
+        if (!this.paused)
+        {
+            this.onStop.dispatch(this, prevMarker);
+        }
+
+    },
+
+    /**
+     * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero.
+     * Then increases the volume from 0 to 1 over the duration specified.
+     *
+     * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
+     * and the final volume (1) as the second parameter.
+     *
+     * @method Phaser.Sound#fadeIn
+     * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in.
+     * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat.
+     * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`.
+     */
+    fadeIn: function (duration, loop, marker) {
+
+        if (loop === undefined) { loop = false; }
+        if (marker === undefined) { marker = this.currentMarker; }
+
+        if (this.paused)
+        {
+            return;
+        }
+
+        this.play(marker, 0, 0, loop);
+
+        this.fadeTo(duration, 1);
+
+    },
+    
+    /**
+     * Decreases the volume of this Sound from its current value to 0 over the duration specified.
+     * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
+     * and the final volume (0) as the second parameter.
+     *
+     * @method Phaser.Sound#fadeOut
+     * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out.
+     */
+    fadeOut: function (duration) {
+
+        this.fadeTo(duration, 0);
+
+    },
+
+    /**
+     * Fades the volume of this Sound from its current value to the given volume over the duration specified.
+     * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, 
+     * and the final volume (volume) as the second parameter.
+     *
+     * @method Phaser.Sound#fadeTo
+     * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out.
+     * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1.
+     */
+    fadeTo: function (duration, volume) {
+
+        if (!this.isPlaying || this.paused || volume === this.volume)
+        {
+            return;
+        }
+
+        if (duration === undefined) { duration = 1000; }
+
+        if (volume === undefined)
+        {
+            console.warn("Phaser.Sound.fadeTo: No Volume Specified.");
+            return;
+        }
+
+        this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true);
+
+        this.fadeTween.onComplete.add(this.fadeComplete, this);
+
+    },
+
+    /**
+     * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo.
+     *
+     * @method Phaser.Sound#fadeComplete
+     * @private
+     */
+    fadeComplete: function () {
+
+        this.onFadeComplete.dispatch(this, this.volume);
+
+        if (this.volume === 0)
+        {
+            this.stop();
+        }
+
+    },
+
+    /**
+    * Destroys this sound and all associated events and removes it from the SoundManager.
+    *
+    * @method Phaser.Sound#destroy
+    * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager.
+    */
+    destroy: function (remove) {
+
+        if (remove === undefined) { remove = true; }
+
+        this.stop();
+
+        if (remove)
+        {
+            this.game.sound.remove(this);
+        }
+        else
+        {
+            this.markers = {};
+            this.context = null;
+            this._buffer = null;
+            this.externalNode = null;
+
+            this.onDecoded.dispose();
+            this.onPlay.dispose();
+            this.onPause.dispose();
+            this.onResume.dispose();
+            this.onLoop.dispose();
+            this.onStop.dispose();
+            this.onMute.dispose();
+            this.onMarkerComplete.dispose();
+        }
+
+    }
+
+};
+
+Phaser.Sound.prototype.constructor = Phaser.Sound;
+
+/**
+* @name Phaser.Sound#isDecoding
+* @property {boolean} isDecoding - Returns true if the sound file is still decoding.
+* @readonly
+*/
+Object.defineProperty(Phaser.Sound.prototype, "isDecoding", {
+
+    get: function () {
+        return this.game.cache.getSound(this.key).isDecoding;
+    }
+
+});
+
+/**
+* @name Phaser.Sound#isDecoded
+* @property {boolean} isDecoded - Returns true if the sound file has decoded.
+* @readonly
+*/
+Object.defineProperty(Phaser.Sound.prototype, "isDecoded", {
+
+    get: function () {
+        return this.game.cache.isSoundDecoded(this.key);
+    }
+
+});
+
+/**
+* @name Phaser.Sound#mute
+* @property {boolean} mute - Gets or sets the muted state of this sound.
+*/
+Object.defineProperty(Phaser.Sound.prototype, "mute", {
+
+    get: function () {
+
+        return (this._muted || this.game.sound.mute);
+
+    },
+
+    set: function (value) {
+
+        value = value || false;
+
+        if (value === this._muted)
+        {
+            return;
+        }
+
+        if (value)
+        {
+            this._muted = true;
+            this._muteVolume = this._tempVolume;
+
+            if (this.usingWebAudio)
+            {
+                this.gainNode.gain.value = 0;
+            }
+            else if (this.usingAudioTag && this._sound)
+            {
+                this._sound.volume = 0;
+            }
+        }
+        else
+        {
+            this._muted = false;
+
+            if (this.usingWebAudio)
+            {
+                this.gainNode.gain.value = this._muteVolume;
+            }
+            else if (this.usingAudioTag && this._sound)
+            {
+                this._sound.volume = this._muteVolume;
+            }
+        }
+
+        this.onMute.dispatch(this);
+
+    }
+
+});
+
+/**
+* @name Phaser.Sound#volume
+* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1.
+* @readonly
+*/
+Object.defineProperty(Phaser.Sound.prototype, "volume", {
+
+    get: function () {
+        return this._volume;
+    },
+
+    set: function (value) {
+
+        //  Causes an Index size error in Firefox if you don't clamp the value
+        if (this.game.device.firefox && this.usingAudioTag)
+        {
+            value = this.game.math.clamp(value, 0, 1);
+        }
+
+        if (this._muted)
+        {
+            this._muteVolume = value;
+            return;
+        }
+
+        this._tempVolume = value;
+        this._volume = value;
+
+        if (this.usingWebAudio)
+        {
+            this.gainNode.gain.value = value;
+        }
+        else if (this.usingAudioTag && this._sound)
+        {
+            this._sound.volume = value;
+        }
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it.
+* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files.
+* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats.
+* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/
+*
+* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out
+* of AudioContext nodes. If this is the case create a global var called PhaserGlobal on the window object before creating the game. The active
+* AudioContext will then be saved to window.PhaserGlobal.audioContext when the Phaser game is destroyed, and re-used when it starts again.
+*
+* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio.
+* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system.
+* The solution is to use a lower encoding rate such as 44100 Hz.
+*
+* @class Phaser.SoundManager
+* @constructor
+* @param {Phaser.Game} game - Reference to the current game instance.
+*/
+Phaser.SoundManager = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files)
+    */
+    this.onSoundDecode = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback.
+    * @property {Phaser.Signal} onVolumeChange
+    */
+    this.onVolumeChange = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing.
+    * @property {Phaser.Signal} onMute
+    */
+    this.onMute = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause.
+    * @property {Phaser.Signal} onUnMute
+    */
+    this.onUnMute = new Phaser.Signal();
+
+    /**
+    * @property {AudioContext} context - The AudioContext being used for playback.
+    * @default
+    */
+    this.context = null;
+
+    /**
+    * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio.
+    * @readonly
+    */
+    this.usingWebAudio = false;
+
+    /**
+    * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio.
+    * @readonly
+    */
+    this.usingAudioTag = false;
+
+    /**
+    * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio.
+    * @default
+    */
+    this.noAudio = false;
+
+    /**
+    * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node.
+    * @default
+    */
+    this.connectToMaster = true;
+
+    /**
+    * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event.
+    * @default
+    */
+    this.touchLocked = false;
+
+    /**
+    * @property {number} channels - The number of audio channels to use in playback.
+    * @default
+    */
+    this.channels = 32;
+
+    /**
+    * @property {boolean} _codeMuted - Internal mute tracking var.
+    * @private
+    * @default
+    */
+    this._codeMuted = false;
+
+    /**
+    * @property {boolean} _muted - Internal mute tracking var.
+    * @private
+    * @default
+    */
+    this._muted = false;
+
+    /**
+    * @property {AudioContext} _unlockSource - Internal unlock tracking var.
+    * @private
+    * @default
+    */
+    this._unlockSource = null;
+
+    /**
+    * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
+    * @private
+    * @default
+    */
+    this._volume = 1;
+
+    /**
+    * @property {array} _sounds - An array containing all the sounds
+    * @private
+    */
+    this._sounds = [];
+
+    /**
+    * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status.
+    * @private
+    */
+    this._watchList = new Phaser.ArraySet();
+
+    /**
+    * @property {boolean} _watching - Is the SoundManager monitoring the watchList?
+    * @private
+    */
+    this._watching = false;
+
+    /**
+    * @property {function} _watchCallback - The callback to invoke once the watchlist is clear.
+    * @private
+    */
+    this._watchCallback = null;
+
+    /**
+    * @property {object} _watchContext - The context in which to call the watchlist callback.
+    * @private
+    */
+    this._watchContext = null;
+
+};
+
+Phaser.SoundManager.prototype = {
+
+    /**
+    * Initialises the sound manager.
+    * @method Phaser.SoundManager#boot
+    * @protected
+    */
+    boot: function () {
+
+        if (this.game.device.iOS && this.game.device.webAudio === false)
+        {
+            this.channels = 1;
+        }
+
+        //  PhaserGlobal overrides
+        if (window['PhaserGlobal'])
+        {
+            //  Check to see if all audio playback is disabled (i.e. handled by a 3rd party class)
+            if (window['PhaserGlobal'].disableAudio === true)
+            {
+                this.noAudio = true;
+                this.touchLocked = false;
+                return;
+            }
+
+            //  Check if the Web Audio API is disabled (for testing Audio Tag playback during development)
+            if (window['PhaserGlobal'].disableWebAudio === true)
+            {
+                this.usingAudioTag = true;
+                this.touchLocked = false;
+                return;
+            }
+        }
+
+        if (window['PhaserGlobal'] && window['PhaserGlobal'].audioContext)
+        {
+            this.context = window['PhaserGlobal'].audioContext;
+        }
+        else
+        {
+            if (!!window['AudioContext'])
+            {
+                try {
+                    this.context = new window['AudioContext']();
+                } catch (error) {
+                    this.context = null;
+                    this.usingWebAudio = false;
+                    this.touchLocked = false;
+                }
+            }
+            else if (!!window['webkitAudioContext'])
+            {
+                try {
+                    this.context = new window['webkitAudioContext']();
+                } catch (error) {
+                    this.context = null;
+                    this.usingWebAudio = false;
+                    this.touchLocked = false;
+                }
+            }
+        }
+
+        if (this.context === null)
+        {
+            //  No Web Audio support - how about legacy Audio?
+            if (window['Audio'] === undefined)
+            {
+                this.noAudio = true;
+                return;
+            }
+            else
+            {
+                this.usingAudioTag = true;
+            }
+        }
+        else
+        {
+            this.usingWebAudio = true;
+
+            if (this.context.createGain === undefined)
+            {
+                this.masterGain = this.context.createGainNode();
+            }
+            else
+            {
+                this.masterGain = this.context.createGain();
+            }
+
+            this.masterGain.gain.value = 1;
+            this.masterGain.connect(this.context.destination);
+        }
+
+        if (!this.noAudio)
+        {
+            //  On mobile we need a native touch event before we can play anything, so capture it here
+            if (!this.game.device.cocoonJS && this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
+            {
+                this.setTouchLock();
+            }
+        }
+
+    },
+
+    /**
+    * Sets the Input Manager touch callback to be SoundManager.unlock.
+    * Required for iOS audio device unlocking. Mostly just used internally.
+    * 
+    * @method Phaser.SoundManager#setTouchLock
+    */
+    setTouchLock: function () {
+
+        this.game.input.touch.addTouchLockCallback(this.unlock, this);
+        this.touchLocked = true;
+
+    },
+
+    /**
+    * Enables the audio, usually after the first touch.
+    * 
+    * @method Phaser.SoundManager#unlock
+    * @return {boolean} True if the callback should be removed, otherwise false.
+    */
+    unlock: function () {
+
+        if (this.noAudio || !this.touchLocked || this._unlockSource !== null)
+        {
+            return true;
+        }
+
+        //  Global override (mostly for Audio Tag testing)
+        if (this.usingAudioTag)
+        {
+            this.touchLocked = false;
+            this._unlockSource = null;
+        }
+        else if (this.usingWebAudio)
+        {
+            // Create empty buffer and play it
+            // The SoundManager.update loop captures the state of it and then resets touchLocked to false
+
+            var buffer = this.context.createBuffer(1, 1, 22050);
+            this._unlockSource = this.context.createBufferSource();
+            this._unlockSource.buffer = buffer;
+            this._unlockSource.connect(this.context.destination);
+
+            if (this._unlockSource.start === undefined)
+            {
+                this._unlockSource.noteOn(0);
+            }
+            else
+            {
+                this._unlockSource.start(0);
+            }
+        }
+
+        //  We can remove the event because we've done what we needed (started the unlock sound playing)
+        return true;
+
+    },
+
+    /**
+    * Stops all the sounds in the game.
+    *
+    * @method Phaser.SoundManager#stopAll
+    */
+    stopAll: function () {
+
+        if (this.noAudio)
+        {
+            return;
+        }
+
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            if (this._sounds[i])
+            {
+                this._sounds[i].stop();
+            }
+        }
+
+    },
+
+    /**
+    * Pauses all the sounds in the game.
+    *
+    * @method Phaser.SoundManager#pauseAll
+    */
+    pauseAll: function () {
+
+        if (this.noAudio)
+        {
+            return;
+        }
+
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            if (this._sounds[i])
+            {
+                this._sounds[i].pause();
+            }
+        }
+
+    },
+
+    /**
+    * Resumes every sound in the game.
+    *
+    * @method Phaser.SoundManager#resumeAll
+    */
+    resumeAll: function () {
+
+        if (this.noAudio)
+        {
+            return;
+        }
+
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            if (this._sounds[i])
+            {
+                this._sounds[i].resume();
+            }
+        }
+
+    },
+
+    /**
+    * Decode a sound by its asset key.
+    *
+    * @method Phaser.SoundManager#decode
+    * @param {string} key - Assets key of the sound to be decoded.
+    * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data.
+    */
+    decode: function (key, sound) {
+
+        sound = sound || null;
+
+        var soundData = this.game.cache.getSoundData(key);
+
+        if (soundData)
+        {
+            if (this.game.cache.isSoundDecoded(key) === false)
+            {
+                this.game.cache.updateSound(key, 'isDecoding', true);
+
+                var _this = this;
+
+                try {
+                    this.context.decodeAudioData(soundData, function (buffer) {
+
+                        if (buffer)
+                        {
+                            _this.game.cache.decodedSound(key, buffer);
+                            _this.onSoundDecode.dispatch(key, sound);
+                        }
+                    });
+                }
+                catch (e) {}
+            }
+        }
+
+    },
+
+    /**
+     * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback.
+     * Once all of the Sound files have finished decoding the callback will be invoked.
+     * The amount of time spent decoding depends on the codec used and file size.
+     * If all of the files given have already decoded the callback is triggered immediately.
+     *
+     * @method Phaser.SoundManager#setDecodedCallback
+     * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache.
+     * @param {Function} callback - The callback which will be invoked once all files have finished decoding.
+     * @param {Object} callbackContext - The context in which the callback will run.
+     */
+    setDecodedCallback: function (files, callback, callbackContext) {
+
+        if (typeof files === 'string')
+        {
+            files = [ files ];
+        }
+
+        this._watchList.reset();
+
+        for (var i = 0; i < files.length; i++)
+        {
+            if (files[i] instanceof Phaser.Sound)
+            {
+                if (!this.game.cache.isSoundDecoded(files[i].key))
+                {
+                    this._watchList.add(files[i].key);
+                }
+            }
+            else if (!this.game.cache.isSoundDecoded(files[i]))
+            {
+                this._watchList.add(files[i]);
+            }
+        }
+
+        //  All decoded already?
+        if (this._watchList.total === 0)
+        {
+            this._watching = false;
+            callback.call(callbackContext);
+        }
+        else
+        {
+            this._watching = true;
+            this._watchCallback = callback;
+            this._watchContext = callbackContext;
+        }
+
+    },
+
+    /**
+    * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list.
+    *
+    * @method Phaser.SoundManager#update
+    * @protected
+    */
+    update: function () {
+
+        if (this.noAudio)
+        {
+            return;
+        }
+
+        if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE))
+        {
+            this.touchLocked = false;
+            this._unlockSource = null;
+        }
+
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            this._sounds[i].update();
+        }
+
+        if (this._watching)
+        {
+            var key = this._watchList.first;
+
+            while (key)
+            {
+                if (this.game.cache.isSoundDecoded(key))
+                {
+                    this._watchList.remove(key);
+                }
+
+                key = this._watchList.next;
+            }
+
+            if (this._watchList.total === 0)
+            {
+                this._watching = false;
+                this._watchCallback.call(this._watchContext);
+            }
+        }
+
+    },
+
+    /**
+    * Adds a new Sound into the SoundManager.
+    *
+    * @method Phaser.SoundManager#add
+    * @param {string} key - Asset key for the sound.
+    * @param {number} [volume=1] - Default value for the volume.
+    * @param {boolean} [loop=false] - Whether or not the sound will loop.
+    * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
+    * @return {Phaser.Sound} The new sound instance.
+    */
+    add: function (key, volume, loop, connect) {
+
+        if (volume === undefined) { volume = 1; }
+        if (loop === undefined) { loop = false; }
+        if (connect === undefined) { connect = this.connectToMaster; }
+
+        var sound = new Phaser.Sound(this.game, key, volume, loop, connect);
+
+        this._sounds.push(sound);
+
+        return sound;
+
+    },
+
+    /**
+     * Adds a new AudioSprite into the SoundManager.
+     *
+     * @method Phaser.SoundManager#addSprite
+     * @param {string} key - Asset key for the sound.
+     * @return {Phaser.AudioSprite} The new AudioSprite instance.
+     */
+    addSprite: function(key) {
+
+        var audioSprite = new Phaser.AudioSprite(this.game, key);
+
+        return audioSprite;
+
+    },
+
+    /**
+    * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal.
+    *
+    * @method Phaser.SoundManager#remove
+    * @param {Phaser.Sound} sound - The sound object to remove.
+    * @return {boolean} True if the sound was removed successfully, otherwise false.
+    */
+    remove: function (sound) {
+
+        var i = this._sounds.length;
+
+        while (i--)
+        {
+            if (this._sounds[i] === sound)
+            {
+                this._sounds[i].destroy(false);
+                this._sounds.splice(i, 1);
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Removes all Sounds from the SoundManager that have an asset key matching the given value.
+    * The removed Sounds are destroyed before removal.
+    *
+    * @method Phaser.SoundManager#removeByKey
+    * @param {string} key - The key to match when removing sound objects.
+    * @return {number} The number of matching sound objects that were removed.
+    */
+    removeByKey: function (key) {
+
+        var i = this._sounds.length;
+        var removed = 0;
+
+        while (i--)
+        {
+            if (this._sounds[i].key === key)
+            {
+                this._sounds[i].destroy(false);
+                this._sounds.splice(i, 1);
+                removed++;
+            }
+        }
+
+        return removed;
+
+    },
+
+    /**
+    * Adds a new Sound into the SoundManager and starts it playing.
+    *
+    * @method Phaser.SoundManager#play
+    * @param {string} key - Asset key for the sound.
+    * @param {number} [volume=1] - Default value for the volume.
+    * @param {boolean} [loop=false] - Whether or not the sound will loop.
+    * @return {Phaser.Sound} The new sound instance.
+    */
+    play: function (key, volume, loop) {
+
+        if (this.noAudio)
+        {
+            return;
+        }
+
+        var sound = this.add(key, volume, loop);
+
+        sound.play();
+
+        return sound;
+
+    },
+
+    /**
+    * Internal mute handler called automatically by the SoundManager.mute setter.
+    *
+    * @method Phaser.SoundManager#setMute
+    * @private
+    */
+    setMute: function () {
+
+        if (this._muted)
+        {
+            return;
+        }
+
+        this._muted = true;
+
+        if (this.usingWebAudio)
+        {
+            this._muteVolume = this.masterGain.gain.value;
+            this.masterGain.gain.value = 0;
+        }
+
+        //  Loop through sounds
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            if (this._sounds[i].usingAudioTag)
+            {
+                this._sounds[i].mute = true;
+            }
+        }
+
+        this.onMute.dispatch();
+
+    },
+
+    /**
+    * Internal mute handler called automatically by the SoundManager.mute setter.
+    *
+    * @method Phaser.SoundManager#unsetMute
+    * @private
+    */
+    unsetMute: function () {
+
+        if (!this._muted || this._codeMuted)
+        {
+            return;
+        }
+
+        this._muted = false;
+
+        if (this.usingWebAudio)
+        {
+            this.masterGain.gain.value = this._muteVolume;
+        }
+
+        //  Loop through sounds
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            if (this._sounds[i].usingAudioTag)
+            {
+                this._sounds[i].mute = false;
+            }
+        }
+
+        this.onUnMute.dispatch();
+
+    },
+
+    /**
+    * Stops all the sounds in the game, then destroys them and finally clears up any callbacks.
+    *
+    * @method Phaser.SoundManager#destroy
+    */
+    destroy: function () {
+
+        this.stopAll();
+
+        for (var i = 0; i < this._sounds.length; i++)
+        {
+            if (this._sounds[i])
+            {
+                this._sounds[i].destroy();
+            }
+        }
+
+        this._sounds = [];
+
+        this.onSoundDecode.dispose();
+
+        if (this.context && window['PhaserGlobal'])
+        {
+            //  Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing
+            window['PhaserGlobal'].audioContext = this.context;
+        }
+
+    }
+
+};
+
+Phaser.SoundManager.prototype.constructor = Phaser.SoundManager;
+
+/**
+* @name Phaser.SoundManager#mute
+* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game.
+*/
+Object.defineProperty(Phaser.SoundManager.prototype, "mute", {
+
+    get: function () {
+
+        return this._muted;
+
+    },
+
+    set: function (value) {
+
+        value = value || false;
+
+        if (value)
+        {
+            if (this._muted)
+            {
+                return;
+            }
+
+            this._codeMuted = true;
+            this.setMute();
+        }
+        else
+        {
+            if (!this._muted)
+            {
+                return;
+            }
+
+            this._codeMuted = false;
+            this.unsetMute();
+        }
+    }
+
+});
+
+/**
+* @name Phaser.SoundManager#volume
+* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1.
+*/
+Object.defineProperty(Phaser.SoundManager.prototype, "volume", {
+
+    get: function () {
+
+        return this._volume;
+
+    },
+
+    set: function (value) {
+
+        if (value < 0)
+        {
+            value = 0;
+        }
+        else if (value > 1)
+        {
+            value = 1;
+        }
+
+        if (this._volume !== value)
+        {
+            this._volume = value;
+
+            if (this.usingWebAudio)
+            {
+                this.masterGain.gain.value = value;
+            }
+            else
+            {
+                //  Loop through the sound cache and change the volume of all html audio tags
+                for (var i = 0; i < this._sounds.length; i++)
+                {
+                    if (this._sounds[i].usingAudioTag)
+                    {
+                        this._sounds[i].volume = this._sounds[i].volume * value;
+                    }
+                }
+            }
+
+            this.onVolumeChange.dispatch(value);
+
+        }
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A collection of methods for displaying debug information about game objects.
+* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture
+* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug
+* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production!
+* If your game is using a Canvas renderer then the debug information is literally drawn on the top of the active game canvas and no Sprite is used.
+*
+* @class Phaser.Utils.Debug
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Utils.Debug = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Image} sprite - If debugging in WebGL mode we need this.
+    */
+    this.sprite = null;
+
+    /**
+    * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas.
+    */
+    this.bmd = null;
+
+    /**
+    * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws.
+    */
+    this.canvas = null;
+
+    /**
+    * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
+    */
+    this.context = null;
+
+    /**
+    * @property {string} font - The font that the debug information is rendered in.
+    * @default '14px Courier'
+    */
+    this.font = '14px Courier';
+
+    /**
+    * @property {number} columnWidth - The spacing between columns.
+    */
+    this.columnWidth = 100;
+
+    /**
+    * @property {number} lineHeight - The line height between the debug text.
+    */
+    this.lineHeight = 16;
+
+    /**
+    * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background.
+    */
+    this.renderShadow = true;
+
+    /**
+    * @property {number} currentX - The current X position the debug information will be rendered at.
+    * @default
+    */
+    this.currentX = 0;
+
+    /**
+    * @property {number} currentY - The current Y position the debug information will be rendered at.
+    * @default
+    */
+    this.currentY = 0;
+
+    /**
+    * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it.
+    * @default
+    */
+    this.currentAlpha = 1;
+
+    /**
+    * @property {boolean} dirty - Does the canvas need re-rendering?
+    */
+    this.dirty = false;
+
+};
+
+Phaser.Utils.Debug.prototype = {
+
+    /**
+    * Internal method that boots the debug displayer.
+    *
+    * @method Phaser.Utils.Debug#boot
+    * @protected
+    */
+    boot: function () {
+
+        if (this.game.renderType === Phaser.CANVAS)
+        {
+            this.context = this.game.context;
+        }
+        else
+        {
+            this.bmd = this.game.make.bitmapData(this.game.width, this.game.height);
+            this.sprite = this.game.make.image(0, 0, this.bmd);
+            this.game.stage.addChild(this.sprite);
+
+            this.canvas = Phaser.Canvas.create(this.game.width, this.game.height, '', true);
+            this.context = this.canvas.getContext('2d');
+        }
+
+    },
+
+    /**
+    * Internal method that clears the canvas (if a Sprite) ready for a new debug session.
+    *
+    * @method Phaser.Utils.Debug#preUpdate
+    */
+    preUpdate: function () {
+
+        if (this.dirty && this.sprite)
+        {
+            this.bmd.clear();
+            this.bmd.draw(this.canvas, 0, 0);
+
+            this.context.clearRect(0, 0, this.game.width, this.game.height);
+            this.dirty = false;
+        }
+
+    },
+
+    /**
+    * Clears the Debug canvas.
+    *
+    * @method Phaser.Utils.Debug#reset
+    */
+    reset: function () {
+
+        if (this.context)
+        {
+            this.context.clearRect(0, 0, this.game.width, this.game.height);
+        }
+
+        if (this.sprite)
+        {
+            this.bmd.clear();
+        }
+
+    },
+
+    /**
+    * Internal method that resets and starts the debug output values.
+    *
+    * @method Phaser.Utils.Debug#start
+    * @protected
+    * @param {number} [x=0] - The X value the debug info will start from.
+    * @param {number} [y=0] - The Y value the debug info will start from.
+    * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in.
+    * @param {number} [columnWidth=0] - The spacing between columns.
+    */
+    start: function (x, y, color, columnWidth) {
+
+        if (typeof x !== 'number') { x = 0; }
+        if (typeof y !== 'number') { y = 0; }
+        color = color || 'rgb(255,255,255)';
+        if (columnWidth === undefined) { columnWidth = 0; }
+
+        this.currentX = x;
+        this.currentY = y;
+        this.currentColor = color;
+        this.columnWidth = columnWidth;
+
+        this.dirty = true;
+
+        this.context.save();
+        this.context.setTransform(1, 0, 0, 1, 0, 0);
+        this.context.strokeStyle = color;
+        this.context.fillStyle = color;
+        this.context.font = this.font;
+        this.context.globalAlpha = this.currentAlpha;
+
+    },
+
+    /**
+    * Internal method that stops the debug output.
+    *
+    * @method Phaser.Utils.Debug#stop
+    * @protected
+    */
+    stop: function () {
+
+        this.context.restore();
+
+    },
+
+    /**
+    * Internal method that outputs a single line of text split over as many columns as needed, one per parameter.
+    *
+    * @method Phaser.Utils.Debug#line
+    * @protected
+    */
+    line: function () {
+
+        var x = this.currentX;
+
+        for (var i = 0; i < arguments.length; i++)
+        {
+            if (this.renderShadow)
+            {
+                this.context.fillStyle = 'rgb(0,0,0)';
+                this.context.fillText(arguments[i], x + 1, this.currentY + 1);
+                this.context.fillStyle = this.currentColor;
+            }
+
+            this.context.fillText(arguments[i], x, this.currentY);
+
+            x += this.columnWidth;
+        }
+
+        this.currentY += this.lineHeight;
+
+    },
+
+    /**
+    * Render Sound information, including decoded state, duration, volume and more.
+    *
+    * @method Phaser.Utils.Debug#soundInfo
+    * @param {Phaser.Sound} sound - The sound object to debug.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    soundInfo: function (sound, x, y, color) {
+
+        this.start(x, y, color);
+        this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked);
+        this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback);
+        this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding);
+        this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying);
+        this.line('Time: ' + sound.currentTime);
+        this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute);
+        this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag);
+
+        if (sound.currentMarker !== '')
+        {
+            this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')');
+            this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop);
+            this.line('Position: ' + sound.position);
+        }
+
+        this.stop();
+
+    },
+
+    /**
+    * Render camera information including dimensions and location.
+    *
+    * @method Phaser.Utils.Debug#cameraInfo
+    * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    cameraInfo: function (camera, x, y, color) {
+
+        this.start(x, y, color);
+        this.line('Camera (' + camera.width + ' x ' + camera.height + ')');
+        this.line('X: ' + camera.x + ' Y: ' + camera.y);
+
+        if (camera.bounds)
+        {
+            this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height);
+        }
+
+        this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height);
+        // this.line('Screen View x: ' + camera.screenView.x + ' Y: ' + camera.screenView.y + ' w: ' + camera.screenView.width + ' h: ' + camera.screenView.height);
+        this.line('Total in view: ' + camera.totalInView);
+        this.stop();
+
+    },
+
+    /**
+    * Render Timer information.
+    *
+    * @method Phaser.Utils.Debug#timer
+    * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    timer: function (timer, x, y, color) {
+
+        this.start(x, y, color);
+        this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')');
+        this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration);
+        this.line('Paused: ' + timer.paused + ' Length: ' + timer.length);
+        this.stop();
+
+    },
+
+    /**
+    * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text.
+    *
+    * @method Phaser.Utils.Debug#pointer
+    * @param {Phaser.Pointer} pointer - The Pointer you wish to display.
+    * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up.
+    * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down.
+    * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false).
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    pointer: function (pointer, hideIfUp, downColor, upColor, color) {
+
+        if (pointer == null)
+        {
+            return;
+        }
+
+        if (hideIfUp === undefined) { hideIfUp = false; }
+        downColor = downColor || 'rgba(0,255,0,0.5)';
+        upColor = upColor || 'rgba(255,0,0,0.5)';
+
+        if (hideIfUp === true && pointer.isUp === true)
+        {
+            return;
+        }
+
+        this.start(pointer.x, pointer.y - 100, color);
+        this.context.beginPath();
+        this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2);
+
+        if (pointer.active)
+        {
+            this.context.fillStyle = downColor;
+        }
+        else
+        {
+            this.context.fillStyle = upColor;
+        }
+
+        this.context.fill();
+        this.context.closePath();
+
+        //  Render the points
+        this.context.beginPath();
+        this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y);
+        this.context.lineTo(pointer.position.x, pointer.position.y);
+        this.context.lineWidth = 2;
+        this.context.stroke();
+        this.context.closePath();
+
+        //  Render the text
+        this.line('ID: ' + pointer.id + " Active: " + pointer.active);
+        this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY);
+        this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y);
+        this.line('Duration: ' + pointer.duration + " ms");
+        this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp);
+        this.stop();
+
+    },
+
+    /**
+    * Render Sprite Input Debug information.
+    *
+    * @method Phaser.Utils.Debug#spriteInputInfo
+    * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    spriteInputInfo: function (sprite, x, y, color) {
+
+        this.start(x, y, color);
+        this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')');
+        this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1));
+        this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0));
+        this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0));
+        this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut());
+        this.stop();
+
+    },
+
+    /**
+    * Renders Phaser.Key object information.
+    *
+    * @method Phaser.Utils.Debug#key
+    * @param {Phaser.Key} key - The Key to render the information for.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    key: function (key, x, y, color) {
+
+        this.start(x, y, color, 150);
+
+        this.line('Key:', key.keyCode, 'isDown:', key.isDown);
+        this.line('justDown:', key.justDown, 'justUp:', key.justUp);
+        this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0));
+
+        this.stop();
+
+    },
+
+    /**
+    * Render debug information about the Input object.
+    *
+    * @method Phaser.Utils.Debug#inputInfo
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    inputInfo: function (x, y, color) {
+
+        this.start(x, y, color);
+        this.line('Input');
+        this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y);
+        this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY);
+        this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1));
+        this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY);
+        this.stop();
+
+    },
+
+    /**
+    * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it!
+    *
+    * @method Phaser.Utils.Debug#spriteBounds
+    * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of.
+    * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
+    * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
+    */
+    spriteBounds: function (sprite, color, filled) {
+
+        var bounds = sprite.getBounds();
+
+        bounds.x += this.game.camera.x;
+        bounds.y += this.game.camera.y;
+
+        this.rectangle(bounds, color, filled);
+
+    },
+
+    /**
+    * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it
+    *
+    * @method Phaser.Utils.Debug#ropeSegments
+    * @param {Phaser.Rope} rope - The rope to display the segments of.
+    * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
+    * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
+    */
+    ropeSegments: function (rope, color, filled) {
+
+        var segments = rope.segments;
+
+        var self = this;
+
+        segments.forEach(function(segment) {
+            self.rectangle(segment, color, filled);
+        }, this);
+
+    },
+
+    /**
+    * Render debug infos (including name, bounds info, position and some other properties) about the Sprite.
+    *
+    * @method Phaser.Utils.Debug#spriteInfo
+    * @param {Phaser.Sprite} sprite - The Sprite to display the information of.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    spriteInfo: function (sprite, x, y, color) {
+
+        this.start(x, y, color);
+
+        this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y);
+        this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1));
+        this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1));
+        this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera);
+        this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1));
+
+        this.stop();
+
+    },
+
+    /**
+    * Renders the sprite coordinates in local, positional and world space.
+    *
+    * @method Phaser.Utils.Debug#spriteCoords
+    * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    spriteCoords: function (sprite, x, y, color) {
+
+        this.start(x, y, color, 100);
+
+        if (sprite.name)
+        {
+            this.line(sprite.name);
+        }
+
+        this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2));
+        this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2));
+        this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2));
+
+        this.stop();
+
+    },
+
+    /**
+    * Renders Line information in the given color.
+    *
+    * @method Phaser.Utils.Debug#lineInfo
+    * @param {Phaser.Line} line - The Line to display the data for.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    lineInfo: function (line, x, y, color) {
+
+        this.start(x, y, color, 80);
+        this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2));
+        this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2));
+        this.line('length:', line.length.toFixed(2), 'angle:', line.angle);
+        this.stop();
+
+    },
+
+    /**
+    * Renders a single pixel at the given size.
+    *
+    * @method Phaser.Utils.Debug#pixel
+    * @param {number} x - X position of the pixel to be rendered.
+    * @param {number} y - Y position of the pixel to be rendered.
+    * @param {string} [color] - Color of the pixel (format is css color string).
+    * @param {number} [size=2] - The 'size' to render the pixel at.
+    */
+    pixel: function (x, y, color, size) {
+
+        size = size || 2;
+
+        this.start();
+        this.context.fillStyle = color;
+        this.context.fillRect(x, y, size, size);
+        this.stop();
+
+    },
+
+    /**
+    * Renders a Phaser geometry object including Rectangle, Circle, Point or Line.
+    *
+    * @method Phaser.Utils.Debug#geom
+    * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Point|Phaser.Line} object - The geometry object to render.
+    * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
+    * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
+    * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle, 3 = Point and 4 = Line.
+    */
+    geom: function (object, color, filled, forceType) {
+
+        if (filled === undefined) { filled = true; }
+        if (forceType === undefined) { forceType = 0; }
+
+        color = color || 'rgba(0,255,0,0.4)';
+
+        this.start();
+
+        this.context.fillStyle = color;
+        this.context.strokeStyle = color;
+
+        if (object instanceof Phaser.Rectangle || forceType === 1)
+        {
+            if (filled)
+            {
+                this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
+            }
+            else
+            {
+                this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
+            }
+        }
+        else if (object instanceof Phaser.Circle || forceType === 2)
+        {
+            this.context.beginPath();
+            this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false);
+            this.context.closePath();
+
+            if (filled)
+            {
+                this.context.fill();
+            }
+            else
+            {
+                this.context.stroke();
+            }
+        }
+        else if (object instanceof Phaser.Point || forceType === 3)
+        {
+            this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4);
+        }
+        else if (object instanceof Phaser.Line || forceType === 4)
+        {
+            this.context.lineWidth = 1;
+            this.context.beginPath();
+            this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y);
+            this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y);
+            this.context.closePath();
+            this.context.stroke();
+        }
+
+        this.stop();
+
+    },
+
+    /**
+    * Renders a Rectangle.
+    *
+    * @method Phaser.Utils.Debug#geom
+    * @param {Phaser.Rectangle|object} object - The geometry object to render.
+    * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
+    * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
+    */
+    rectangle: function (object, color, filled) {
+
+        if (filled === undefined) { filled = true; }
+
+        color = color || 'rgba(0, 255, 0, 0.4)';
+
+        this.start();
+
+        if (filled)
+        {
+            this.context.fillStyle = color;
+            this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
+        }
+        else
+        {
+            this.context.strokeStyle = color;
+            this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
+        }
+
+        this.stop();
+
+    },
+
+    /**
+    * Render a string of text.
+    *
+    * @method Phaser.Utils.Debug#text
+    * @param {string} text - The line of text to draw.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
+    * @param {string} [font] - The font of text to draw.
+    */
+    text: function (text, x, y, color, font) {
+
+        color = color || 'rgb(255,255,255)';
+        font = font || '16px Courier';
+
+        this.start();
+        this.context.font = font;
+
+        if (this.renderShadow)
+        {
+            this.context.fillStyle = 'rgb(0,0,0)';
+            this.context.fillText(text, x + 1, y + 1);
+        }
+
+        this.context.fillStyle = color;
+        this.context.fillText(text, x, y);
+
+        this.stop();
+
+    },
+
+    /**
+    * Visually renders a QuadTree to the display.
+    *
+    * @method Phaser.Utils.Debug#quadTree
+    * @param {Phaser.QuadTree} quadtree - The quadtree to render.
+    * @param {string} color - The color of the lines in the quadtree.
+    */
+    quadTree: function (quadtree, color) {
+
+        color = color || 'rgba(255,0,0,0.3)';
+
+        this.start();
+
+        var bounds = quadtree.bounds;
+
+        if (quadtree.nodes.length === 0)
+        {
+            this.context.strokeStyle = color;
+            this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
+            this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier');
+
+            this.context.strokeStyle = 'rgb(0,255,0)';
+
+            for (var i = 0; i < quadtree.objects.length; i++)
+            {
+                this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height);
+            }
+        }
+        else
+        {
+            for (var i = 0; i < quadtree.nodes.length; i++)
+            {
+                this.quadTree(quadtree.nodes[i]);
+            }
+        }
+
+        this.stop();
+
+    },
+
+    /**
+    * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle.
+    * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies.
+    * To display a P2 Physics body you should enable debug mode on the body when creating it.
+    *
+    * @method Phaser.Utils.Debug#body
+    * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered.
+    * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'.
+    * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false)
+    */
+    body: function (sprite, color, filled) {
+
+        if (sprite.body)
+        {
+            this.start();
+
+            if (sprite.body.type === Phaser.Physics.ARCADE)
+            {
+                Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled);
+            }
+            else if (sprite.body.type === Phaser.Physics.NINJA)
+            {
+                Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled);
+            }
+            else if (sprite.body.type === Phaser.Physics.BOX2D)
+            {
+                Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color);
+            }
+
+            this.stop();
+        }
+
+    },
+
+    /**
+    * Render a Sprites Physic Body information.
+    *
+    * @method Phaser.Utils.Debug#bodyInfo
+    * @param {Phaser.Sprite} sprite - The sprite to be rendered.
+    * @param {number} x - X position of the debug info to be rendered.
+    * @param {number} y - Y position of the debug info to be rendered.
+    * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    bodyInfo: function (sprite, x, y, color) {
+
+        if (sprite.body)
+        {
+            this.start(x, y, color, 210);
+
+            if (sprite.body.type === Phaser.Physics.ARCADE)
+            {
+                Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body);
+            }
+            else if (sprite.body.type === Phaser.Physics.BOX2D)
+            {
+                this.game.physics.box2d.renderBodyInfo(this, sprite.body);
+            }
+
+            this.stop();
+        }
+
+    },
+
+    /**
+    * Renders 'debug draw' data for the Box2D world if it exists.
+    * This uses the standard debug drawing feature of Box2D, so colors will be decided by
+    * the Box2D engine.
+    *
+    * @method Phaser.Utils.Debug#box2dWorld
+    */
+    box2dWorld: function () {
+    
+        this.start();
+        
+        this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0);
+        this.game.physics.box2d.renderDebugDraw(this.context);
+        
+        this.stop();
+
+    },
+
+    /**
+    * Renders 'debug draw' data for the given Box2D body.
+    * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine.
+    *
+    * @method Phaser.Utils.Debug#box2dBody
+    * @param {Phaser.Sprite} sprite - The sprite whos body will be rendered.
+    * @param {string} [color='rgb(0,255,0)'] - color of the debug info to be rendered. (format is css color string).
+    */
+    box2dBody: function (body, color) {
+    
+        this.start();
+        Phaser.Physics.Box2D.renderBody(this.context, body, color);
+        this.stop();
+
+    }
+
+};
+
+Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* ArraySet is a Set data structure (items must be unique within the set) that also maintains order.
+* This allows specific items to be easily added or removed from the Set.
+*
+* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`.
+*
+* This used primarily by the Input subsystem.
+*
+* @class Phaser.ArraySet
+* @constructor
+* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet.
+*/
+Phaser.ArraySet = function (list) {
+
+    /**
+    * Current cursor position as established by `first` and `next`.
+    * @property {integer} position
+    * @default
+    */
+    this.position = 0;
+
+    /**
+    * The backing array.
+    * @property {any[]} list
+    */
+    this.list = list || [];
+
+};
+
+Phaser.ArraySet.prototype = {
+
+    /**
+    * Adds a new element to the end of the list.
+    * If the item already exists in the list it is not moved.
+    *
+    * @method Phaser.ArraySet#add
+    * @param {any} item - The element to add to this list.
+    * @return {any} The item that was added.
+    */
+    add: function (item) {
+
+        if (!this.exists(item))
+        {
+            this.list.push(item);
+        }
+
+        return item;
+
+    },
+
+    /**
+    * Gets the index of the item in the list, or -1 if it isn't in the list.
+    *
+    * @method Phaser.ArraySet#getIndex
+    * @param {any} item - The element to get the list index for.
+    * @return {integer} The index of the item or -1 if not found.
+    */
+    getIndex: function (item) {
+
+        return this.list.indexOf(item);
+
+    },
+
+    /**
+    * Gets an item from the set based on the property strictly equaling the value given.
+    * Returns null if not found.
+    *
+    * @method Phaser.ArraySet#getByKey
+    * @param {string} property - The property to check against the value.
+    * @param {any} value - The value to check if the property strictly equals.
+    * @return {any} The item that was found, or null if nothing matched.
+    */
+    getByKey: function (property, value) {
+
+        var i = this.list.length;
+
+        while (i--)
+        {
+            if (this.list[i][property] === value)
+            {
+                return this.list[i];
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Checks for the item within this list.
+    *
+    * @method Phaser.ArraySet#exists
+    * @param {any} item - The element to get the list index for.
+    * @return {boolean} True if the item is found in the list, otherwise false.
+    */
+    exists: function (item) {
+
+        return (this.list.indexOf(item) > -1);
+
+    },
+
+    /**
+    * Removes all the items.
+    *
+    * @method Phaser.ArraySet#reset
+    */
+    reset: function () {
+
+        this.list.length = 0;
+
+    },
+
+    /**
+    * Removes the given element from this list if it exists.
+    *
+    * @method Phaser.ArraySet#remove
+    * @param {any} item - The item to be removed from the list.
+    * @return {any} item - The item that was removed.
+    */
+    remove: function (item) {
+
+        var idx = this.list.indexOf(item);
+
+        if (idx > -1)
+        {
+            this.list.splice(idx, 1);
+            return item;
+        }
+
+    },
+
+    /**
+    * Sets the property `key` to the given value on all members of this list.
+    *
+    * @method Phaser.ArraySet#setAll
+    * @param {any} key - The property of the item to set.
+    * @param {any} value - The value to set the property to.
+    */
+    setAll: function (key, value) {
+
+        var i = this.list.length;
+
+        while (i--)
+        {
+            if (this.list[i])
+            {
+                this.list[i][key] = value;
+            }
+        }
+
+    },
+
+    /**
+    * Calls a function on all members of this list, using the member as the context for the callback.
+    *
+    * If the `key` property is present it must be a function.
+    * The function is invoked using the item as the context.
+    *
+    * @method Phaser.ArraySet#callAll
+    * @param {string} key - The name of the property with the function to call.
+    * @param {...*} parameter - Additional parameters that will be passed to the callback.
+    */
+    callAll: function (key) {
+
+        var args = Array.prototype.splice.call(arguments, 1);
+
+        var i = this.list.length;
+
+        while (i--)
+        {
+            if (this.list[i] && this.list[i][key])
+            {
+                this.list[i][key].apply(this.list[i], args);
+            }
+        }
+
+    },
+
+    /**
+    * Removes every member from this ArraySet and optionally destroys it.
+    *
+    * @method Phaser.ArraySet#removeAll
+    * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set.
+    */
+    removeAll: function (destroy) {
+
+        if (destroy === undefined) { destroy = false; }
+
+        var i = this.list.length;
+
+        while (i--)
+        {
+            if (this.list[i])
+            {
+                var item = this.remove(this.list[i]);
+
+                if (destroy)
+                {
+                    item.destroy();
+                }
+            }
+        }
+
+        this.position = 0;
+        this.list = [];
+
+    }
+
+};
+
+/**
+* Number of items in the ArraySet. Same as `list.length`.
+*
+* @name Phaser.ArraySet#total
+* @property {integer} total
+*/
+Object.defineProperty(Phaser.ArraySet.prototype, "total", {
+
+    get: function () {
+        return this.list.length;
+    }
+
+});
+
+/**
+* Returns the first item and resets the cursor to the start.
+*
+* @name Phaser.ArraySet#first
+* @property {any} first
+*/
+Object.defineProperty(Phaser.ArraySet.prototype, "first", {
+
+    get: function () {
+
+        this.position = 0;
+
+        if (this.list.length > 0)
+        {
+            return this.list[0];
+        }
+        else
+        {
+            return null;
+        }
+
+    }
+
+});
+
+/**
+* Returns the the next item (based on the cursor) and advances the cursor.
+*
+* @name Phaser.ArraySet#next
+* @property {any} next
+*/
+Object.defineProperty(Phaser.ArraySet.prototype, "next", {
+
+    get: function () {
+
+        if (this.position < this.list.length)
+        {
+            this.position++;
+
+            return this.list[this.position];
+        }
+        else
+        {
+            return null;
+        }
+
+    }
+
+});
+
+Phaser.ArraySet.prototype.constructor = Phaser.ArraySet;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Utility functions for dealing with Arrays.
+*
+* @class Phaser.ArrayUtils
+* @static
+*/
+Phaser.ArrayUtils = {
+
+    /**
+    * Fetch a random entry from the given array.
+    *
+    * Will return null if there are no array items that fall within the specified range
+    * or if there is no item for the randomly choosen index.
+    *
+    * @method
+    * @param {any[]} objects - An array of objects.
+    * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
+    * @param {integer} length - Optional restriction on the number of values you want to randomly select from.
+    * @return {object} The random object that was selected.
+    */
+    getRandomItem: function (objects, startIndex, length) {
+
+        if (objects == null) { // undefined or null
+            return null;
+        }
+
+        if (startIndex === undefined) { startIndex = 0; }
+        if (length === undefined) { length = objects.length; }
+
+        var randomIndex = startIndex + Math.floor(Math.random() * length);
+        return objects[randomIndex] === undefined ? null : objects[randomIndex];
+
+    },
+
+    /**
+    * Removes a random object from the given array and returns it.
+    *
+    * Will return null if there are no array items that fall within the specified range
+    * or if there is no item for the randomly choosen index.
+    *
+    * @method
+    * @param {any[]} objects - An array of objects.
+    * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
+    * @param {integer} length - Optional restriction on the number of values you want to randomly select from.
+    * @return {object} The random object that was removed.
+    */
+    removeRandomItem: function (objects, startIndex, length) {
+
+        if (objects == null) { // undefined or null
+            return null;
+        }
+
+        if (startIndex === undefined) { startIndex = 0; }
+        if (length === undefined) { length = objects.length; }
+
+        var randomIndex = startIndex + Math.floor(Math.random() * length);
+        if (randomIndex < objects.length)
+        {
+            var removed = objects.splice(randomIndex, 1);
+            return removed[0] === undefined ? null : removed[0];
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * A standard Fisher-Yates Array shuffle implementation which modifies the array in place.
+    *
+    * @method
+    * @param {any[]} array - The array to shuffle.
+    * @return {any[]} The original array, now shuffled.
+    */
+    shuffle: function (array) {
+
+        for (var i = array.length - 1; i > 0; i--)
+        {
+            var j = Math.floor(Math.random() * (i + 1));
+            var temp = array[i];
+            array[i] = array[j];
+            array[j] = temp;
+        }
+
+        return array;
+
+    },
+
+    /**
+    * Transposes the elements of the given matrix (array of arrays).
+    *
+    * @method
+    * @param {Array<any[]>} array - The matrix to transpose.
+    * @return {Array<any[]>} A new transposed matrix
+    */
+    transposeMatrix: function (array) {
+
+        var sourceRowCount = array.length;
+        var sourceColCount = array[0].length;
+
+        var result = new Array(sourceColCount);
+
+        for (var i = 0; i < sourceColCount; i++)
+        {
+            result[i] = new Array(sourceRowCount);
+
+            for (var j = sourceRowCount - 1; j > -1; j--)
+            {
+                result[i][j] = array[j][i];
+            }
+        }
+
+        return result;
+
+    },
+
+    /**
+    * Rotates the given matrix (array of arrays).
+    *
+    * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}.
+    *
+    * @method
+    * @param {Array<any[]>} matrix - The array to rotate; this matrix _may_ be altered.
+    * @param {number|string} direction - The amount to rotate: the roation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
+    * @return {Array<any[]>} The rotated matrix. The source matrix should be discarded for the returned matrix.
+    */
+    rotateMatrix: function (matrix, direction) {
+
+        if (typeof direction !== 'string')
+        {
+            direction = ((direction % 360) + 360) % 360;
+        }
+
+        if (direction === 90 || direction === -270 || direction === 'rotateLeft')
+        {
+            matrix = Phaser.ArrayUtils.transposeMatrix(matrix);
+            matrix = matrix.reverse();
+        }
+        else if (direction === -90 || direction === 270 || direction === 'rotateRight')
+        {
+            matrix = matrix.reverse();
+            matrix = Phaser.ArrayUtils.transposeMatrix(matrix);
+        }
+        else if (Math.abs(direction) === 180 || direction === 'rotate180')
+        {
+            for (var i = 0; i < matrix.length; i++)
+            {
+                matrix[i].reverse();
+            }
+
+            matrix = matrix.reverse();
+        }
+
+        return matrix;
+
+    },
+
+    /**
+    * Snaps a value to the nearest value in an array.
+    * The result will always be in the range `[first_value, last_value]`.
+    *
+    * @method
+    * @param {number} value - The search value
+    * @param {number[]} arr - The input array which _must_ be sorted.
+    * @return {number} The nearest value found.
+    */
+    findClosest: function (value, arr) {
+
+        if (!arr.length)
+        {
+            return NaN;
+        }
+        else if (arr.length === 1 || value < arr[0])
+        {
+            return arr[0];
+        }
+
+        var i = 1;
+        while (arr[i] < value) {
+            i++;
+        }
+
+        var low = arr[i - 1];
+        var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
+
+        return ((high - value) <= (value - low)) ? high : low;
+
+    },
+
+    /**
+    * Moves the element from the start of the array to the end, shifting all items in the process.
+    * The "rotation" happens to the left.
+    *
+    * @method Phaser.ArrayUtils.rotate
+    * @param {any[]} array - The array to shift/rotate. The array is modified.
+    * @return {any} The shifted value.
+    */
+    rotate: function (array) {
+
+        var s = array.shift();
+        array.push(s);
+
+        return s;
+
+    },
+
+    /**
+    * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]`.
+    * This is equivalent to `numberArrayStep(start, end, 1)`.
+    *
+    * @method Phaser.ArrayUtils#numberArray
+    * @param {number} start - The minimum value the array starts with.
+    * @param {number} end - The maximum value the array contains.
+    * @return {number[]} The array of number values.
+    */
+    numberArray: function (start, end) {
+
+        var result = [];
+
+        for (var i = start; i <= end; i++)
+        {
+            result.push(i);
+        }
+
+        return result;
+
+    },
+
+    /**
+    * Create an array of numbers (positive and/or negative) progressing from `start`
+    * up to but not including `end` by advancing by `step`.
+    *
+    * If `start` is less than `stop` a zero-length range is created unless a negative `step` is specified.
+    *
+    * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0;
+    * for forward compatibility make sure to pass in actual numbers.
+    *
+    * @method Phaser.ArrayUtils#numberArrayStep
+    * @param {number} start - The start of the range.
+    * @param {number} end - The end of the range.
+    * @param {number} [step=1] - The value to increment or decrement by.
+    * @returns {Array} Returns the new array of numbers.
+    * @example
+    * Phaser.ArrayUtils.numberArrayStep(4);
+    * // => [0, 1, 2, 3]
+    *
+    * Phaser.ArrayUtils.numberArrayStep(1, 5);
+    * // => [1, 2, 3, 4]
+    *
+    * Phaser.ArrayUtils.numberArrayStep(0, 20, 5);
+    * // => [0, 5, 10, 15]
+    *
+    * Phaser.ArrayUtils.numberArrayStep(0, -4, -1);
+    * // => [0, -1, -2, -3]
+    *
+    * Phaser.ArrayUtils.numberArrayStep(1, 4, 0);
+    * // => [1, 1, 1]
+    *
+    * Phaser.ArrayUtils.numberArrayStep(0);
+    * // => []
+    */
+    numberArrayStep: function(start, end, step) {
+
+        start = +start || 0;
+
+        // enables use as a callback for functions like `_.map`
+        var type = typeof end;
+
+        if ((type === 'number' || type === 'string') && step && step[end] === start)
+        {
+            end = step = null;
+        }
+
+        step = step == null ? 1 : (+step || 0);
+
+        if (end === null)
+        {
+            end = start;
+            start = 0;
+        }
+        else
+        {
+            end = +end || 0;
+        }
+
+        // use `Array(length)` so engines like Chakra and V8 avoid slower modes
+        // http://youtu.be/XAqIpGU8ZZk#t=17m25s
+        var index = -1;
+        var length = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0);
+        var result = new Array(length);
+
+        while (++index < length)
+        {
+            result[index] = start;
+            start += step;
+        }
+
+        return result;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion.
+*
+* @class Phaser.Color
+*/
+Phaser.Color = {
+
+    /**
+    * Packs the r, g, b, a components into a single integer, for use with Int32Array.
+    * If device is little endian then ABGR order is used. Otherwise RGBA order is used.
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    * @method Phaser.Color.packPixel
+    * @static
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @param {number} a - The alpha color component, in the range 0 - 255.
+    * @return {number} The packed color as uint32
+    */
+    packPixel: function (r, g, b, a) {
+
+        if (Phaser.Device.LITTLE_ENDIAN)
+        {
+            return ( (a << 24) | (b << 16) | (g <<  8) | r ) >>> 0;
+        }
+        else
+        {
+            return ( (r << 24) | (g << 16) | (b <<  8) | a ) >>> 0;
+        }
+
+    },
+
+    /**
+    * Unpacks the r, g, b, a components into the specified color object, or a new
+    * object, for use with Int32Array. If little endian, then ABGR order is used when
+    * unpacking, otherwise, RGBA order is used. The resulting color object has the
+    * `r, g, b, a` properties which are unrelated to endianness.
+    *
+    * Note that the integer is assumed to be packed in the correct endianness. On little-endian
+    * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
+    * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    * @method Phaser.Color.unpackPixel
+    * @static
+    * @param {number} rgba - The integer, packed in endian order by packPixel.
+    * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
+    * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
+    * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
+    * @return {object} An object with the red, green and blue values set in the r, g and b properties.
+    */
+    unpackPixel: function (rgba, out, hsl, hsv) {
+
+        if (out === undefined || out === null) { out = Phaser.Color.createColor(); }
+        if (hsl === undefined || hsl === null) { hsl = false; }
+        if (hsv === undefined || hsv === null) { hsv = false; }
+
+        if (Phaser.Device.LITTLE_ENDIAN)
+        {
+            out.a = ((rgba & 0xff000000) >>> 24);
+            out.b = ((rgba & 0x00ff0000) >>> 16);
+            out.g = ((rgba & 0x0000ff00) >>> 8);
+            out.r = ((rgba & 0x000000ff));
+        }
+        else
+        {
+            out.r = ((rgba & 0xff000000) >>> 24);
+            out.g = ((rgba & 0x00ff0000) >>> 16);
+            out.b = ((rgba & 0x0000ff00) >>> 8);
+            out.a = ((rgba & 0x000000ff));
+        }
+
+        out.color = rgba;
+        out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + (out.a / 255) + ')';
+
+        if (hsl)
+        {
+            Phaser.Color.RGBtoHSL(out.r, out.g, out.b, out);
+        }
+
+        if (hsv)
+        {
+            Phaser.Color.RGBtoHSV(out.r, out.g, out.b, out);
+        }
+
+        return out;
+
+    },
+
+    /**
+    * A utility to convert an integer in 0xRRGGBBAA format to a color object.
+    * This does not rely on endianness.
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    * @method Phaser.Color.fromRGBA
+    * @static
+    * @param {number} rgba - An RGBA hex
+    * @param {object} [out] - The object to use, optional.
+    * @return {object} A color object.
+    */
+    fromRGBA: function (rgba, out) {
+
+        if (!out)
+        {
+            out = Phaser.Color.createColor();
+        }
+
+        out.r = ((rgba & 0xff000000) >>> 24);
+        out.g = ((rgba & 0x00ff0000) >>> 16);
+        out.b = ((rgba & 0x0000ff00) >>> 8);
+        out.a = ((rgba & 0x000000ff));
+
+        out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')';
+
+        return out;
+
+    },
+
+    /**
+    * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    * @method Phaser.Color.toRGBA
+    * @static
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @param {number} a - The alpha color component, in the range 0 - 255.
+    * @return {number} A RGBA-packed 32 bit integer
+    */
+    toRGBA: function (r, g, b, a) {
+
+        return (r << 24) | (g << 16) | (b <<  8) | a;
+
+    },
+
+    /**
+    * Converts an RGB color value to HSL (hue, saturation and lightness).
+    * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
+    * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
+    * Based on code by Michael Jackson (https://github.com/mjijackson)
+    *
+    * @method Phaser.Color.RGBtoHSL
+    * @static
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created.
+    * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties.
+    */
+    RGBtoHSL: function (r, g, b, out) {
+
+        if (!out)
+        {
+            out = Phaser.Color.createColor(r, g, b, 1);
+        }
+
+        r /= 255;
+        g /= 255;
+        b /= 255;
+
+        var min = Math.min(r, g, b);
+        var max = Math.max(r, g, b);
+
+        // achromatic by default
+        out.h = 0;
+        out.s = 0;
+        out.l = (max + min) / 2;
+
+        if (max !== min)
+        {
+            var d = max - min;
+
+            out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min);
+
+            if (max === r)
+            {
+                out.h = (g - b) / d + (g < b ? 6 : 0);
+            }
+            else if (max === g)
+            {
+                out.h = (b - r) / d + 2;
+            }
+            else if (max === b)
+            {
+                out.h = (r - g) / d + 4;
+            }
+
+            out.h /= 6;
+        }
+
+        return out;
+
+    },
+
+    /**
+    * Converts an HSL (hue, saturation and lightness) color value to RGB.
+    * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
+    * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
+    * Based on code by Michael Jackson (https://github.com/mjijackson)
+    *
+    * @method Phaser.Color.HSLtoRGB
+    * @static
+    * @param {number} h - The hue, in the range 0 - 1.
+    * @param {number} s - The saturation, in the range 0 - 1.
+    * @param {number} l - The lightness, in the range 0 - 1.
+    * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
+    * @return {object} An object with the red, green and blue values set in the r, g and b properties.
+    */
+    HSLtoRGB: function (h, s, l, out) {
+
+        if (!out)
+        {
+            out = Phaser.Color.createColor(l, l, l);
+        }
+        else
+        {
+            // achromatic by default
+            out.r = l;
+            out.g = l;
+            out.b = l;
+        }
+
+        if (s !== 0)
+        {
+            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+            var p = 2 * l - q;
+            out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3);
+            out.g = Phaser.Color.hueToColor(p, q, h);
+            out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3);
+        }
+
+        // out.r = (out.r * 255 | 0);
+        // out.g = (out.g * 255 | 0);
+        // out.b = (out.b * 255 | 0);
+
+        out.r = Math.floor((out.r * 255 | 0));
+        out.g = Math.floor((out.g * 255 | 0));
+        out.b = Math.floor((out.b * 255 | 0));
+
+        Phaser.Color.updateColor(out);
+
+        return out;
+
+    },
+
+    /**
+    * Converts an RGB color value to HSV (hue, saturation and value).
+    * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
+    * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
+    * Based on code by Michael Jackson (https://github.com/mjijackson)
+    *
+    * @method Phaser.Color.RGBtoHSV
+    * @static
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created.
+    * @return {object} An object with the hue, saturation and value set in the h, s and v properties.
+    */
+    RGBtoHSV: function (r, g, b, out) {
+
+        if (!out)
+        {
+            out = Phaser.Color.createColor(r, g, b, 255);
+        }
+
+        r /= 255;
+        g /= 255;
+        b /= 255;
+
+        var min = Math.min(r, g, b);
+        var max = Math.max(r, g, b);
+        var d = max - min;
+
+        // achromatic by default
+        out.h = 0;
+        out.s = max === 0 ? 0 : d / max;
+        out.v = max;
+
+        if (max !== min)
+        {
+            if (max === r)
+            {
+                out.h = (g - b) / d + (g < b ? 6 : 0);
+            }
+            else if (max === g)
+            {
+                out.h = (b - r) / d + 2;
+            }
+            else if (max === b)
+            {
+                out.h = (r - g) / d + 4;
+            }
+
+            out.h /= 6;
+        }
+
+        return out;
+
+    },
+
+    /**
+    * Converts an HSV (hue, saturation and value) color value to RGB.
+    * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
+    * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
+    * Based on code by Michael Jackson (https://github.com/mjijackson)
+    *
+    * @method Phaser.Color.HSVtoRGB
+    * @static
+    * @param {number} h - The hue, in the range 0 - 1.
+    * @param {number} s - The saturation, in the range 0 - 1.
+    * @param {number} v - The value, in the range 0 - 1.
+    * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
+    * @return {object} An object with the red, green and blue values set in the r, g and b properties.
+    */
+    HSVtoRGB: function (h, s, v, out) {
+
+        if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); }
+
+        var r, g, b;
+        var i = Math.floor(h * 6);
+        var f = h * 6 - i;
+        var p = v * (1 - s);
+        var q = v * (1 - f * s);
+        var t = v * (1 - (1 - f) * s);
+
+        switch (i % 6)
+        {
+            case 0:
+                r = v;
+                g = t;
+                b = p;
+                break;
+            case 1:
+                r = q;
+                g = v;
+                b = p;
+                break;
+            case 2:
+                r = p;
+                g = v;
+                b = t;
+                break;
+            case 3:
+                r = p;
+                g = q;
+                b = v;
+                break;
+            case 4:
+                r = t;
+                g = p;
+                b = v;
+                break;
+            case 5:
+                r = v;
+                g = p;
+                b = q;
+                break;
+        }
+
+        out.r = Math.floor(r * 255);
+        out.g = Math.floor(g * 255);
+        out.b = Math.floor(b * 255);
+
+        Phaser.Color.updateColor(out);
+
+        return out;
+
+    },
+
+    /**
+    * Converts a hue to an RGB color.
+    * Based on code by Michael Jackson (https://github.com/mjijackson)
+    *
+    * @method Phaser.Color.hueToColor
+    * @static
+    * @param {number} p
+    * @param {number} q
+    * @param {number} t
+    * @return {number} The color component value.
+    */
+    hueToColor: function (p, q, t) {
+
+        if (t < 0)
+        {
+            t += 1;
+        }
+
+        if (t > 1)
+        {
+            t -= 1;
+        }
+
+        if (t < 1 / 6)
+        {
+            return p + (q - p) * 6 * t;
+        }
+
+        if (t < 1 / 2)
+        {
+            return q;
+        }
+
+        if (t < 2 / 3)
+        {
+            return p + (q - p) * (2 / 3 - t) * 6;
+        }
+
+        return p;
+
+    },
+
+    /**
+    * A utility function to create a lightweight 'color' object with the default components.
+    * Any components that are not specified will default to zero.
+    *
+    * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
+    *
+    * @author Matt DesLauriers (@mattdesl)
+    * @method Phaser.Color.createColor
+    * @static
+    * @param {number} [r=0] - The red color component, in the range 0 - 255.
+    * @param {number} [g=0] - The green color component, in the range 0 - 255.
+    * @param {number} [b=0] - The blue color component, in the range 0 - 255.
+    * @param {number} [a=1] - The alpha color component, in the range 0 - 1.
+    * @param {number} [h=0] - The hue, in the range 0 - 1.
+    * @param {number} [s=0] - The saturation, in the range 0 - 1.
+    * @param {number} [l=0] - The lightness, in the range 0 - 1.
+    * @param {number} [v=0] - The value, in the range 0 - 1.
+    * @return {object} The resulting object with r, g, b, a properties and h, s, l and v.
+    */
+    createColor: function (r, g, b, a, h, s, l, v) {
+
+        var out = { r: r || 0, g: g || 0, b: b || 0, a: a || 1, h: h || 0, s: s || 0, l: l || 0, v: v || 0, color: 0, color32: 0, rgba: '' };
+
+        return Phaser.Color.updateColor(out);
+
+    },
+
+    /**
+    * Takes a color object and updates the rgba property.
+    *
+    * @method Phaser.Color.updateColor
+    * @static
+    * @param {object} out - The color object to update.
+    * @returns {number} A native color value integer (format: 0xAARRGGBB).
+    */
+    updateColor: function (out) {
+
+        out.rgba = 'rgba(' + out.r.toString() + ',' + out.g.toString() + ',' + out.b.toString() + ',' + out.a.toString() + ')';
+        out.color = Phaser.Color.getColor(out.r, out.g, out.b);
+        out.color32 = Phaser.Color.getColor32(out.a, out.r, out.g, out.b);
+
+        return out;
+
+    },
+
+    /**
+    * Given an alpha and 3 color values this will return an integer representation of it.
+    *
+    * @method Phaser.Color.getColor32
+    * @static
+    * @param {number} a - The alpha color component, in the range 0 - 255.
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @returns {number} A native color value integer (format: 0xAARRGGBB).
+    */
+    getColor32: function (a, r, g, b) {
+
+        return a << 24 | r << 16 | g << 8 | b;
+
+    },
+
+    /**
+    * Given 3 color values this will return an integer representation of it.
+    *
+    * @method Phaser.Color.getColor
+    * @static
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @returns {number} A native color value integer (format: 0xRRGGBB).
+    */
+    getColor: function (r, g, b) {
+
+        return r << 16 | g << 8 | b;
+
+    },
+
+    /**
+    * Converts the given color values into a string.
+    * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
+    *
+    * @method Phaser.Color.RGBtoString
+    * @static
+    * @param {number} r - The red color component, in the range 0 - 255.
+    * @param {number} g - The green color component, in the range 0 - 255.
+    * @param {number} b - The blue color component, in the range 0 - 255.
+    * @param {number} [a=255] - The alpha color component, in the range 0 - 255.
+    * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
+    * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
+    */
+    RGBtoString: function (r, g, b, a, prefix) {
+
+        if (a === undefined) { a = 255; }
+        if (prefix === undefined) { prefix = '#'; }
+
+        if (prefix === '#')
+        {
+            return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
+        }
+        else
+        {
+            return '0x' + Phaser.Color.componentToHex(a) + Phaser.Color.componentToHex(r) + Phaser.Color.componentToHex(g) + Phaser.Color.componentToHex(b);
+        }
+
+    },
+
+    /**
+    * Converts a hex string into an integer color value.
+    *
+    * @method Phaser.Color.hexToRGB
+    * @static
+    * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
+    * @return {number} The rgb color value in the format 0xAARRGGBB.
+    */
+    hexToRGB: function (hex) {
+
+        var rgb = Phaser.Color.hexToColor(hex);
+
+        if (rgb)
+        {
+            return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b);
+        }
+
+    },
+
+    /**
+    * Converts a hex string into a Phaser Color object.
+    *
+    * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed.    
+    *
+    * An alpha channel is _not_ supported.
+    *
+    * @method Phaser.Color.hexToColor
+    * @static
+    * @param {string} hex - The color string in a hex format.
+    * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created.
+    * @return {object} An object with the red, green and blue values set in the r, g and b properties.
+    */
+    hexToColor: function (hex, out) {
+
+        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
+        hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) {
+            return r + r + g + g + b + b;
+        });
+
+        var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+
+        if (result)
+        {
+            var r = parseInt(result[1], 16);
+            var g = parseInt(result[2], 16);
+            var b = parseInt(result[3], 16);
+
+            if (!out)
+            {
+                out = Phaser.Color.createColor(r, g, b);
+            }
+            else
+            {
+                out.r = r;
+                out.g = g;
+                out.b = b;
+            }
+        }
+
+        return out;
+
+    },
+
+    /**
+    * Converts a CSS 'web' string into a Phaser Color object.
+    *
+    * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1].
+    *
+    * @method Phaser.Color.webToColor
+    * @static
+    * @param {string} web - The color string in CSS 'web' format.
+    * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
+    * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
+    */
+    webToColor: function (web, out) {
+
+        if (!out)
+        {
+            out = Phaser.Color.createColor();
+        }
+
+        var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web);
+
+        if (result)
+        {
+            out.r = parseInt(result[1], 10);
+            out.g = parseInt(result[2], 10);
+            out.b = parseInt(result[3], 10);
+            out.a = result[4] !== undefined ? parseFloat(result[4]) : 1;
+            Phaser.Color.updateColor(out);
+        }
+
+        return out;
+
+    },
+
+    /**
+    * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components.
+    *
+    * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`).
+    *
+    * An alpha channel is _not_ supported when specifying a hex string.
+    *
+    * @method Phaser.Color.valueToColor
+    * @static
+    * @param {string|number} value - The color expressed as a recognized string format or a packed integer.
+    * @param {object} [out] - The object to use for the output. If not provided a new object will be created.
+    * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties.
+    */
+    valueToColor: function (value, out) {
+
+        //  The behavior is not consistent between hexToColor/webToColor on invalid input.
+        //  This unifies both by returning a new object, but returning null may be better.
+        if (!out)
+        {
+            out = Phaser.Color.createColor();
+        }
+
+        if (typeof value === 'string')
+        {
+            if (value.indexOf('rgb') === 0)
+            {
+                return Phaser.Color.webToColor(value, out);
+            }
+            else
+            {
+                //  `hexToColor` does not support alpha; match `createColor`.
+                out.a = 1;
+                return Phaser.Color.hexToColor(value, out);
+            }
+        }
+        else if (typeof value === 'number')
+        {
+            //  `getRGB` does not take optional object to modify;
+            //  alpha is also adjusted to match `createColor`.
+            var tempColor = Phaser.Color.getRGB(value);
+            out.r = tempColor.r;
+            out.g = tempColor.g;
+            out.b = tempColor.b;
+            out.a = tempColor.a / 255;
+            return out;
+        }
+        else
+        {
+            return out;
+        }
+
+    },
+
+    /**
+    * Return a string containing a hex representation of the given color component.
+    *
+    * @method Phaser.Color.componentToHex
+    * @static
+    * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255.
+    * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64.
+    */
+    componentToHex: function (color) {
+
+        var hex = color.toString(16);
+        return hex.length == 1 ? "0" + hex : hex;
+
+    },
+
+    /**
+    * Get HSV color wheel values in an array which will be 360 elements in size.
+    *
+    * @method Phaser.Color.HSVColorWheel
+    * @static
+    * @param {number} [s=1] - The saturation, in the range 0 - 1.
+    * @param {number} [v=1] - The value, in the range 0 - 1.
+    * @return {array} An array containing 360 elements corresponding to the HSV color wheel.
+    */
+    HSVColorWheel: function (s, v) {
+
+        if (s === undefined) { s = 1.0; }
+        if (v === undefined) { v = 1.0; }
+
+        var colors = [];
+
+        for (var c = 0; c <= 359; c++)
+        {
+            colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v));
+        }
+
+        return colors;
+
+    },
+
+    /**
+    * Get HSL color wheel values in an array which will be 360 elements in size.
+    *
+    * @method Phaser.Color.HSLColorWheel
+    * @static
+    * @param {number} [s=0.5] - The saturation, in the range 0 - 1.
+    * @param {number} [l=0.5] - The lightness, in the range 0 - 1.
+    * @return {array} An array containing 360 elements corresponding to the HSL color wheel.
+    */
+    HSLColorWheel: function (s, l) {
+
+        if (s === undefined) { s = 0.5; }
+        if (l === undefined) { l = 0.5; }
+
+        var colors = [];
+
+        for (var c = 0; c <= 359; c++)
+        {
+            colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l));
+        }
+
+        return colors;
+
+    },
+
+    /**
+    * Interpolates the two given colours based on the supplied step and currentStep properties.
+    *
+    * @method Phaser.Color.interpolateColor
+    * @static
+    * @param {number} color1 - The first color value.
+    * @param {number} color2 - The second color value.
+    * @param {number} steps - The number of steps to run the interpolation over.
+    * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
+    * @param {number} alpha - The alpha of the returned color.
+    * @returns {number} The interpolated color value.
+    */
+    interpolateColor: function (color1, color2, steps, currentStep, alpha) {
+
+        if (alpha === undefined) { alpha = 255; }
+
+        var src1 = Phaser.Color.getRGB(color1);
+        var src2 = Phaser.Color.getRGB(color2);
+        var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red;
+        var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green;
+        var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue;
+
+        return Phaser.Color.getColor32(alpha, r, g, b);
+
+    },
+
+    /**
+    * Interpolates the two given colours based on the supplied step and currentStep properties.
+    *
+    * @method Phaser.Color.interpolateColorWithRGB
+    * @static
+    * @param {number} color - The first color value.
+    * @param {number} r - The red color value, between 0 and 0xFF (255).
+    * @param {number} g - The green color value, between 0 and 0xFF (255).
+    * @param {number} b - The blue color value, between 0 and 0xFF (255).
+    * @param {number} steps - The number of steps to run the interpolation over.
+    * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
+    * @returns {number} The interpolated color value.
+    */
+    interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) {
+
+        var src = Phaser.Color.getRGB(color);
+        var or = (((r - src.red) * currentStep) / steps) + src.red;
+        var og = (((g - src.green) * currentStep) / steps) + src.green;
+        var ob = (((b - src.blue) * currentStep) / steps) + src.blue;
+
+        return Phaser.Color.getColor(or, og, ob);
+
+    },
+
+    /**
+    * Interpolates the two given colours based on the supplied step and currentStep properties.
+    * @method Phaser.Color.interpolateRGB
+    * @static
+    * @param {number} r1 - The red color value, between 0 and 0xFF (255).
+    * @param {number} g1 - The green color value, between 0 and 0xFF (255).
+    * @param {number} b1 - The blue color value, between 0 and 0xFF (255).
+    * @param {number} r2 - The red color value, between 0 and 0xFF (255).
+    * @param {number} g2 - The green color value, between 0 and 0xFF (255).
+    * @param {number} b2 - The blue color value, between 0 and 0xFF (255).
+    * @param {number} steps - The number of steps to run the interpolation over.
+    * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
+    * @returns {number} The interpolated color value.
+    */
+    interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) {
+
+        var r = (((r2 - r1) * currentStep) / steps) + r1;
+        var g = (((g2 - g1) * currentStep) / steps) + g1;
+        var b = (((b2 - b1) * currentStep) / steps) + b1;
+
+        return Phaser.Color.getColor(r, g, b);
+
+    },
+
+    /**
+    * Returns a random color value between black and white
+    * Set the min value to start each channel from the given offset.
+    * Set the max value to restrict the maximum color used per channel.
+    *
+    * @method Phaser.Color.getRandomColor
+    * @static
+    * @param {number} min - The lowest value to use for the color.
+    * @param {number} max - The highest value to use for the color.
+    * @param {number} alpha - The alpha value of the returning color (default 255 = fully opaque).
+    * @returns {number} 32-bit color value with alpha.
+    */
+    getRandomColor: function (min, max, alpha) {
+
+        if (min === undefined) { min = 0; }
+        if (max === undefined) { max = 255; }
+        if (alpha === undefined) { alpha = 255; }
+
+        //  Sanity checks
+        if (max > 255 || min > max)
+        {
+            return Phaser.Color.getColor(255, 255, 255);
+        }
+
+        var red = min + Math.round(Math.random() * (max - min));
+        var green = min + Math.round(Math.random() * (max - min));
+        var blue = min + Math.round(Math.random() * (max - min));
+
+        return Phaser.Color.getColor32(alpha, red, green, blue);
+
+    },
+
+    /**
+    * Return the component parts of a color as an Object with the properties alpha, red, green, blue.
+    *
+    * Alpha will only be set if it exist in the given color (0xAARRGGBB)
+    *
+    * @method Phaser.Color.getRGB
+    * @static
+    * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
+    * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given.
+    */
+    getRGB: function (color) {
+
+        if (color > 16777215)
+        {
+            //  The color value has an alpha component
+            return {
+                alpha: color >>> 24,
+                red: color >> 16 & 0xFF,
+                green: color >> 8 & 0xFF,
+                blue: color & 0xFF,
+                a: color >>> 24,
+                r: color >> 16 & 0xFF,
+                g: color >> 8 & 0xFF,
+                b: color & 0xFF
+            };
+        }
+        else
+        {
+            return {
+                alpha: 255,
+                red: color >> 16 & 0xFF,
+                green: color >> 8 & 0xFF,
+                blue: color & 0xFF,
+                a: 255,
+                r: color >> 16 & 0xFF,
+                g: color >> 8 & 0xFF,
+                b: color & 0xFF
+            };
+        }
+
+    },
+
+    /**
+    * Returns a CSS friendly string value from the given color.
+    *
+    * @method Phaser.Color.getWebRGB
+    * @static
+    * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
+    * @returns {string} A string in the format: 'rgba(r,g,b,a)'
+    */
+    getWebRGB: function (color) {
+
+        if (typeof color === 'object')
+        {
+            return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')';
+        }
+        else
+        {
+            var rgb = Phaser.Color.getRGB(color);
+            return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')';
+        }
+
+    },
+
+    /**
+    * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
+    *
+    * @method Phaser.Color.getAlpha
+    * @static
+    * @param {number} color - In the format 0xAARRGGBB.
+    * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
+    */
+    getAlpha: function (color) {
+        return color >>> 24;
+    },
+
+    /**
+    * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
+    *
+    * @method Phaser.Color.getAlphaFloat
+    * @static
+    * @param {number} color - In the format 0xAARRGGBB.
+    * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
+    */
+    getAlphaFloat: function (color) {
+        return (color >>> 24) / 255;
+    },
+
+    /**
+    * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
+    *
+    * @method Phaser.Color.getRed
+    * @static
+    * @param {number} color In the format 0xAARRGGBB.
+    * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red).
+    */
+    getRed: function (color) {
+        return color >> 16 & 0xFF;
+    },
+
+    /**
+    * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
+    *
+    * @method Phaser.Color.getGreen
+    * @static
+    * @param {number} color - In the format 0xAARRGGBB.
+    * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green).
+    */
+    getGreen: function (color) {
+        return color >> 8 & 0xFF;
+    },
+
+    /**
+    * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
+    *
+    * @method Phaser.Color.getBlue
+    * @static
+    * @param {number} color - In the format 0xAARRGGBB.
+    * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue).
+    */
+    getBlue: function (color) {
+        return color & 0xFF;
+    },
+
+    /**
+    * Blends the source color, ignoring the backdrop.
+    *
+    * @method Phaser.Color.blendNormal
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendNormal: function (a) {
+        return a;
+    },
+
+    /**
+    * Selects the lighter of the backdrop and source colors.
+    *
+    * @method Phaser.Color.blendLighten
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendLighten: function (a, b) {
+        return (b > a) ? b : a;
+    },
+
+    /**
+    * Selects the darker of the backdrop and source colors.
+    *
+    * @method Phaser.Color.blendDarken
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendDarken: function (a, b) {
+        return (b > a) ? a : b;
+    },
+
+    /**
+    * Multiplies the backdrop and source color values.
+    * The result color is always at least as dark as either of the two constituent
+    * colors. Multiplying any color with black produces black;
+    * multiplying with white leaves the original color unchanged.
+    *
+    * @method Phaser.Color.blendMultiply
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendMultiply: function (a, b) {
+        return (a * b) / 255;
+    },
+
+    /**
+    * Takes the average of the source and backdrop colors.
+    *
+    * @method Phaser.Color.blendAverage
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendAverage: function (a, b) {
+        return (a + b) / 2;
+    },
+
+    /**
+    * Adds the source and backdrop colors together and returns the value, up to a maximum of 255.
+    *
+    * @method Phaser.Color.blendAdd
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendAdd: function (a, b) {
+        return Math.min(255, a + b);
+    },
+
+    /**
+    * Combines the source and backdrop colors and returns their value minus 255.
+    *
+    * @method Phaser.Color.blendSubtract
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendSubtract: function (a, b) {
+        return Math.max(0, a + b - 255);
+    },
+
+    /**
+    * Subtracts the darker of the two constituent colors from the lighter.
+    * 
+    * Painting with white inverts the backdrop color; painting with black produces no change. 
+    *
+    * @method Phaser.Color.blendDifference
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendDifference: function (a, b) {
+        return Math.abs(a - b);
+    },
+
+    /**
+    * Negation blend mode.
+    *
+    * @method Phaser.Color.blendNegation
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendNegation: function (a, b) {
+        return 255 - Math.abs(255 - a - b);
+    },
+
+    /**
+    * Multiplies the complements of the backdrop and source color values, then complements the result.
+    * The result color is always at least as light as either of the two constituent colors. 
+    * Screening any color with white produces white; screening with black leaves the original color unchanged. 
+    *
+    * @method Phaser.Color.blendScreen
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendScreen: function (a, b) {
+        return 255 - (((255 - a) * (255 - b)) >> 8);
+    },
+
+    /**
+    * Produces an effect similar to that of the Difference mode, but lower in contrast. 
+    * Painting with white inverts the backdrop color; painting with black produces no change. 
+    *
+    * @method Phaser.Color.blendExclusion
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendExclusion: function (a, b) {
+        return a + b - 2 * a * b / 255;
+    },
+
+    /**
+    * Multiplies or screens the colors, depending on the backdrop color.
+    * Source colors overlay the backdrop while preserving its highlights and shadows. 
+    * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop.
+    *
+    * @method Phaser.Color.blendOverlay
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendOverlay: function (a, b) {
+        return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255);
+    },
+
+    /**
+    * Darkens or lightens the colors, depending on the source color value. 
+    * 
+    * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; 
+    * this is useful for adding highlights to a scene. 
+    * 
+    * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. 
+    * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; 
+    * if it is equal to 0.5, the backdrop is unchanged.
+    * 
+    * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. 
+    * The effect is similar to shining a diffused spotlight on the backdrop. 
+    *
+    * @method Phaser.Color.blendSoftLight
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendSoftLight: function (a, b) {
+        return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255);
+    },
+
+    /**
+    * Multiplies or screens the colors, depending on the source color value. 
+    * 
+    * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; 
+    * this is useful for adding highlights to a scene. 
+    * 
+    * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; 
+    * this is useful for adding shadows to a scene. 
+    * 
+    * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; 
+    * if it is equal to 0.5, the backdrop is unchanged.
+    * 
+    * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. 
+    *
+    * @method Phaser.Color.blendHardLight
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendHardLight: function (a, b) {
+        return Phaser.Color.blendOverlay(b, a);
+    },
+
+    /**
+    * Brightens the backdrop color to reflect the source color. 
+    * Painting with black produces no change.
+    *
+    * @method Phaser.Color.blendColorDodge
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendColorDodge: function (a, b) {
+        return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b)));
+    },
+
+    /**
+    * Darkens the backdrop color to reflect the source color.
+    * Painting with white produces no change. 
+    *
+    * @method Phaser.Color.blendColorBurn
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendColorBurn: function (a, b) {
+        return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b));
+    },
+
+    /**
+    * An alias for blendAdd, it simply sums the values of the two colors.
+    *
+    * @method Phaser.Color.blendLinearDodge
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendLinearDodge: function (a, b) {
+        return Phaser.Color.blendAdd(a, b);
+    },
+
+    /**
+    * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255.
+    *
+    * @method Phaser.Color.blendLinearBurn
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendLinearBurn: function (a, b) {
+        return Phaser.Color.blendSubtract(a, b);
+    },
+
+    /**
+    * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray).
+    * Dodge applies to values of top layer lighter than middle gray, and burn to darker values.
+    * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases.
+    *
+    * @method Phaser.Color.blendLinearLight
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendLinearLight: function (a, b) {
+        return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128)));
+    },
+
+    /**
+    * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray).
+    * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values.
+    * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom 
+    * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases.
+    *
+    * @method Phaser.Color.blendVividLight
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendVividLight: function (a, b) {
+        return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128)));
+    },
+
+    /**
+    * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change.
+    * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change.
+    *
+    * @method Phaser.Color.blendPinLight
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendPinLight: function (a, b) {
+        return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128)));
+    },
+
+    /**
+    * Runs blendVividLight on the source and backdrop colors.
+    * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0.
+    * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255.
+    * This changes all pixels to primary additive colors (red, green, or blue), white, or black.
+    *
+    * @method Phaser.Color.blendHardMix
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendHardMix: function (a, b) {
+        return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255;
+    },
+
+    /**
+    * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. 
+    *
+    * @method Phaser.Color.blendReflect
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendReflect: function (a, b) {
+        return b === 255 ? b : Math.min(255, (a * a / (255 - b)));
+    },
+
+    /**
+    * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped.
+    *
+    * @method Phaser.Color.blendGlow
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendGlow: function (a, b) {
+        return Phaser.Color.blendReflect(b, a);
+    },
+
+    /**
+    * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result.
+    *
+    * @method Phaser.Color.blendPhoenix
+    * @static
+    * @param {integer} a - The source color to blend, in the range 1 to 255.
+    * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
+    * @returns {integer} The blended color value, in the range 1 to 255.
+    */
+    blendPhoenix: function (a, b) {
+        return Math.min(a, b) - Math.max(a, b) + 255;
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A basic Linked List data structure.
+*
+* This implementation _modifies_ the `prev` and `next` properties of each item added:
+* - The `prev` and `next` properties must be writable and should not be used for any other purpose.
+* - Items _cannot_ be added to multiple LinkedLists at the same time.
+* - Only objects can be added.
+*
+* @class Phaser.LinkedList
+* @constructor
+*/
+Phaser.LinkedList = function () {
+
+    /**
+    * Next element in the list.
+    * @property {object} next
+    * @default
+    */
+    this.next = null;
+
+    /**
+    * Previous element in the list.
+    * @property {object} prev
+    * @default
+    */
+    this.prev = null;
+
+    /**
+    * First element in the list.
+    * @property {object} first
+    * @default
+    */
+    this.first = null;
+
+    /**
+    * Last element in the list.
+    * @property {object} last
+    * @default
+    */
+    this.last = null;
+
+    /**
+    * Number of elements in the list.
+    * @property {integer} total
+    * @default
+    */
+    this.total = 0;
+
+};
+
+Phaser.LinkedList.prototype = {
+
+    /**
+    * Adds a new element to this linked list.
+    *
+    * @method Phaser.LinkedList#add
+    * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
+    * @return {object} The item that was added.
+    */
+    add: function (item) {
+
+        //  If the list is empty
+        if (this.total === 0 && this.first === null && this.last === null)
+        {
+            this.first = item;
+            this.last = item;
+            this.next = item;
+            item.prev = this;
+            this.total++;
+            return item;
+        }
+
+        //  Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
+        this.last.next = item;
+
+        item.prev = this.last;
+
+        this.last = item;
+
+        this.total++;
+
+        return item;
+
+    },
+
+    /**
+    * Resets the first, last, next and previous node pointers in this list.
+    *
+    * @method Phaser.LinkedList#reset
+    */
+    reset: function () {
+
+        this.first = null;
+        this.last = null;
+        this.next = null;
+        this.prev = null;
+        this.total = 0;
+
+    },
+
+    /**
+    * Removes the given element from this linked list if it exists.
+    *
+    * @method Phaser.LinkedList#remove
+    * @param {object} item - The item to be removed from the list.
+    */
+    remove: function (item) {
+
+        if (this.total === 1)
+        {
+            this.reset();
+            item.next = item.prev = null;
+            return;
+        }
+
+        if (item === this.first)
+        {
+            // It was 'first', make 'first' point to first.next
+            this.first = this.first.next;
+        }
+        else if (item === this.last)
+        {
+            // It was 'last', make 'last' point to last.prev
+            this.last = this.last.prev;
+        }
+
+        if (item.prev)
+        {
+            // make item.prev.next point to childs.next instead of item
+            item.prev.next = item.next;
+        }
+
+        if (item.next)
+        {
+            // make item.next.prev point to item.prev instead of item
+            item.next.prev = item.prev;
+        }
+
+        item.next = item.prev = null;
+
+        if (this.first === null )
+        {
+            this.last = null;
+        }
+
+        this.total--;
+
+    },
+
+    /**
+    * Calls a function on all members of this list, using the member as the context for the callback.
+    * The function must exist on the member.
+    *
+    * @method Phaser.LinkedList#callAll
+    * @param {function} callback - The function to call.
+    */
+    callAll: function (callback) {
+
+        if (!this.first || !this.last)
+        {
+            return;
+        }
+
+        var entity = this.first;
+
+        do
+        {
+            if (entity && entity[callback])
+            {
+                entity[callback].call(entity);
+            }
+
+            entity = entity.next;
+
+        }
+        while(entity != this.last.next);
+
+    }
+
+};
+
+Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Physics Manager is responsible for looking after all of the running physics systems.
+* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin.
+* 
+* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game.
+*
+* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the
+* faster (due to being much simpler) Arcade Physics system.
+*
+* @class Phaser.Physics
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
+*/
+Phaser.Physics = function (game, config) {
+
+    config = config || {};
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {object} config - The physics configuration object as passed to the game on creation.
+    */
+    this.config = config;
+
+    /**
+    * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
+    */
+    this.arcade = null;
+
+    /**
+    * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
+    */
+    this.p2 = null;
+
+    /**
+    * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system.
+    */
+    this.ninja = null;
+
+    /**
+    * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system.
+    */
+    this.box2d = null;
+
+    /**
+    * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
+    */
+    this.chipmunk = null;
+
+    /**
+    * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon).
+    */
+    this.matter = null;
+
+    this.parseConfig();
+
+};
+
+/**
+* @const
+* @type {number}
+*/
+Phaser.Physics.ARCADE = 0;
+
+/**
+* @const
+* @type {number}
+*/
+Phaser.Physics.P2JS = 1;
+
+/**
+* @const
+* @type {number}
+*/
+Phaser.Physics.NINJA = 2;
+
+/**
+* @const
+* @type {number}
+*/
+Phaser.Physics.BOX2D = 3;
+
+/**
+* @const
+* @type {number}
+*/
+Phaser.Physics.CHIPMUNK = 4;
+
+/**
+* @const
+* @type {number}
+*/
+Phaser.Physics.MATTERJS = 5;
+
+Phaser.Physics.prototype = {
+
+    /**
+    * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within.
+    *
+    * @method Phaser.Physics#parseConfig
+    */
+    parseConfig: function () {
+
+        if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade'))
+        {
+            //  If Arcade isn't specified, we create it automatically if we can
+            this.arcade = new Phaser.Physics.Arcade(this.game);
+        }
+
+        if (this.config.hasOwnProperty('ninja') && this.config['ninja'] === true && Phaser.Physics.hasOwnProperty('Ninja'))
+        {
+            this.ninja = new Phaser.Physics.Ninja(this.game);
+        }
+
+        if (this.config.hasOwnProperty('p2') && this.config['p2'] === true && Phaser.Physics.hasOwnProperty('P2'))
+        {
+            this.p2 = new Phaser.Physics.P2(this.game, this.config);
+        }
+
+        if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D'))
+        {
+            this.box2d = new Phaser.Physics.BOX2D(this.game, this.config);
+        }
+
+        if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter'))
+        {
+            this.matter = new Phaser.Physics.Matter(this.game, this.config);
+        }
+
+    },
+
+    /**
+    * This will create an instance of the requested physics simulation.
+    * Phaser.Physics.Arcade is running by default, but all others need activating directly.
+    * 
+    * You can start the following physics systems:
+    * 
+    * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman.
+    * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
+    * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io)
+    *
+    * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them.
+    * They are not bundled into the core Phaser library.
+    *
+    * If the physics world has already been created (i.e. in another state in your game) then 
+    * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors 
+    * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`.
+    *
+    * @method Phaser.Physics#startSystem
+    * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D.
+    */
+    startSystem: function (system) {
+
+        if (system === Phaser.Physics.ARCADE)
+        {
+            this.arcade = new Phaser.Physics.Arcade(this.game);
+        }
+        else if (system === Phaser.Physics.P2JS)
+        {
+            if (this.p2 === null)
+            {
+                this.p2 = new Phaser.Physics.P2(this.game, this.config);
+            }
+            else
+            {
+                this.p2.reset();
+            }
+        }
+        else if (system === Phaser.Physics.NINJA)
+        {
+            this.ninja = new Phaser.Physics.Ninja(this.game);
+        }
+        else if (system === Phaser.Physics.BOX2D)
+        {
+            if (this.box2d === null)
+            {
+                this.box2d = new Phaser.Physics.Box2D(this.game, this.config);
+            }
+            else
+            {
+                this.box2d.reset();
+            }
+        }
+        else if (system === Phaser.Physics.MATTERJS)
+        {
+            if (this.matter === null)
+            {
+                this.matter = new Phaser.Physics.Matter(this.game, this.config);
+            }
+            else
+            {
+                this.matter.reset();
+            }
+        }
+
+    },
+
+    /**
+    * This will create a default physics body on the given game object or array of objects.
+    * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
+    * It can be for any of the physics systems that have been started:
+    *
+    * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
+    * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
+    * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
+    * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5
+    * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development)
+    * Phaser.Physics.CHIPMUNK is still in development.
+    *
+    * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the
+    * individual physics systems `enable` methods instead of using this generic one.
+    *
+    * @method Phaser.Physics#enable
+    * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
+    * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
+    * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false.
+    */
+    enable: function (object, system, debug) {
+
+        if (system === undefined) { system = Phaser.Physics.ARCADE; }
+        if (debug === undefined) { debug = false; }
+
+        if (system === Phaser.Physics.ARCADE)
+        {
+            this.arcade.enable(object);
+        }
+        else if (system === Phaser.Physics.P2JS && this.p2)
+        {
+            this.p2.enable(object, debug);
+        }
+        else if (system === Phaser.Physics.NINJA && this.ninja)
+        {
+            this.ninja.enableAABB(object);
+        }
+        else if (system === Phaser.Physics.BOX2D && this.box2d)
+        {
+            this.box2d.enable(object);
+        }
+        else if (system === Phaser.Physics.MATTERJS && this.matter)
+        {
+            this.matter.enable(object);
+        }
+
+    },
+
+    /**
+    * preUpdate checks.
+    *
+    * @method Phaser.Physics#preUpdate
+    * @protected
+    */
+    preUpdate: function () {
+
+        //  ArcadePhysics / Ninja don't have a core to preUpdate
+
+        if (this.p2)
+        {
+            this.p2.preUpdate();
+        }
+
+        if (this.box2d)
+        {
+            this.box2d.preUpdate();
+        }
+
+        if (this.matter)
+        {
+            this.matter.preUpdate();
+        }
+
+    },
+
+    /**
+    * Updates all running physics systems.
+    *
+    * @method Phaser.Physics#update
+    * @protected
+    */
+    update: function () {
+
+        //  ArcadePhysics / Ninja don't have a core to update
+
+        if (this.p2)
+        {
+            this.p2.update();
+        }
+
+        if (this.box2d)
+        {
+            this.box2d.update();
+        }
+
+        if (this.matter)
+        {
+            this.matter.update();
+        }
+
+    },
+
+    /**
+    * Updates the physics bounds to match the world dimensions.
+    *
+    * @method Phaser.Physics#setBoundsToWorld
+    * @protected
+    */
+    setBoundsToWorld: function () {
+
+        if (this.arcade)
+        {
+            this.arcade.setBoundsToWorld();
+        }
+
+        if (this.ninja)
+        {
+            this.ninja.setBoundsToWorld();
+        }
+
+        if (this.p2)
+        {
+            this.p2.setBoundsToWorld();
+        }
+
+        if (this.box2d)
+        {
+            this.box2d.setBoundsToWorld();
+        }
+
+        if (this.matter)
+        {
+            this.matter.setBoundsToWorld();
+        }
+
+    },
+
+    /**
+    * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
+    *
+    * @method Phaser.Physics#clear
+    * @protected
+    */
+    clear: function () {
+
+        if (this.p2)
+        {
+            this.p2.clear();
+        }
+
+        if (this.box2d)
+        {
+            this.box2d.clear();
+        }
+
+        if (this.matter)
+        {
+            this.matter.clear();
+        }
+
+    },
+
+    /**
+    * Resets the active physics system. Called automatically on a Phaser.State swap.
+    *
+    * @method Phaser.Physics#reset
+    * @protected
+    */
+    reset: function () {
+
+        if (this.p2)
+        {
+            this.p2.reset();
+        }
+
+        if (this.box2d)
+        {
+            this.box2d.reset();
+        }
+
+        if (this.matter)
+        {
+            this.matter.reset();
+        }
+
+    },
+
+    /**
+    * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap.
+    *
+    * @method Phaser.Physics#destroy
+    */
+    destroy: function () {
+
+        if (this.p2)
+        {
+            this.p2.destroy();
+        }
+
+        if (this.box2d)
+        {
+            this.box2d.destroy();
+        }
+
+        if (this.matter)
+        {
+            this.matter.destroy();
+        }
+
+        this.arcade = null;
+        this.ninja = null;
+        this.p2 = null;
+        this.box2d = null;
+        this.matter = null;
+
+    }
+
+};
+
+Phaser.Physics.prototype.constructor = Phaser.Physics;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods.
+*
+* @class Phaser.Physics.Arcade
+* @constructor
+* @param {Phaser.Game} game - reference to the current game instance.
+*/
+Phaser.Physics.Arcade = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
+    */
+    this.gravity = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
+    */
+    this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
+
+    /**
+    * Set the checkCollision properties to control for which bounds collision is processed.
+    * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom.
+    * @property {object} checkCollision - An object containing allowed collision flags.
+    */
+    this.checkCollision = { up: true, down: true, left: true, right: true };
+
+    /**
+    * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
+    */
+    this.maxObjects = 10;
+
+    /**
+    * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
+    */
+    this.maxLevels = 4;
+
+    /**
+    * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
+    */
+    this.OVERLAP_BIAS = 4;
+
+    /**
+    * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first.
+    */
+    this.forceX = false;
+
+    /**
+    * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT.
+    * @default
+    */
+    this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT;
+
+    /**
+    * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`.
+    */
+    this.skipQuadTree = true;
+
+    /**
+    * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies.
+    */
+    this.isPaused = false;
+
+    /**
+    * @property {Phaser.QuadTree} quadTree - The world QuadTree.
+    */
+    this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
+
+    /**
+    * @property {number} _total - Internal cache var.
+    * @private
+    */
+    this._total = 0;
+
+    // By default we want the bounds the same size as the world bounds
+    this.setBoundsToWorld();
+
+};
+
+Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade;
+
+/**
+* A constant used for the sortDirection value.
+* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups.
+* @constant
+* @type {number}
+*/
+Phaser.Physics.Arcade.SORT_NONE = 0;
+
+/**
+* A constant used for the sortDirection value.
+* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario)
+* @constant
+* @type {number}
+*/
+Phaser.Physics.Arcade.LEFT_RIGHT = 1;
+
+/**
+* A constant used for the sortDirection value.
+* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards)
+* @constant
+* @type {number}
+*/
+Phaser.Physics.Arcade.RIGHT_LEFT = 2;
+
+/**
+* A constant used for the sortDirection value.
+* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug)
+* @constant
+* @type {number}
+*/
+Phaser.Physics.Arcade.TOP_BOTTOM = 3;
+
+/**
+* A constant used for the sortDirection value.
+* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up)
+* @constant
+* @type {number}
+*/
+Phaser.Physics.Arcade.BOTTOM_TOP = 4;
+
+Phaser.Physics.Arcade.prototype = {
+
+    /**
+    * Updates the size of this physics world.
+    *
+    * @method Phaser.Physics.Arcade#setBounds
+    * @param {number} x - Top left most corner of the world.
+    * @param {number} y - Top left most corner of the world.
+    * @param {number} width - New width of the world. Can never be smaller than the Game.width.
+    * @param {number} height - New height of the world. Can never be smaller than the Game.height.
+    */
+    setBounds: function (x, y, width, height) {
+
+        this.bounds.setTo(x, y, width, height);
+
+    },
+
+    /**
+    * Updates the size of this physics world to match the size of the game world.
+    *
+    * @method Phaser.Physics.Arcade#setBoundsToWorld
+    */
+    setBoundsToWorld: function () {
+
+        this.bounds.copyFrom(this.game.world.bounds);
+
+    },
+
+    /**
+    * This will create an Arcade Physics body on the given game object or array of game objects.
+    * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
+    *
+    * @method Phaser.Physics.Arcade#enable
+    * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
+    * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
+    */
+    enable: function (object, children) {
+
+        if (children === undefined) { children = true; }
+
+        var i = 1;
+
+        if (Array.isArray(object))
+        {
+            i = object.length;
+
+            while (i--)
+            {
+                if (object[i] instanceof Phaser.Group)
+                {
+                    //  If it's a Group then we do it on the children regardless
+                    this.enable(object[i].children, children);
+                }
+                else
+                {
+                    this.enableBody(object[i]);
+
+                    if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
+                    {
+                        this.enable(object[i], true);
+                    }
+                }
+            }
+        }
+        else
+        {
+            if (object instanceof Phaser.Group)
+            {
+                //  If it's a Group then we do it on the children regardless
+                this.enable(object.children, children);
+            }
+            else
+            {
+                this.enableBody(object);
+
+                if (children && object.hasOwnProperty('children') && object.children.length > 0)
+                {
+                    this.enable(object.children, true);
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Creates an Arcade Physics body on the given game object.
+    * 
+    * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
+    *
+    * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array.
+    *
+    * @method Phaser.Physics.Arcade#enableBody
+    * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
+    */
+    enableBody: function (object) {
+
+        if (object.hasOwnProperty('body') && object.body === null)
+        {
+            object.body = new Phaser.Physics.Arcade.Body(object);
+
+            if (object.parent && object.parent instanceof Phaser.Group)
+            {
+                object.parent.addToHash(object);
+            }
+        }
+
+    },
+
+    /**
+    * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`.
+    *
+    * @method Phaser.Physics.Arcade#updateMotion
+    * @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
+    */
+    updateMotion: function (body) {
+
+        var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity;
+        body.angularVelocity += velocityDelta;
+        body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
+
+        body.velocity.x = this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x);
+        body.velocity.y = this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y);
+
+    },
+
+    /**
+    * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
+    * Based on a function in Flixel by @ADAMATOMIC
+    *
+    * @method Phaser.Physics.Arcade#computeVelocity
+    * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical.
+    * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated.
+    * @param {number} velocity - Any component of velocity (e.g. 20).
+    * @param {number} acceleration - Rate at which the velocity is changing.
+    * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
+    * @param {number} [max=10000] - An absolute value cap for the velocity.
+    * @return {number} The altered Velocity value.
+    */
+    computeVelocity: function (axis, body, velocity, acceleration, drag, max) {
+
+        if (max === undefined) { max = 10000; }
+
+        if (axis === 1 && body.allowGravity)
+        {
+            velocity += (this.gravity.x + body.gravity.x) * this.game.time.physicsElapsed;
+        }
+        else if (axis === 2 && body.allowGravity)
+        {
+            velocity += (this.gravity.y + body.gravity.y) * this.game.time.physicsElapsed;
+        }
+
+        if (acceleration)
+        {
+            velocity += acceleration * this.game.time.physicsElapsed;
+        }
+        else if (drag)
+        {
+            drag *= this.game.time.physicsElapsed;
+
+            if (velocity - drag > 0)
+            {
+                velocity -= drag;
+            }
+            else if (velocity + drag < 0)
+            {
+                velocity += drag;
+            }
+            else
+            {
+                velocity = 0;
+            }
+        }
+
+        if (velocity > max)
+        {
+            velocity = max;
+        }
+        else if (velocity < -max)
+        {
+            velocity = -max;
+        }
+
+        return velocity;
+
+    },
+
+    /**
+    * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
+    * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
+    * Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
+    * Both the first and second parameter can be arrays of objects, of differing types.
+    * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
+    * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups within Groups).
+    *
+    * @method Phaser.Physics.Arcade#overlap
+    * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
+    * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
+    * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.  The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter.
+    * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true.
+    * @param {object} [callbackContext] - The context in which to run the callbacks.
+    * @return {boolean} True if an overlap occurred otherwise false.
+    */
+    overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
+
+        overlapCallback = overlapCallback || null;
+        processCallback = processCallback || null;
+        callbackContext = callbackContext || overlapCallback;
+
+        this._total = 0;
+
+        if (!Array.isArray(object1) && Array.isArray(object2))
+        {
+            for (var i = 0; i < object2.length; i++)
+            {
+                this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
+            }
+        }
+        else if (Array.isArray(object1) && !Array.isArray(object2))
+        {
+            for (var i = 0; i < object1.length; i++)
+            {
+                this.collideHandler(object1[i], object2, overlapCallback, processCallback, callbackContext, true);
+            }
+        }
+        else if (Array.isArray(object1) && Array.isArray(object2))
+        {
+            for (var i = 0; i < object1.length; i++)
+            {
+                for (var j = 0; j < object2.length; j++)
+                {
+                    this.collideHandler(object1[i], object2[j], overlapCallback, processCallback, callbackContext, true);
+                }
+            }
+        }
+        else
+        {
+            this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
+        }
+
+        return (this._total > 0);
+
+    },
+
+    /**
+    * Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
+    * Both the first and second parameter can be arrays of objects, of differing types.
+    * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
+    * The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
+    * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
+    * giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
+    * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
+    * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups).
+    *
+    * @method Phaser.Physics.Arcade#collide
+    * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
+    * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer.
+    * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
+    * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} [callbackContext] - The context in which to run the callbacks.
+    * @return {boolean} True if a collision occurred otherwise false.
+    */
+    collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
+
+        collideCallback = collideCallback || null;
+        processCallback = processCallback || null;
+        callbackContext = callbackContext || collideCallback;
+
+        this._total = 0;
+
+        if (!Array.isArray(object1) && Array.isArray(object2))
+        {
+            for (var i = 0; i < object2.length; i++)
+            {
+                this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
+            }
+        }
+        else if (Array.isArray(object1) && !Array.isArray(object2))
+        {
+            for (var i = 0; i < object1.length; i++)
+            {
+                this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, false);
+            }
+        }
+        else if (Array.isArray(object1) && Array.isArray(object2))
+        {
+            for (var i = 0; i < object1.length; i++)
+            {
+                for (var j = 0; j < object2.length; j++)
+                {
+                    this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, false);
+                }
+            }
+        }
+        else
+        {
+            this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
+        }
+
+        return (this._total > 0);
+
+    },
+
+    /**
+     * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction.
+     *
+     * This is called automatically by World.sort
+     *
+     * @method Phaser.Physics.Arcade#sortLeftRight
+     * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
+     */
+    sortLeftRight: function (a, b) {
+
+        if (!a.body || !b.body)
+        {
+            return 0;
+        }
+
+        return a.body.x - b.body.x;
+
+    },
+
+    /**
+     * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction.
+     *
+     * This is called automatically by World.sort
+     *
+     * @method Phaser.Physics.Arcade#sortRightLeft
+     * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
+     */
+    sortRightLeft: function (a, b) {
+
+        if (!a.body || !b.body)
+        {
+            return 0;
+        }
+
+        return b.body.x - a.body.x;
+
+    },
+
+    /**
+     * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction.
+     *
+     * This is called automatically by World.sort
+     *
+     * @method Phaser.Physics.Arcade#sortTopBottom
+     * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
+     */
+    sortTopBottom: function (a, b) {
+
+        if (!a.body || !b.body)
+        {
+            return 0;
+        }
+
+        return a.body.y - b.body.y;
+
+    },
+
+    /**
+     * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction.
+     *
+     * This is called automatically by World.sort
+     *
+     * @method Phaser.Physics.Arcade#sortBottomTop
+     * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
+     * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
+     */
+    sortBottomTop: function (a, b) {
+
+        if (!a.body || !b.body)
+        {
+            return 0;
+        }
+
+        return b.body.y - a.body.y;
+
+    },
+
+    /**
+     * This method will sort a Groups hash array.
+     *
+     * If the Group has `physicsSortDirection` set it will use the sort direction defined.
+     *
+     * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection.
+     *
+     * By changing Group.physicsSortDirection you can customise each Group to sort in a different order.
+     *
+     * @method Phaser.Physics.Arcade#sort
+     * @param {Phaser.Group} group - The Group to sort.
+     * @param {integer} [sortDirection] - The sort direction used to sort this Group.
+     */
+    sort: function (group, sortDirection) {
+
+        if (group.physicsSortDirection !== null)
+        {
+            sortDirection = group.physicsSortDirection;
+        }
+        else
+        {
+            if (sortDirection === undefined) { sortDirection = this.sortDirection; }
+        }
+
+        if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
+        {
+            //  Game world is say 2000x600 and you start at 0
+            group.hash.sort(this.sortLeftRight);
+        }
+        else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
+        {
+            //  Game world is say 2000x600 and you start at 2000
+            group.hash.sort(this.sortRightLeft);
+        }
+        else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
+        {
+            //  Game world is say 800x2000 and you start at 0
+            group.hash.sort(this.sortTopBottom);
+        }
+        else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
+        {
+            //  Game world is say 800x2000 and you start at 2000
+            group.hash.sort(this.sortBottomTop);
+        }
+
+    },
+
+    /**
+    * Internal collision handler.
+    *
+    * @method Phaser.Physics.Arcade#collideHandler
+    * @private
+    * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
+    * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    */
+    collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        //  Only collide valid objects
+        if (object2 === undefined && object1.physicsType === Phaser.GROUP)
+        {
+            this.sort(object1);
+            this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
+            return;
+        }
+
+        //  If neither of the objects are set or exist then bail out
+        if (!object1 || !object2 || !object1.exists || !object2.exists)
+        {
+            return;
+        }
+
+        //  Groups? Sort them
+        if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE)
+        {
+            if (object1.physicsType === Phaser.GROUP)
+            {
+                this.sort(object1);
+            }
+
+            if (object2.physicsType === Phaser.GROUP)
+            {
+                this.sort(object2);
+            }
+        }
+
+        //  SPRITES
+        if (object1.physicsType === Phaser.SPRITE)
+        {
+            if (object2.physicsType === Phaser.SPRITE)
+            {
+                this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+            else if (object2.physicsType === Phaser.GROUP)
+            {
+                this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+            else if (object2.physicsType === Phaser.TILEMAPLAYER)
+            {
+                this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+        }
+        //  GROUPS
+        else if (object1.physicsType === Phaser.GROUP)
+        {
+            if (object2.physicsType === Phaser.SPRITE)
+            {
+                this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+            else if (object2.physicsType === Phaser.GROUP)
+            {
+                this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+            else if (object2.physicsType === Phaser.TILEMAPLAYER)
+            {
+                this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+        }
+        //  TILEMAP LAYERS
+        else if (object1.physicsType === Phaser.TILEMAPLAYER)
+        {
+            if (object2.physicsType === Phaser.SPRITE)
+            {
+                this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+            else if (object2.physicsType === Phaser.GROUP)
+            {
+                this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+        }
+
+    },
+
+    /**
+    * An internal function. Use Phaser.Physics.Arcade.collide instead.
+    *
+    * @method Phaser.Physics.Arcade#collideSpriteVsSprite
+    * @private
+    * @param {Phaser.Sprite} sprite1 - The first sprite to check.
+    * @param {Phaser.Sprite} sprite2 - The second sprite to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    * @return {boolean} True if there was a collision, otherwise false.
+    */
+    collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        if (!sprite1.body || !sprite2.body)
+        {
+            return false;
+        }
+
+        if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
+        {
+            if (collideCallback)
+            {
+                collideCallback.call(callbackContext, sprite1, sprite2);
+            }
+
+            this._total++;
+        }
+
+        return true;
+
+    },
+
+    /**
+    * An internal function. Use Phaser.Physics.Arcade.collide instead.
+    *
+    * @method Phaser.Physics.Arcade#collideSpriteVsGroup
+    * @private
+    * @param {Phaser.Sprite} sprite - The sprite to check.
+    * @param {Phaser.Group} group - The Group to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    */
+    collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        if (group.length === 0 || !sprite.body)
+        {
+            return;
+        }
+
+        var body;
+
+        if (this.skipQuadTree || sprite.body.skipQuadTree)
+        {
+            for (var i = 0; i < group.hash.length; i++)
+            {
+                //  Skip duff entries - we can't check a non-existent sprite or one with no body
+                if (!group.hash[i] || !group.hash[i].exists || !group.hash[i].body)
+                {
+                    continue;
+                }
+
+                body = group.hash[i].body;
+
+                //  Skip items either side of the sprite
+                if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
+                {
+                    if (sprite.body.right < body.x)
+                    {
+                        break;
+                    }
+                    else if (body.right < sprite.body.x)
+                    {
+                        continue;
+                    }
+                }
+                else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
+                {
+                    if (sprite.body.x > body.right)
+                    {
+                        break;
+                    }
+                    else if (body.x > sprite.body.right)
+                    {
+                        continue;
+                    }
+                }
+                else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
+                {
+                    if (sprite.body.bottom < body.y)
+                    {
+                        break;
+                    }
+                    else if (body.bottom < sprite.body.y)
+                    {
+                        continue;
+                    }
+                }
+                else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
+                {
+                    if (sprite.body.y > body.bottom)
+                    {
+                        break;
+                    }
+                    else if (body.y > sprite.body.bottom)
+                    {
+                        continue;
+                    }
+                }
+                
+                this.collideSpriteVsSprite(sprite, group.hash[i], collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+        }
+        else
+        {
+            //  What is the sprite colliding with in the quadtree?
+            this.quadTree.clear();
+
+            this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
+
+            this.quadTree.populate(group);
+
+            var items = this.quadTree.retrieve(sprite);
+
+            for (var i = 0; i < items.length; i++)
+            {
+                //  We have our potential suspects, are they in this group?
+                if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly))
+                {
+                    if (collideCallback)
+                    {
+                        collideCallback.call(callbackContext, sprite, items[i].sprite);
+                    }
+
+                    this._total++;
+                }
+            }
+        }
+
+    },
+
+    /**
+    * An internal function. Use Phaser.Physics.Arcade.collide instead.
+    *
+    * @method Phaser.Physics.Arcade#collideGroupVsSelf
+    * @private
+    * @param {Phaser.Group} group - The Group to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    * @return {boolean} True if there was a collision, otherwise false.
+    */
+    collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        if (group.length === 0)
+        {
+            return;
+        }
+
+        for (var i = 0; i < group.hash.length; i++)
+        {
+            //  Skip duff entries - we can't check a non-existent sprite or one with no body
+            if (!group.hash[i] || !group.hash[i].exists || !group.hash[i].body)
+            {
+                continue;
+            }
+
+            var object1 = group.hash[i];
+
+            for (var j = i + 1; j < group.hash.length; j++)
+            {
+                //  Skip duff entries - we can't check a non-existent sprite or one with no body
+                if (!group.hash[j] || !group.hash[j].exists || !group.hash[j].body)
+                {
+                    continue;
+                }
+
+                var object2 = group.hash[j];
+
+                //  Skip items either side of the sprite
+                if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
+                {
+                    if (object1.body.right < object2.body.x)
+                    {
+                        break;
+                    }
+                    else if (object2.body.right < object1.body.x)
+                    {
+                        continue;
+                    }
+                }
+                else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
+                {
+                    if (object1.body.x > object2.body.right)
+                    {
+                        continue;
+                    }
+                    else if (object2.body.x > object1.body.right)
+                    {
+                        break;
+                    }
+                }
+                else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
+                {
+                    if (object1.body.bottom < object2.body.y)
+                    {
+                        continue;
+                    }
+                    else if (object2.body.bottom < object1.body.y)
+                    {
+                        break;
+                    }
+                }
+                else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
+                {
+                    if (object1.body.y > object2.body.bottom)
+                    {
+                        continue;
+                    }
+                    else if (object2.body.y > object1.body.bottom)
+                    {
+                        break;
+                    }
+                }
+                
+                this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+        }
+
+    },
+
+    /**
+    * An internal function. Use Phaser.Physics.Arcade.collide instead.
+    *
+    * @method Phaser.Physics.Arcade#collideGroupVsGroup
+    * @private
+    * @param {Phaser.Group} group1 - The first Group to check.
+    * @param {Phaser.Group} group2 - The second Group to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    */
+    collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        if (group1.length === 0 || group2.length === 0)
+        {
+            return;
+        }
+
+        for (var i = 0; i < group1.children.length; i++)
+        {
+            if (group1.children[i].exists)
+            {
+                if (group1.children[i].physicsType === Phaser.GROUP)
+                {
+                    this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
+                }
+                else
+                {
+                    this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
+                }
+            }
+        }
+
+    },
+
+    /**
+    * The core separation function to separate two physics bodies.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#separate
+    * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate.
+    * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate.
+    * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true.
+    * @param {object} [callbackContext] - The context in which to run the process callback.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    * @return {boolean} Returns true if the bodies collided, otherwise false.
+    */
+    separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
+
+        if (!body1.enable || !body2.enable || !this.intersects(body1, body2))
+        {
+            return false;
+        }
+
+        //  They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
+        if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
+        {
+            return false;
+        }
+
+        //  Do we separate on x or y first?
+
+        var result = false;
+
+        //  If we weren't having to carry around so much legacy baggage with us, we could do this properly. But alas ...
+        if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x))
+        {
+            result = (this.separateX(body1, body2, overlapOnly) || this.separateY(body1, body2, overlapOnly));
+        }
+        else
+        {
+            result = (this.separateY(body1, body2, overlapOnly) || this.separateX(body1, body2, overlapOnly));
+        }
+
+        if (overlapOnly)
+        {
+            //  We already know they intersect from the check above, but by this point we know they've now had their overlapX/Y values populated
+            return true;
+        }
+        else
+        {
+            return result;
+        }
+
+    },
+
+    /**
+    * Check for intersection against two bodies.
+    *
+    * @method Phaser.Physics.Arcade#intersects
+    * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to check.
+    * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to check.
+    * @return {boolean} True if they intersect, otherwise false.
+    */
+    intersects: function (body1, body2) {
+
+        if (body1.right <= body2.position.x)
+        {
+            return false;
+        }
+
+        if (body1.bottom <= body2.position.y)
+        {
+            return false;
+        }
+
+        if (body1.position.x >= body2.right)
+        {
+            return false;
+        }
+
+        if (body1.position.y >= body2.bottom)
+        {
+            return false;
+        }
+
+        return true;
+
+    },
+
+    /**
+    * The core separation function to separate two physics bodies on the x axis.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#separateX
+    * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
+    * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
+    * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
+    * @return {boolean} Returns true if the bodies were separated, otherwise false.
+    */
+    separateX: function (body1, body2, overlapOnly) {
+
+        //  Can't separate two immovable bodies
+        if (body1.immovable && body2.immovable)
+        {
+            return false;
+        }
+
+        var overlap = 0;
+
+        //  Check if the hulls actually overlap
+        if (this.intersects(body1, body2))
+        {
+            var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
+
+            if (body1.deltaX() === 0 && body2.deltaX() === 0)
+            {
+                //  They overlap but neither of them are moving
+                body1.embedded = true;
+                body2.embedded = true;
+            }
+            else if (body1.deltaX() > body2.deltaX())
+            {
+                //  Body1 is moving right and/or Body2 is moving left
+                overlap = body1.right - body2.x;
+
+                if ((overlap > maxOverlap) || body1.checkCollision.right === false || body2.checkCollision.left === false)
+                {
+                    overlap = 0;
+                }
+                else
+                {
+                    body1.touching.none = false;
+                    body1.touching.right = true;
+                    body2.touching.none = false;
+                    body2.touching.left = true;
+                }
+            }
+            else if (body1.deltaX() < body2.deltaX())
+            {
+                //  Body1 is moving left and/or Body2 is moving right
+                overlap = body1.x - body2.width - body2.x;
+
+                if ((-overlap > maxOverlap) || body1.checkCollision.left === false || body2.checkCollision.right === false)
+                {
+                    overlap = 0;
+                }
+                else
+                {
+                    body1.touching.none = false;
+                    body1.touching.left = true;
+                    body2.touching.none = false;
+                    body2.touching.right = true;
+                }
+            }
+
+            //  Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is
+            body1.overlapX = overlap;
+            body2.overlapX = overlap;
+
+            //  Then adjust their positions and velocities accordingly (if there was any overlap)
+            if (overlap !== 0)
+            {
+                if (overlapOnly || body1.customSeparateX || body2.customSeparateX)
+                {
+                    return true;
+                }
+
+                var v1 = body1.velocity.x;
+                var v2 = body2.velocity.x;
+
+                if (!body1.immovable && !body2.immovable)
+                {
+                    overlap *= 0.5;
+
+                    body1.x = body1.x - overlap;
+                    body2.x += overlap;
+
+                    var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
+                    var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
+                    var avg = (nv1 + nv2) * 0.5;
+
+                    nv1 -= avg;
+                    nv2 -= avg;
+
+                    body1.velocity.x = avg + nv1 * body1.bounce.x;
+                    body2.velocity.x = avg + nv2 * body2.bounce.x;
+                }
+                else if (!body1.immovable)
+                {
+                    body1.x = body1.x - overlap;
+                    body1.velocity.x = v2 - v1 * body1.bounce.x;
+
+                    //  This is special case code that handles things like vertically moving platforms you can ride
+                    if (body2.moves)
+                    {
+                        body1.y += (body2.y - body2.prev.y) * body2.friction.y;
+                    }
+                }
+                else if (!body2.immovable)
+                {
+                    body2.x += overlap;
+                    body2.velocity.x = v1 - v2 * body2.bounce.x;
+
+                    //  This is special case code that handles things like vertically moving platforms you can ride
+                    if (body1.moves)
+                    {
+                        body2.y += (body1.y - body1.prev.y) * body1.friction.y;
+                    }
+                }
+
+                return true;
+            }
+        }
+
+        return false;
+
+    },
+
+    /**
+    * The core separation function to separate two physics bodies on the y axis.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#separateY
+    * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
+    * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
+    * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
+    * @return {boolean} Returns true if the bodies were separated, otherwise false.
+    */
+    separateY: function (body1, body2, overlapOnly) {
+
+        //  Can't separate two immovable or non-existing bodies
+        if (body1.immovable && body2.immovable)
+        {
+            return false;
+        }
+
+        var overlap = 0;
+
+        //  Check if the hulls actually overlap
+        if (this.intersects(body1, body2))
+        {
+            var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
+
+            if (body1.deltaY() === 0 && body2.deltaY() === 0)
+            {
+                //  They overlap but neither of them are moving
+                body1.embedded = true;
+                body2.embedded = true;
+            }
+            else if (body1.deltaY() > body2.deltaY())
+            {
+                //  Body1 is moving down and/or Body2 is moving up
+                overlap = body1.bottom - body2.y;
+
+                if ((overlap > maxOverlap) || body1.checkCollision.down === false || body2.checkCollision.up === false)
+                {
+                    overlap = 0;
+                }
+                else
+                {
+                    body1.touching.none = false;
+                    body1.touching.down = true;
+                    body2.touching.none = false;
+                    body2.touching.up = true;
+                }
+            }
+            else if (body1.deltaY() < body2.deltaY())
+            {
+                //  Body1 is moving up and/or Body2 is moving down
+                overlap = body1.y - body2.bottom;
+
+                if ((-overlap > maxOverlap) || body1.checkCollision.up === false || body2.checkCollision.down === false)
+                {
+                    overlap = 0;
+                }
+                else
+                {
+                    body1.touching.none = false;
+                    body1.touching.up = true;
+                    body2.touching.none = false;
+                    body2.touching.down = true;
+                }
+            }
+
+            //  Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is
+            body1.overlapY = overlap;
+            body2.overlapY = overlap;
+
+            //  Then adjust their positions and velocities accordingly (if there was any overlap)
+            if (overlap !== 0)
+            {
+                if (overlapOnly || body1.customSeparateY || body2.customSeparateY)
+                {
+                    return true;
+                }
+
+                var v1 = body1.velocity.y;
+                var v2 = body2.velocity.y;
+
+                if (!body1.immovable && !body2.immovable)
+                {
+                    overlap *= 0.5;
+
+                    body1.y = body1.y - overlap;
+                    body2.y += overlap;
+
+                    var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
+                    var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
+                    var avg = (nv1 + nv2) * 0.5;
+
+                    nv1 -= avg;
+                    nv2 -= avg;
+
+                    body1.velocity.y = avg + nv1 * body1.bounce.y;
+                    body2.velocity.y = avg + nv2 * body2.bounce.y;
+                }
+                else if (!body1.immovable)
+                {
+                    body1.y = body1.y - overlap;
+                    body1.velocity.y = v2 - v1 * body1.bounce.y;
+
+                    //  This is special case code that handles things like horizontal moving platforms you can ride
+                    if (body2.moves)
+                    {
+                        body1.x += (body2.x - body2.prev.x) * body2.friction.x;
+                    }
+                }
+                else if (!body2.immovable)
+                {
+                    body2.y += overlap;
+                    body2.velocity.y = v1 - v2 * body2.bounce.y;
+
+                    //  This is special case code that handles things like horizontal moving platforms you can ride
+                    if (body1.moves)
+                    {
+                        body2.x += (body1.x - body1.prev.x) * body1.friction.x;
+                    }
+                }
+
+                return true;
+            }
+
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates.
+    * Each child will be sent to the given callback for further processing.
+    * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not.
+    *
+    * @method Phaser.Physics.Arcade#getObjectsUnderPointer
+    * @param {Phaser.Pointer} pointer - The Pointer to check.
+    * @param {Phaser.Group} group - The Group to check.
+    * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it.
+    * @param {object} [callbackContext] - The context in which to run the callback.
+    * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates.
+    */
+    getObjectsUnderPointer: function (pointer, group, callback, callbackContext) {
+
+        if (group.length === 0 || !pointer.exists)
+        {
+            return;
+        }
+
+        return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer);
+
+    },
+
+    /**
+    * Given a Group and a location this will check to see which Group children overlap with the coordinates.
+    * Each child will be sent to the given callback for further processing.
+    * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not.
+    *
+    * @method Phaser.Physics.Arcade#getObjectsAtLocation
+    * @param {number} x - The x coordinate to check.
+    * @param {number} y - The y coordinate to check.
+    * @param {Phaser.Group} group - The Group to check.
+    * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location.
+    * @param {object} [callbackContext] - The context in which to run the callback.
+    * @param {object} [callbackArg] - An argument to pass to the callback.
+    * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates.
+    */
+    getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) {
+
+        this.quadTree.clear();
+
+        this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
+
+        this.quadTree.populate(group);
+
+        var rect = new Phaser.Rectangle(x, y, 1, 1);
+        var output = [];
+
+        var items = this.quadTree.retrieve(rect);
+
+        for (var i = 0; i < items.length; i++)
+        {
+            if (items[i].hitTest(x, y))
+            {
+                if (callback)
+                {
+                    callback.call(callbackContext, callbackArg, items[i].sprite);
+                }
+
+                output.push(items[i].sprite);
+            }
+        }
+
+        return output;
+        
+    },
+
+    /**
+    * Move the given display object towards the destination object at a steady velocity.
+    * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds.
+    * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
+    * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
+    * Note: The display object doesn't stop moving once it reaches the destination coordinates.
+    * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
+    *
+    * @method Phaser.Physics.Arcade#moveToObject
+    * @param {any} displayObject - The display object to move.
+    * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
+    * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
+    * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
+    * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
+    */
+    moveToObject: function (displayObject, destination, speed, maxTime) {
+
+        if (speed === undefined) { speed = 60; }
+        if (maxTime === undefined) { maxTime = 0; }
+
+        var angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
+
+        if (maxTime > 0)
+        {
+            //  We know how many pixels we need to move, but how fast?
+            speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
+        }
+
+        displayObject.body.velocity.x = Math.cos(angle) * speed;
+        displayObject.body.velocity.y = Math.sin(angle) * speed;
+
+        return angle;
+
+    },
+
+    /**
+    * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
+    * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+    * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
+    * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
+    * Note: The display object doesn't stop moving once it reaches the destination coordinates.
+    *
+    * @method Phaser.Physics.Arcade#moveToPointer
+    * @param {any} displayObject - The display object to move.
+    * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
+    * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
+    * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
+    * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
+    */
+    moveToPointer: function (displayObject, speed, pointer, maxTime) {
+
+        if (speed === undefined) { speed = 60; }
+        pointer = pointer || this.game.input.activePointer;
+        if (maxTime === undefined) { maxTime = 0; }
+
+        var angle = this.angleToPointer(displayObject, pointer);
+
+        if (maxTime > 0)
+        {
+            //  We know how many pixels we need to move, but how fast?
+            speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
+        }
+
+        displayObject.body.velocity.x = Math.cos(angle) * speed;
+        displayObject.body.velocity.y = Math.sin(angle) * speed;
+
+        return angle;
+
+    },
+
+    /**
+    * Move the given display object towards the x/y coordinates at a steady velocity.
+    * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+    * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
+    * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
+    * Note: The display object doesn't stop moving once it reaches the destination coordinates.
+    * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
+    *
+    * @method Phaser.Physics.Arcade#moveToXY
+    * @param {any} displayObject - The display object to move.
+    * @param {number} x - The x coordinate to move towards.
+    * @param {number} y - The y coordinate to move towards.
+    * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
+    * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
+    * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
+    */
+    moveToXY: function (displayObject, x, y, speed, maxTime) {
+
+        if (speed === undefined) { speed = 60; }
+        if (maxTime === undefined) { maxTime = 0; }
+
+        var angle = Math.atan2(y - displayObject.y, x - displayObject.x);
+
+        if (maxTime > 0)
+        {
+            //  We know how many pixels we need to move, but how fast?
+            speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
+        }
+
+        displayObject.body.velocity.x = Math.cos(angle) * speed;
+        displayObject.body.velocity.y = Math.sin(angle) * speed;
+
+        return angle;
+
+    },
+
+    /**
+    * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
+    * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
+    *
+    * @method Phaser.Physics.Arcade#velocityFromAngle
+    * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
+    * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
+    * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
+    * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
+    */
+    velocityFromAngle: function (angle, speed, point) {
+
+        if (speed === undefined) { speed = 60; }
+        point = point || new Phaser.Point();
+
+        return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed));
+
+    },
+
+    /**
+    * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
+    * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
+    *
+    * @method Phaser.Physics.Arcade#velocityFromRotation
+    * @param {number} rotation - The angle in radians.
+    * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
+    * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
+    * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
+    */
+    velocityFromRotation: function (rotation, speed, point) {
+
+        if (speed === undefined) { speed = 60; }
+        point = point || new Phaser.Point();
+
+        return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
+
+    },
+
+    /**
+    * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object.
+    * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object.
+    *
+    * @method Phaser.Physics.Arcade#accelerationFromRotation
+    * @param {number} rotation - The angle in radians.
+    * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
+    * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
+    * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
+    */
+    accelerationFromRotation: function (rotation, speed, point) {
+
+        if (speed === undefined) { speed = 60; }
+        point = point || new Phaser.Point();
+
+        return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
+
+    },
+
+    /**
+    * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
+    * You must give a maximum speed value, beyond which the display object won't go any faster.
+    * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
+    * Note: The display object doesn't stop moving once it reaches the destination coordinates.
+    *
+    * @method Phaser.Physics.Arcade#accelerateToObject
+    * @param {any} displayObject - The display object to move.
+    * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
+    * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
+    * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
+    * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
+    * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
+    */
+    accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
+
+        if (speed === undefined) { speed = 60; }
+        if (xSpeedMax === undefined) { xSpeedMax = 1000; }
+        if (ySpeedMax === undefined) { ySpeedMax = 1000; }
+
+        var angle = this.angleBetween(displayObject, destination);
+
+        displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
+        displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
+
+        return angle;
+
+    },
+
+    /**
+    * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
+    * You must give a maximum speed value, beyond which the display object won't go any faster.
+    * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
+    * Note: The display object doesn't stop moving once it reaches the destination coordinates.
+    *
+    * @method Phaser.Physics.Arcade#accelerateToPointer
+    * @param {any} displayObject - The display object to move.
+    * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
+    * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
+    * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
+    * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
+    * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
+    */
+    accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
+
+        if (speed === undefined) { speed = 60; }
+        if (pointer === undefined) { pointer = this.game.input.activePointer; }
+        if (xSpeedMax === undefined) { xSpeedMax = 1000; }
+        if (ySpeedMax === undefined) { ySpeedMax = 1000; }
+
+        var angle = this.angleToPointer(displayObject, pointer);
+
+        displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
+        displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
+
+        return angle;
+
+    },
+
+    /**
+    * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.)
+    * You must give a maximum speed value, beyond which the display object won't go any faster.
+    * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
+    * Note: The display object doesn't stop moving once it reaches the destination coordinates.
+    *
+    * @method Phaser.Physics.Arcade#accelerateToXY
+    * @param {any} displayObject - The display object to move.
+    * @param {number} x - The x coordinate to accelerate towards.
+    * @param {number} y - The y coordinate to accelerate towards.
+    * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
+    * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
+    * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
+    * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
+    */
+    accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
+
+        if (speed === undefined) { speed = 60; }
+        if (xSpeedMax === undefined) { xSpeedMax = 1000; }
+        if (ySpeedMax === undefined) { ySpeedMax = 1000; }
+
+        var angle = this.angleToXY(displayObject, x, y);
+
+        displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
+        displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
+
+        return angle;
+
+    },
+
+    /**
+    * Find the distance between two display objects (like Sprites).
+    *
+    * @method Phaser.Physics.Arcade#distanceBetween
+    * @param {any} source - The Display Object to test from.
+    * @param {any} target - The Display Object to test to.
+    * @return {number} The distance between the source and target objects.
+    */
+    distanceBetween: function (source, target) {
+
+        var dx = source.x - target.x;
+        var dy = source.y - target.y;
+
+        return Math.sqrt(dx * dx + dy * dy);
+
+    },
+
+    /**
+    * Find the distance between a display object (like a Sprite) and the given x/y coordinates.
+    * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
+    * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
+    *
+    * @method Phaser.Physics.Arcade#distanceToXY
+    * @param {any} displayObject - The Display Object to test from.
+    * @param {number} x - The x coordinate to move towards.
+    * @param {number} y - The y coordinate to move towards.
+    * @return {number} The distance between the object and the x/y coordinates.
+    */
+    distanceToXY: function (displayObject, x, y) {
+
+        var dx = displayObject.x - x;
+        var dy = displayObject.y - y;
+
+        return Math.sqrt(dx * dx + dy * dy);
+
+    },
+
+    /**
+    * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
+    * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
+    * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
+    * The distance to the Pointer is returned in screen space, not world space.
+    *
+    * @method Phaser.Physics.Arcade#distanceToPointer
+    * @param {any} displayObject - The Display Object to test from.
+    * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
+    * @return {number} The distance between the object and the Pointer.
+    */
+    distanceToPointer: function (displayObject, pointer) {
+
+        pointer = pointer || this.game.input.activePointer;
+
+        var dx = displayObject.x - pointer.worldX;
+        var dy = displayObject.y - pointer.worldY;
+
+        return Math.sqrt(dx * dx + dy * dy);
+
+    },
+
+    /**
+    * Find the angle in radians between two display objects (like Sprites).
+    *
+    * @method Phaser.Physics.Arcade#angleBetween
+    * @param {any} source - The Display Object to test from.
+    * @param {any} target - The Display Object to test to.
+    * @return {number} The angle in radians between the source and target display objects.
+    */
+    angleBetween: function (source, target) {
+
+        var dx = target.x - source.x;
+        var dy = target.y - source.y;
+
+        return Math.atan2(dy, dx);
+
+    },
+
+    /**
+    * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
+    *
+    * @method Phaser.Physics.Arcade#angleToXY
+    * @param {any} displayObject - The Display Object to test from.
+    * @param {number} x - The x coordinate to get the angle to.
+    * @param {number} y - The y coordinate to get the angle to.
+    * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
+    */
+    angleToXY: function (displayObject, x, y) {
+
+        var dx = x - displayObject.x;
+        var dy = y - displayObject.y;
+
+        return Math.atan2(dy, dx);
+
+    },
+
+    /**
+    * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
+    *
+    * @method Phaser.Physics.Arcade#angleToPointer
+    * @param {any} displayObject - The Display Object to test from.
+    * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
+    * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
+    */
+    angleToPointer: function (displayObject, pointer) {
+
+        pointer = pointer || this.game.input.activePointer;
+
+        var dx = pointer.worldX - displayObject.x;
+        var dy = pointer.worldY - displayObject.y;
+
+        return Math.atan2(dy, dx);
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
+* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
+*
+* @class Phaser.Physics.Arcade.Body
+* @constructor
+* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
+*/
+Phaser.Physics.Arcade.Body = function (sprite) {
+
+    /**
+    * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
+    */
+    this.sprite = sprite;
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = sprite.game;
+
+    /**
+    * @property {number} type - The type of physics system this body belongs to.
+    */
+    this.type = Phaser.Physics.ARCADE;
+
+    /**
+    * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run.
+    * @default
+    */
+    this.enable = true;
+
+    /**
+    * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
+    */
+    this.offset = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} position - The position of the physics body.
+    * @readonly
+    */
+    this.position = new Phaser.Point(sprite.x, sprite.y);
+
+    /**
+    * @property {Phaser.Point} prev - The previous position of the physics body.
+    * @readonly
+    */
+    this.prev = new Phaser.Point(this.position.x, this.position.y);
+
+    /**
+    * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
+    * @default
+    */
+    this.allowRotation = true;
+
+    /**
+    * An Arcade Physics Body can have angularVelocity and angularAcceleration. Please understand that the collision Body
+    * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation.
+    * @property {number} rotation
+    */
+    this.rotation = sprite.rotation;
+
+    /**
+    * @property {number} preRotation - The previous rotation of the physics body.
+    * @readonly
+    */
+    this.preRotation = sprite.rotation;
+
+    /**
+    * @property {number} width - The calculated width of the physics body.
+    * @readonly
+    */
+    this.width = sprite.width;
+
+    /**
+    * @property {number} height - The calculated height of the physics body.
+    * @readonly
+    */
+    this.height = sprite.height;
+
+    /**
+    * @property {number} sourceWidth - The un-scaled original size.
+    * @readonly
+    */
+    this.sourceWidth = sprite.width;
+
+    /**
+    * @property {number} sourceHeight - The un-scaled original size.
+    * @readonly
+    */
+    this.sourceHeight = sprite.height;
+
+    if (sprite.texture)
+    {
+        this.sourceWidth = sprite.texture.frame.width;
+        this.sourceHeight = sprite.texture.frame.height;
+    }
+
+    /**
+    * @property {number} halfWidth - The calculated width / 2 of the physics body.
+    * @readonly
+    */
+    this.halfWidth = Math.abs(sprite.width / 2);
+
+    /**
+    * @property {number} halfHeight - The calculated height / 2 of the physics body.
+    * @readonly
+    */
+    this.halfHeight = Math.abs(sprite.height / 2);
+
+    /**
+    * @property {Phaser.Point} center - The center coordinate of the Physics Body.
+    * @readonly
+    */
+    this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight);
+
+    /**
+    * @property {Phaser.Point} velocity - The velocity, or rate of change in speed of the Body. Measured in pixels per second.
+    */
+    this.velocity = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} newVelocity - The new velocity. Calculated during the Body.preUpdate and applied to its position.
+    * @readonly
+    */
+    this.newVelocity = new Phaser.Point(0, 0);
+
+    /**
+    * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax.
+    */
+    this.deltaMax = new Phaser.Point(0, 0);
+
+    /**
+    * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared.
+    */
+    this.acceleration = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} drag - The drag applied to the motion of the Body.
+    */
+    this.drag = new Phaser.Point();
+
+    /**
+    * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local.
+    * @default
+    */
+    this.allowGravity = true;
+
+    /**
+    * @property {Phaser.Point} gravity - A local gravity applied to this Body. If non-zero this over rides any world gravity, unless Body.allowGravity is set to false.
+    */
+    this.gravity = new Phaser.Point(0, 0);
+
+    /**
+    * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
+    */
+    this.bounce = new Phaser.Point();
+
+    /**
+    * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
+    * @default
+    */
+    this.maxVelocity = new Phaser.Point(10000, 10000);
+
+    /**
+    * @property {Phaser.Point} friction - The amount of movement that will occur if another object 'rides' this one.
+    */
+    this.friction = new Phaser.Point(1, 0);
+
+    /**
+    * @property {number} angularVelocity - The angular velocity controls the rotation speed of the Body. It is measured in radians per second.
+    * @default
+    */
+    this.angularVelocity = 0;
+
+    /**
+    * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in radians per second squared.
+    * @default
+    */
+    this.angularAcceleration = 0;
+
+    /**
+    * @property {number} angularDrag - The drag applied during the rotation of the Body.
+    * @default
+    */
+    this.angularDrag = 0;
+
+    /**
+    * @property {number} maxAngular - The maximum angular velocity in radians per second that the Body can reach.
+    * @default
+    */
+    this.maxAngular = 1000;
+
+    /**
+    * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity.
+    * @default
+    */
+    this.mass = 1;
+
+    /**
+    * @property {number} angle - The angle of the Body in radians, as calculated by its angularVelocity.
+    * @readonly
+    */
+    this.angle = 0;
+
+    /**
+    * @property {number} speed - The speed of the Body as calculated by its velocity.
+    * @readonly
+    */
+    this.speed = 0;
+
+    /**
+    * @property {number} facing - A const reference to the direction the Body is traveling or facing.
+    * @default
+    */
+    this.facing = Phaser.NONE;
+
+    /**
+    * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
+    * @default
+    */
+    this.immovable = false;
+
+    /**
+    * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never
+    * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen.
+    * If you want the physics system to move the body around, then set moves to true.
+    * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually.
+    * @default
+    */
+    this.moves = true;
+
+    /**
+    * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
+    * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
+    * @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
+    * @default
+    */
+    this.customSeparateX = false;
+
+    /**
+    * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
+    * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
+    * @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
+    * @default
+    */
+    this.customSeparateY = false;
+
+    /**
+    * When this body collides with another, the amount of overlap is stored here.
+    * @property {number} overlapX - The amount of horizontal overlap during the collision.
+    */
+    this.overlapX = 0;
+
+    /**
+    * When this body collides with another, the amount of overlap is stored here.
+    * @property {number} overlapY - The amount of vertical overlap during the collision.
+    */
+    this.overlapY = 0;
+
+    /**
+    * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true.
+    * @property {boolean} embedded - Body embed value.
+    */
+    this.embedded = false;
+
+    /**
+    * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
+    * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
+    */
+    this.collideWorldBounds = false;
+
+    /**
+    * Set the checkCollision properties to control which directions collision is processed for this Body.
+    * For example checkCollision.up = false means it won't collide when the collision happened while moving up.
+    * @property {object} checkCollision - An object containing allowed collision.
+    */
+    this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
+
+    /**
+    * This object is populated with boolean values when the Body collides with another.
+    * touching.up = true means the collision happened to the top of this Body for example.
+    * @property {object} touching - An object containing touching results.
+    */
+    this.touching = { none: true, up: false, down: false, left: false, right: false };
+
+    /**
+    * This object is populated with previous touching values from the bodies previous collision.
+    * @property {object} wasTouching - An object containing previous touching results.
+    */
+    this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
+
+    /**
+    * This object is populated with boolean values when the Body collides with the World bounds or a Tile.
+    * For example if blocked.up is true then the Body cannot move up.
+    * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
+    */
+    this.blocked = { up: false, down: false, left: false, right: false };
+
+    /**
+    * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step.
+    * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height.
+    * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision.
+    */
+    this.tilePadding = new Phaser.Point();
+
+    /**
+    * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state?
+    */
+    this.dirty = false;
+
+    /**
+    * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree.
+    */
+    this.skipQuadTree = false;
+
+    /**
+    * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly.
+    * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed.
+    * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, 
+    * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless.
+    * @property {boolean} syncBounds
+    * @default
+    */
+    this.syncBounds = false;
+
+    /**
+    * @property {boolean} _reset - Internal cache var.
+    * @private
+    */
+    this._reset = true;
+
+    /**
+    * @property {number} _sx - Internal cache var.
+    * @private
+    */
+    this._sx = sprite.scale.x;
+
+    /**
+    * @property {number} _sy - Internal cache var.
+    * @private
+    */
+    this._sy = sprite.scale.y;
+
+    /**
+    * @property {number} _dx - Internal cache var.
+    * @private
+    */
+    this._dx = 0;
+
+    /**
+    * @property {number} _dy - Internal cache var.
+    * @private
+    */
+    this._dy = 0;
+
+};
+
+Phaser.Physics.Arcade.Body.prototype = {
+
+    /**
+    * Internal method.
+    *
+    * @method Phaser.Physics.Arcade.Body#updateBounds
+    * @protected
+    */
+    updateBounds: function () {
+
+        if (this.syncBounds)
+        {
+            var b = this.sprite.getBounds();
+            b.ceilAll();
+
+            if (b.width !== this.width || b.height !== this.height)
+            {
+                this.width = b.width;
+                this.height = b.height;
+                this._reset = true;
+            }
+        }
+        else
+        {
+            var asx = Math.abs(this.sprite.scale.x);
+            var asy = Math.abs(this.sprite.scale.y);
+
+            if (asx !== this._sx || asy !== this._sy)
+            {
+                this.width = this.sourceWidth * asx;
+                this.height = this.sourceHeight * asy;
+                this._sx = asx;
+                this._sy = asy;
+                this._reset = true;
+            }
+        }
+
+        if (this._reset)
+        {
+            this.halfWidth = Math.floor(this.width / 2);
+            this.halfHeight = Math.floor(this.height / 2);
+            this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
+        }
+
+    },
+
+    /**
+    * Internal method.
+    *
+    * @method Phaser.Physics.Arcade.Body#preUpdate
+    * @protected
+    */
+    preUpdate: function () {
+
+        if (!this.enable || this.game.physics.arcade.isPaused)
+        {
+            return;
+        }
+
+        this.dirty = true;
+
+        //  Store and reset collision flags
+        this.wasTouching.none = this.touching.none;
+        this.wasTouching.up = this.touching.up;
+        this.wasTouching.down = this.touching.down;
+        this.wasTouching.left = this.touching.left;
+        this.wasTouching.right = this.touching.right;
+
+        this.touching.none = true;
+        this.touching.up = false;
+        this.touching.down = false;
+        this.touching.left = false;
+        this.touching.right = false;
+
+        this.blocked.up = false;
+        this.blocked.down = false;
+        this.blocked.left = false;
+        this.blocked.right = false;
+
+        this.embedded = false;
+
+        this.updateBounds();
+
+        this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
+        this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
+        this.rotation = this.sprite.angle;
+
+        this.preRotation = this.rotation;
+
+        if (this._reset || this.sprite.fresh)
+        {
+            this.prev.x = this.position.x;
+            this.prev.y = this.position.y;
+        }
+
+        if (this.moves)
+        {
+            this.game.physics.arcade.updateMotion(this);
+
+            this.newVelocity.set(this.velocity.x * this.game.time.physicsElapsed, this.velocity.y * this.game.time.physicsElapsed);
+
+            this.position.x += this.newVelocity.x;
+            this.position.y += this.newVelocity.y;
+
+            if (this.position.x !== this.prev.x || this.position.y !== this.prev.y)
+            {
+                this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
+                this.angle = Math.atan2(this.velocity.y, this.velocity.x);
+            }
+
+            //  Now the State update will throw collision checks at the Body
+            //  And finally we'll integrate the new position back to the Sprite in postUpdate
+
+            if (this.collideWorldBounds)
+            {
+                this.checkWorldBounds();
+            }
+        }
+
+        this._dx = this.deltaX();
+        this._dy = this.deltaY();
+
+        this._reset = false;
+
+    },
+
+    /**
+    * Internal method.
+    *
+    * @method Phaser.Physics.Arcade.Body#postUpdate
+    * @protected
+    */
+    postUpdate: function () {
+
+        //  Only allow postUpdate to be called once per frame
+        if (!this.enable || !this.dirty)
+        {
+            return;
+        }
+
+        this.dirty = false;
+
+        if (this.deltaX() < 0)
+        {
+            this.facing = Phaser.LEFT;
+        }
+        else if (this.deltaX() > 0)
+        {
+            this.facing = Phaser.RIGHT;
+        }
+
+        if (this.deltaY() < 0)
+        {
+            this.facing = Phaser.UP;
+        }
+        else if (this.deltaY() > 0)
+        {
+            this.facing = Phaser.DOWN;
+        }
+
+        if (this.moves)
+        {
+            this._dx = this.deltaX();
+            this._dy = this.deltaY();
+
+            if (this.deltaMax.x !== 0 && this._dx !== 0)
+            {
+                if (this._dx < 0 && this._dx < -this.deltaMax.x)
+                {
+                    this._dx = -this.deltaMax.x;
+                }
+                else if (this._dx > 0 && this._dx > this.deltaMax.x)
+                {
+                    this._dx = this.deltaMax.x;
+                }
+            }
+
+            if (this.deltaMax.y !== 0 && this._dy !== 0)
+            {
+                if (this._dy < 0 && this._dy < -this.deltaMax.y)
+                {
+                    this._dy = -this.deltaMax.y;
+                }
+                else if (this._dy > 0 && this._dy > this.deltaMax.y)
+                {
+                    this._dy = this.deltaMax.y;
+                }
+            }
+
+            this.sprite.position.x += this._dx;
+            this.sprite.position.y += this._dy;
+            this._reset = true;
+        }
+
+        this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
+
+        if (this.allowRotation)
+        {
+            this.sprite.angle += this.deltaZ();
+        }
+
+        this.prev.x = this.position.x;
+        this.prev.y = this.position.y;
+
+    },
+
+    /**
+    * Removes this bodys reference to its parent sprite, freeing it up for gc.
+    *
+    * @method Phaser.Physics.Arcade.Body#destroy
+    */
+    destroy: function () {
+
+        if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group)
+        {
+            this.sprite.parent.removeFromHash(this.sprite);
+        }
+
+        this.sprite.body = null;
+        this.sprite = null;
+
+    },
+
+    /**
+    * Internal method.
+    *
+    * @method Phaser.Physics.Arcade.Body#checkWorldBounds
+    * @protected
+    */
+    checkWorldBounds: function () {
+
+        var pos = this.position;
+        var bounds = this.game.physics.arcade.bounds;
+        var check = this.game.physics.arcade.checkCollision;
+
+        if (pos.x < bounds.x && check.left)
+        {
+            pos.x = bounds.x;
+            this.velocity.x *= -this.bounce.x;
+            this.blocked.left = true;
+        }
+        else if (this.right > bounds.right && check.right)
+        {
+            pos.x = bounds.right - this.width;
+            this.velocity.x *= -this.bounce.x;
+            this.blocked.right = true;
+        }
+
+        if (pos.y < bounds.y && check.up)
+        {
+            pos.y = bounds.y;
+            this.velocity.y *= -this.bounce.y;
+            this.blocked.up = true;
+        }
+        else if (this.bottom > bounds.bottom && check.down)
+        {
+            pos.y = bounds.bottom - this.height;
+            this.velocity.y *= -this.bounce.y;
+            this.blocked.down = true;
+        }
+
+    },
+
+    /**
+    * You can modify the size of the physics Body to be any dimension you need.
+    * So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which
+    * is the position of the Body relative to the top-left of the Sprite.
+    *
+    * @method Phaser.Physics.Arcade.Body#setSize
+    * @param {number} width - The width of the Body.
+    * @param {number} height - The height of the Body.
+    * @param {number} [offsetX] - The X offset of the Body from the Sprite position.
+    * @param {number} [offsetY] - The Y offset of the Body from the Sprite position.
+    */
+    setSize: function (width, height, offsetX, offsetY) {
+
+        if (offsetX === undefined) { offsetX = this.offset.x; }
+        if (offsetY === undefined) { offsetY = this.offset.y; }
+
+        this.sourceWidth = width;
+        this.sourceHeight = height;
+        this.width = this.sourceWidth * this._sx;
+        this.height = this.sourceHeight * this._sy;
+        this.halfWidth = Math.floor(this.width / 2);
+        this.halfHeight = Math.floor(this.height / 2);
+        this.offset.setTo(offsetX, offsetY);
+
+        this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
+
+    },
+
+    /**
+    * Resets all Body values (velocity, acceleration, rotation, etc)
+    *
+    * @method Phaser.Physics.Arcade.Body#reset
+    * @param {number} x - The new x position of the Body.
+    * @param {number} y - The new y position of the Body.
+    */
+    reset: function (x, y) {
+
+        this.velocity.set(0);
+        this.acceleration.set(0);
+
+        this.speed = 0;
+        this.angularVelocity = 0;
+        this.angularAcceleration = 0;
+
+        this.position.x = (x - (this.sprite.anchor.x * this.width)) + this.offset.x;
+        this.position.y = (y - (this.sprite.anchor.y * this.height)) + this.offset.y;
+
+        this.prev.x = this.position.x;
+        this.prev.y = this.position.y;
+
+        this.rotation = this.sprite.angle;
+        this.preRotation = this.rotation;
+
+        this._sx = this.sprite.scale.x;
+        this._sy = this.sprite.scale.y;
+
+        this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
+
+    },
+
+    /**
+    * Tests if a world point lies within this Body.
+    *
+    * @method Phaser.Physics.Arcade.Body#hitTest
+    * @param {number} x - The world x coordinate to test.
+    * @param {number} y - The world y coordinate to test.
+    * @return {boolean} True if the given coordinates are inside this Body, otherwise false.
+    */
+    hitTest: function (x, y) {
+        return Phaser.Rectangle.contains(this, x, y);
+    },
+
+    /**
+    * Returns true if the bottom of this Body is in contact with either the world bounds or a tile.
+    *
+    * @method Phaser.Physics.Arcade.Body#onFloor
+    * @return {boolean} True if in contact with either the world bounds or a tile.
+    */
+    onFloor: function () {
+        return this.blocked.down;
+    },
+
+    /**
+    * Returns true if either side of this Body is in contact with either the world bounds or a tile.
+    *
+    * @method Phaser.Physics.Arcade.Body#onWall
+    * @return {boolean} True if in contact with either the world bounds or a tile.
+    */
+    onWall: function () {
+        return (this.blocked.left || this.blocked.right);
+    },
+
+    /**
+    * Returns the absolute delta x value.
+    *
+    * @method Phaser.Physics.Arcade.Body#deltaAbsX
+    * @return {number} The absolute delta value.
+    */
+    deltaAbsX: function () {
+        return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
+    },
+
+    /**
+    * Returns the absolute delta y value.
+    *
+    * @method Phaser.Physics.Arcade.Body#deltaAbsY
+    * @return {number} The absolute delta value.
+    */
+    deltaAbsY: function () {
+        return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
+    },
+
+    /**
+    * Returns the delta x value. The difference between Body.x now and in the previous step.
+    *
+    * @method Phaser.Physics.Arcade.Body#deltaX
+    * @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
+    */
+    deltaX: function () {
+        return this.position.x - this.prev.x;
+    },
+
+    /**
+    * Returns the delta y value. The difference between Body.y now and in the previous step.
+    *
+    * @method Phaser.Physics.Arcade.Body#deltaY
+    * @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
+    */
+    deltaY: function () {
+        return this.position.y - this.prev.y;
+    },
+
+    /**
+    * Returns the delta z value. The difference between Body.rotation now and in the previous step.
+    *
+    * @method Phaser.Physics.Arcade.Body#deltaZ
+    * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise.
+    */
+    deltaZ: function () {
+        return this.rotation - this.preRotation;
+    }
+
+};
+
+/**
+* @name Phaser.Physics.Arcade.Body#bottom
+* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
+* @readonly
+*/
+Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
+
+    get: function () {
+        return this.position.y + this.height;
+    }
+
+});
+
+/**
+* @name Phaser.Physics.Arcade.Body#right
+* @property {number} right - The right value of this Body (same as Body.x + Body.width)
+* @readonly
+*/
+Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
+
+    get: function () {
+        return this.position.x + this.width;
+    }
+
+});
+
+/**
+* @name Phaser.Physics.Arcade.Body#x
+* @property {number} x - The x position.
+*/
+Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", {
+
+    get: function () {
+        return this.position.x;
+    },
+
+    set: function (value) {
+
+        this.position.x = value;
+    }
+
+});
+
+/**
+* @name Phaser.Physics.Arcade.Body#y
+* @property {number} y - The y position.
+*/
+Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", {
+
+    get: function () {
+        return this.position.y;
+    },
+
+    set: function (value) {
+
+        this.position.y = value;
+
+    }
+
+});
+
+/**
+* Render Sprite Body.
+*
+* @method Phaser.Physics.Arcade.Body#render
+* @param {object} context - The context to render to.
+* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
+* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string).
+* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
+*/
+Phaser.Physics.Arcade.Body.render = function (context, body, color, filled) {
+
+    if (filled === undefined) { filled = true; }
+
+    color = color || 'rgba(0,255,0,0.4)';
+
+    if (filled)
+    {
+        context.fillStyle = color;
+        context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
+    }
+    else
+    {
+        context.strokeStyle = color;
+        context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
+    }
+
+};
+
+/**
+* Render Sprite Body Physics Data as text.
+*
+* @method Phaser.Physics.Arcade.Body#renderBodyInfo
+* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
+* @param {number} x - X position of the debug info to be rendered.
+* @param {number} y - Y position of the debug info to be rendered.
+* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
+*/
+Phaser.Physics.Arcade.Body.renderBodyInfo = function (debug, body) {
+
+    debug.line('x: ' + body.x.toFixed(2), 'y: ' + body.y.toFixed(2), 'width: ' + body.width, 'height: ' + body.height);
+    debug.line('velocity x: ' + body.velocity.x.toFixed(2), 'y: ' + body.velocity.y.toFixed(2), 'deltaX: ' + body._dx.toFixed(2), 'deltaY: ' + body._dy.toFixed(2));
+    debug.line('acceleration x: ' + body.acceleration.x.toFixed(2), 'y: ' + body.acceleration.y.toFixed(2), 'speed: ' + body.speed.toFixed(2), 'angle: ' + body.angle.toFixed(2));
+    debug.line('gravity x: ' + body.gravity.x, 'y: ' + body.gravity.y, 'bounce x: ' + body.bounce.x.toFixed(2), 'y: ' + body.bounce.y.toFixed(2));
+    debug.line('touching left: ' + body.touching.left, 'right: ' + body.touching.right, 'up: ' + body.touching.up, 'down: ' + body.touching.down);
+    debug.line('blocked left: ' + body.blocked.left, 'right: ' + body.blocked.right, 'up: ' + body.blocked.up, 'down: ' + body.blocked.down);
+
+};
+
+Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+Phaser.Physics.Arcade.TilemapCollision = function () {
+
+};
+
+/**
+* The Arcade Physics tilemap collision methods.
+*
+* @class Phaser.Physics.Arcade.TilemapCollision
+* @constructor
+* @param {Phaser.Game} game - reference to the current game instance.
+*/
+Phaser.Physics.Arcade.TilemapCollision.prototype = {
+
+    /**
+    * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling.
+    */
+    TILE_BIAS: 16,
+
+    /**
+    * An internal function. Use Phaser.Physics.Arcade.collide instead.
+    *
+    * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer
+    * @private
+    * @param {Phaser.Sprite} sprite - The sprite to check.
+    * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    */
+    collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        if (!sprite.body)
+        {
+            return;
+        }
+
+        var mapData = tilemapLayer.getTiles(
+            sprite.body.position.x - sprite.body.tilePadding.x,
+            sprite.body.position.y - sprite.body.tilePadding.y,
+            sprite.body.width + sprite.body.tilePadding.x,
+            sprite.body.height + sprite.body.tilePadding.y,
+            false, false);
+
+        if (mapData.length === 0)
+        {
+            return;
+        }
+
+        for (var i = 0; i < mapData.length; i++)
+        {
+            if (processCallback)
+            {
+                if (processCallback.call(callbackContext, sprite, mapData[i]))
+                {
+                    if (this.separateTile(i, sprite.body, mapData[i], overlapOnly))
+                    {
+                        this._total++;
+
+                        if (collideCallback)
+                        {
+                            collideCallback.call(callbackContext, sprite, mapData[i]);
+                        }
+                    }
+                }
+            }
+            else
+            {
+                if (this.separateTile(i, sprite.body, mapData[i], overlapOnly))
+                {
+                    this._total++;
+
+                    if (collideCallback)
+                    {
+                        collideCallback.call(callbackContext, sprite, mapData[i]);
+                    }
+                }
+            }
+        }
+
+    },
+
+    /**
+    * An internal function. Use Phaser.Physics.Arcade.collide instead.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer
+    * @param {Phaser.Group} group - The Group to check.
+    * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
+    * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
+    * @param {object} callbackContext - The context in which to run the callbacks.
+    * @param {boolean} overlapOnly - Just run an overlap or a full collision.
+    */
+    collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) {
+
+        if (group.length === 0)
+        {
+            return;
+        }
+
+        for (var i = 0; i < group.children.length; i++)
+        {
+            if (group.children[i].exists)
+            {
+                this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly);
+            }
+        }
+
+    },
+
+    /**
+    * The core separation function to separate a physics body and a tile.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#separateTile
+    * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
+    * @param {Phaser.Tile} tile - The tile to collide against.
+    * @return {boolean} Returns true if the body was separated, otherwise false.
+    */
+    separateTile: function (i, body, tile, overlapOnly) {
+
+        if (!body.enable)
+        {
+            return false;
+        }
+
+        //  We re-check for collision in case body was separated in a previous step
+        if (!tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
+        {
+            //  no collision so bail out (separated in a previous step)
+            return false;
+        }
+        else if (overlapOnly)
+        {
+            //  There is an overlap, and we don't need to separate. Bail.
+            return true;
+        }
+
+        //  They overlap. Any custom callbacks?
+
+        //  A local callback always takes priority over a layer level callback
+        if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile))
+        {
+            //  If it returns true then we can carry on, otherwise we should abort.
+            return false;
+        }
+        else if (tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile))
+        {
+            //  If it returns true then we can carry on, otherwise we should abort.
+            return false;
+        }
+
+        //  We don't need to go any further if this tile doesn't actually separate
+        if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom)
+        {
+            //   This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation
+            return false;
+        }
+
+        var ox = 0;
+        var oy = 0;
+        var minX = 0;
+        var minY = 1;
+
+        if (body.deltaAbsX() > body.deltaAbsY())
+        {
+            //  Moving faster horizontally, check X axis first
+            minX = -1;
+        }
+        else if (body.deltaAbsX() < body.deltaAbsY())
+        {
+            //  Moving faster vertically, check Y axis first
+            minY = -1;
+        }
+
+        if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom))
+        {
+            //  We only need do this if both axis have checking faces AND we're moving in both directions
+            minX = Math.min(Math.abs(body.position.x - tile.right), Math.abs(body.right - tile.left));
+            minY = Math.min(Math.abs(body.position.y - tile.bottom), Math.abs(body.bottom - tile.top));
+        }
+
+        if (minX < minY)
+        {
+            if (tile.faceLeft || tile.faceRight)
+            {
+                ox = this.tileCheckX(body, tile);
+
+                //  That's horizontal done, check if we still intersects? If not then we can return now
+                if (ox !== 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
+                {
+                    return true;
+                }
+            }
+
+            if (tile.faceTop || tile.faceBottom)
+            {
+                oy = this.tileCheckY(body, tile);
+            }
+        }
+        else
+        {
+            if (tile.faceTop || tile.faceBottom)
+            {
+                oy = this.tileCheckY(body, tile);
+
+                //  That's vertical done, check if we still intersects? If not then we can return now
+                if (oy !== 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
+                {
+                    return true;
+                }
+            }
+
+            if (tile.faceLeft || tile.faceRight)
+            {
+                ox = this.tileCheckX(body, tile);
+            }
+        }
+
+        return (ox !== 0 || oy !== 0);
+
+    },
+
+    /**
+    * Check the body against the given tile on the X axis.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#tileCheckX
+    * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
+    * @param {Phaser.Tile} tile - The tile to check.
+    * @return {number} The amount of separation that occurred.
+    */
+    tileCheckX: function (body, tile) {
+
+        var ox = 0;
+
+        if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left)
+        {
+            //  Body is moving LEFT
+            if (tile.faceRight && body.x < tile.right)
+            {
+                ox = body.x - tile.right;
+
+                if (ox < -this.TILE_BIAS)
+                {
+                    ox = 0;
+                }
+            }
+        }
+        else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right)
+        {
+            //  Body is moving RIGHT
+            if (tile.faceLeft && body.right > tile.left)
+            {
+                ox = body.right - tile.left;
+
+                if (ox > this.TILE_BIAS)
+                {
+                    ox = 0;
+                }
+            }
+        }
+
+        if (ox !== 0)
+        {
+            if (body.customSeparateX)
+            {
+                body.overlapX = ox;
+            }
+            else
+            {
+                this.processTileSeparationX(body, ox);
+            }
+        }
+
+        return ox;
+
+    },
+
+    /**
+    * Check the body against the given tile on the Y axis.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#tileCheckY
+    * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
+    * @param {Phaser.Tile} tile - The tile to check.
+    * @return {number} The amount of separation that occurred.
+    */
+    tileCheckY: function (body, tile) {
+
+        var oy = 0;
+
+        if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up)
+        {
+            //  Body is moving UP
+            if (tile.faceBottom && body.y < tile.bottom)
+            {
+                oy = body.y - tile.bottom;
+
+                if (oy < -this.TILE_BIAS)
+                {
+                    oy = 0;
+                }
+            }
+        }
+        else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down)
+        {
+            //  Body is moving DOWN
+            if (tile.faceTop && body.bottom > tile.top)
+            {
+                oy = body.bottom - tile.top;
+
+                if (oy > this.TILE_BIAS)
+                {
+                    oy = 0;
+                }
+            }
+        }
+
+        if (oy !== 0)
+        {
+            if (body.customSeparateY)
+            {
+                body.overlapY = oy;
+            }
+            else
+            {
+                this.processTileSeparationY(body, oy);
+            }
+        }
+
+        return oy;
+
+    },
+
+    /**
+    * Internal function to process the separation of a physics body from a tile.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#processTileSeparationX
+    * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
+    * @param {number} x - The x separation amount.
+    */
+    processTileSeparationX: function (body, x) {
+
+        if (x < 0)
+        {
+            body.blocked.left = true;
+        }
+        else if (x > 0)
+        {
+            body.blocked.right = true;
+        }
+
+        body.position.x -= x;
+
+        if (body.bounce.x === 0)
+        {
+            body.velocity.x = 0;
+        }
+        else
+        {
+            body.velocity.x = -body.velocity.x * body.bounce.x;
+        }
+
+    },
+
+    /**
+    * Internal function to process the separation of a physics body from a tile.
+    *
+    * @private
+    * @method Phaser.Physics.Arcade#processTileSeparationY
+    * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
+    * @param {number} y - The y separation amount.
+    */
+    processTileSeparationY: function (body, y) {
+
+        if (y < 0)
+        {
+            body.blocked.up = true;
+        }
+        else if (y > 0)
+        {
+            body.blocked.down = true;
+        }
+
+        body.position.y -= y;
+
+        if (body.bounce.y === 0)
+        {
+            body.velocity.y = 0;
+        }
+        else
+        {
+            body.velocity.y = -body.velocity.y * body.bounce.y;
+        }
+
+    }
+
+};
+
+//  Merge this with the Arcade Physics prototype
+Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype);
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+//  Add an extra properties to p2 that we need
+p2.Body.prototype.parent = null;
+p2.Spring.prototype.parent = null;
+
+/**
+* This is your main access to the P2 Physics World.
+* From here you can create materials, listen for events and add bodies into the physics simulation.
+* 
+* @class Phaser.Physics.P2
+* @constructor
+* @param {Phaser.Game} game - Reference to the current game instance.
+* @param {object} [config] - Physics configuration object passed in from the game constructor.
+*/
+Phaser.Physics.P2 = function (game, config) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    if (config === undefined)
+    {
+        config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() };
+    }
+    else
+    {
+        if (!config.hasOwnProperty('gravity'))
+        {
+            config.gravity = [0, 0];
+        }
+
+        if (!config.hasOwnProperty('broadphase'))
+        {
+            config.broadphase = new p2.SAPBroadphase();
+        }
+    }
+
+    /**
+    * @property {object} config - The p2 World configuration object.
+    * @protected
+    */
+    this.config = config;
+
+    /**
+    * @property {p2.World} world - The p2 World in which the simulation is run.
+    * @protected
+    */
+    this.world = new p2.World(this.config);
+
+    /**
+    * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property.
+    * @default
+    */
+    this.frameRate = 1 / 60;
+
+    /**
+    * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value.
+    * @default
+    */
+    this.useElapsedTime = false;
+
+    /**
+    * @property {boolean} paused - The paused state of the P2 World.
+    * @default
+    */
+    this.paused = false;
+
+    /**
+    * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials.
+    * @protected
+    */
+    this.materials = [];
+
+    /**
+    * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step.
+    */
+    this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity);
+
+    /**
+    * @property {object} walls - An object containing the 4 wall bodies that bound the physics world.
+    */
+    this.walls = { left: null, right: null, top: null, bottom: null };
+
+    /**
+    * This signal is dispatched when a new Body is added to the World.
+    *
+    * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world.
+    * 
+    * @property {Phaser.Signal} onBodyAdded
+    */
+    this.onBodyAdded = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Body is removed to the World.
+    *
+    * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world.
+    * 
+    * @property {Phaser.Signal} onBodyRemoved
+    */
+    this.onBodyRemoved = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Spring is added to the World.
+    *
+    * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world.
+    * 
+    * @property {Phaser.Signal} onSpringAdded
+    */
+    this.onSpringAdded = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Spring is removed from the World.
+    *
+    * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world.
+    * 
+    * @property {Phaser.Signal} onSpringRemoved
+    */
+    this.onSpringRemoved = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Constraint is added to the World.
+    *
+    * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world.
+    * 
+    * @property {Phaser.Signal} onConstraintAdded
+    */
+    this.onConstraintAdded = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Constraint is removed from the World.
+    *
+    * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world.
+    * 
+    * @property {Phaser.Signal} onConstraintRemoved
+    */
+    this.onConstraintRemoved = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Contact Material is added to the World.
+    *
+    * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world.
+    * 
+    * @property {Phaser.Signal} onContactMaterialAdded
+    */
+    this.onContactMaterialAdded = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched when a Contact Material is removed from the World.
+    *
+    * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world.
+    * 
+    * @property {Phaser.Signal} onContactMaterialRemoved
+    */
+    this.onContactMaterialRemoved = new Phaser.Signal();
+
+    /**
+    * @property {function} postBroadphaseCallback - A postBroadphase callback.
+    */
+    this.postBroadphaseCallback = null;
+
+    /**
+    * @property {object} callbackContext - The context under which the callbacks are fired.
+    */
+    this.callbackContext = null;
+
+    /**
+    * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done.
+    * 
+    * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`.
+    * 
+    * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this
+    * in your own code to avoid processing potentially null physics bodies.
+    * 
+    * @property {Phaser.Signal} onBeginContact
+    */
+    this.onBeginContact = new Phaser.Signal();
+
+    /**
+    * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done.
+    * 
+    * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`.
+    * 
+    * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this
+    * in your own code to avoid processing potentially null physics bodies.
+    * 
+    * @property {Phaser.Signal} onEndContact
+    */
+    this.onEndContact = new Phaser.Signal();
+
+    //  Pixel to meter function overrides
+    if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi'))
+    {
+        this.mpx = config.mpx;
+        this.mpxi = config.mpxi;
+        this.pxm = config.pxm;
+        this.pxmi = config.pxmi;
+    }
+
+    //  Hook into the World events
+    this.world.on("beginContact", this.beginContactHandler, this);
+    this.world.on("endContact", this.endContactHandler, this);
+
+    /**
+    * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World.
+    */
+    this.collisionGroups = [];
+
+    /**
+    * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group.
+    */
+    this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
+
+    /**
+    * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group.
+    */
+    this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
+
+    /**
+    * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group.
+    */
+    this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
+
+    /**
+    * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with.
+    */
+    this.boundsCollidesWith = [];
+
+    /**
+    * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step.
+    * @private
+    */
+    this._toRemove = [];
+
+    /**
+    * @property {number} _collisionGroupID - Internal var.
+    * @private
+    */
+    this._collisionGroupID = 2;
+
+    /**
+    * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings.
+    * @private
+    */
+    this._boundsLeft = true;
+
+    /**
+    * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings.
+    * @private
+    */
+    this._boundsRight = true;
+
+    /**
+    * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings.
+    * @private
+    */
+    this._boundsTop = true;
+
+    /**
+    * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings.
+    * @private
+    */
+    this._boundsBottom = true;
+
+    /**
+    * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings.
+    * @private
+    */
+    this._boundsOwnGroup = false;
+
+    //  By default we want everything colliding with everything
+    this.setBoundsToWorld(true, true, true, true, false);
+
+};
+
+Phaser.Physics.P2.prototype = {
+
+    /**
+    * This will add a P2 Physics body into the removal list for the next step.
+    *
+    * @method Phaser.Physics.P2#removeBodyNextStep
+    * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step.
+    */
+    removeBodyNextStep: function (body) {
+
+        this._toRemove.push(body);
+
+    },
+
+    /**
+    * Called at the start of the core update loop. Purges flagged bodies from the world.
+    *
+    * @method Phaser.Physics.P2#preUpdate
+    */
+    preUpdate: function () {
+
+        var i = this._toRemove.length;
+
+        while (i--)
+        {
+            this.removeBody(this._toRemove[i]);
+        }
+
+        this._toRemove.length = 0;
+
+    },
+
+    /**
+    * This will create a P2 Physics body on the given game object or array of game objects.
+    * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
+    * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered.
+    *
+    * @method Phaser.Physics.P2#enable
+    * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
+    * @param {boolean} [debug=false] - Create a debug object to go with this body?
+    * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
+    */
+    enable: function (object, debug, children) {
+
+        if (debug === undefined) { debug = false; }
+        if (children === undefined) { children = true; }
+
+        var i = 1;
+
+        if (Array.isArray(object))
+        {
+            i = object.length;
+
+            while (i--)
+            {
+                if (object[i] instanceof Phaser.Group)
+                {
+                    //  If it's a Group then we do it on the children regardless
+                    this.enable(object[i].children, debug, children);
+                }
+                else
+                {
+                    this.enableBody(object[i], debug);
+
+                    if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
+                    {
+                        this.enable(object[i], debug, true);
+                    }
+                }
+            }
+        }
+        else
+        {
+            if (object instanceof Phaser.Group)
+            {
+                //  If it's a Group then we do it on the children regardless
+                this.enable(object.children, debug, children);
+            }
+            else
+            {
+                this.enableBody(object, debug);
+
+                if (children && object.hasOwnProperty('children') && object.children.length > 0)
+                {
+                    this.enable(object.children, debug, true);
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Creates a P2 Physics body on the given game object.
+    * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
+    *
+    * @method Phaser.Physics.P2#enableBody
+    * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
+    * @param {boolean} debug - Create a debug object to go with this body?
+    */
+    enableBody: function (object, debug) {
+
+        if (object.hasOwnProperty('body') && object.body === null)
+        {
+            object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1);
+            object.body.debug = debug;
+			if (typeof object.anchor !== 'undefined') {
+				object.anchor.set(0.5);
+			}
+        }
+
+    },
+
+    /**
+    * Impact event handling is disabled by default. Enable it before any impact events will be dispatched.
+    * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks.
+    *
+    * @method Phaser.Physics.P2#setImpactEvents
+    * @param {boolean} state - Set to true to enable impact events, or false to disable.
+    */
+    setImpactEvents: function (state) {
+
+        if (state)
+        {
+            this.world.on("impact", this.impactHandler, this);
+        }
+        else
+        {
+            this.world.off("impact", this.impactHandler, this);
+        }
+
+    },
+
+    /**
+    * Sets a callback to be fired after the Broadphase has collected collision pairs in the world.
+    * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do.
+    * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step.
+    * Returning `true` from the callback will ensure they are checked in the narrowphase.
+    *
+    * @method Phaser.Physics.P2#setPostBroadphaseCallback
+    * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback.
+    * @param {object} context - The context under which the callback will be fired.
+    */
+    setPostBroadphaseCallback: function (callback, context) {
+
+        this.postBroadphaseCallback = callback;
+        this.callbackContext = context;
+
+        if (callback !== null)
+        {
+            this.world.on("postBroadphase", this.postBroadphaseHandler, this);
+        }
+        else
+        {
+            this.world.off("postBroadphase", this.postBroadphaseHandler, this);
+        }
+
+    },
+
+    /**
+    * Internal handler for the postBroadphase event.
+    *
+    * @method Phaser.Physics.P2#postBroadphaseHandler
+    * @private
+    * @param {object} event - The event data.
+    */
+    postBroadphaseHandler: function (event) {
+
+        if (!this.postBroadphaseCallback || event.pairs.length === 0)
+        {
+            return;
+        }
+
+        for (var i = event.pairs.length - 2; i >= 0; i -= 2)
+        {
+            if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent))
+            {
+                event.pairs.splice(i, 2);
+            }
+        }
+
+    },
+
+    /**
+    * Handles a p2 impact event.
+    *
+    * @method Phaser.Physics.P2#impactHandler
+    * @private
+    * @param {object} event - The event data.
+    */
+    impactHandler: function (event) {
+
+        if (event.bodyA.parent && event.bodyB.parent)
+        {
+            //  Body vs. Body callbacks
+            var a = event.bodyA.parent;
+            var b = event.bodyB.parent;
+
+            if (a._bodyCallbacks[event.bodyB.id])
+            {
+                a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB);
+            }
+
+            if (b._bodyCallbacks[event.bodyA.id])
+            {
+                b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA);
+            }
+
+            //  Body vs. Group callbacks
+            if (a._groupCallbacks[event.shapeB.collisionGroup])
+            {
+                a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB);
+            }
+
+            if (b._groupCallbacks[event.shapeA.collisionGroup])
+            {
+                b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA);
+            }
+        }
+
+    },
+
+    /**
+    * Handles a p2 begin contact event.
+    *
+    * @method Phaser.Physics.P2#beginContactHandler
+    * @param {object} event - The event data.
+    */
+    beginContactHandler: function (event) {
+
+        if (event.bodyA && event.bodyB)
+        {
+            this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations);
+
+            if (event.bodyA.parent)
+            {
+                event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB, event.contactEquations);
+            }
+
+            if (event.bodyB.parent)
+            {
+                event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations);
+            }
+        }
+
+    },
+
+    /**
+    * Handles a p2 end contact event.
+    *
+    * @method Phaser.Physics.P2#endContactHandler
+    * @param {object} event - The event data.
+    */
+    endContactHandler: function (event) {
+
+        if (event.bodyA && event.bodyB)
+        {
+            this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB);
+
+            if (event.bodyA.parent)
+            {
+                event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB);
+            }
+
+            if (event.bodyB.parent)
+            {
+                event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA);
+            }
+        }
+
+    },
+
+    /**
+    * Sets the bounds of the Physics world to match the Game.World dimensions.
+    * You can optionally set which 'walls' to create: left, right, top or bottom.
+    *
+    * @method Phaser.Physics#setBoundsToWorld
+    * @param {boolean} [left=true] - If true will create the left bounds wall.
+    * @param {boolean} [right=true] - If true will create the right bounds wall.
+    * @param {boolean} [top=true] - If true will create the top bounds wall.
+    * @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
+    * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
+    */
+    setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) {
+
+        this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup);
+
+    },
+
+    /**
+    * Sets the given material against the 4 bounds of this World.
+    *
+    * @method Phaser.Physics#setWorldMaterial
+    * @param {Phaser.Physics.P2.Material} material - The material to set.
+    * @param {boolean} [left=true] - If true will set the material on the left bounds wall.
+    * @param {boolean} [right=true] - If true will set the material on the right bounds wall.
+    * @param {boolean} [top=true] - If true will set the material on the top bounds wall.
+    * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall.
+    */
+    setWorldMaterial: function (material, left, right, top, bottom) {
+
+        if (left === undefined) { left = true; }
+        if (right === undefined) { right = true; }
+        if (top === undefined) { top = true; }
+        if (bottom === undefined) { bottom = true; }
+
+        if (left && this.walls.left)
+        {
+            this.walls.left.shapes[0].material = material;
+        }
+
+        if (right && this.walls.right)
+        {
+            this.walls.right.shapes[0].material = material;
+        }
+
+        if (top && this.walls.top)
+        {
+            this.walls.top.shapes[0].material = material;
+        }
+
+        if (bottom && this.walls.bottom)
+        {
+            this.walls.bottom.shapes[0].material = material;
+        }
+
+    },
+
+    /**
+    * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face.
+    * If you start to use your own collision groups then your objects will no longer collide with the bounds.
+    * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group.
+    *
+    * @method Phaser.Physics.P2#updateBoundsCollisionGroup
+    * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
+    */
+    updateBoundsCollisionGroup: function (setCollisionGroup) {
+
+        var mask = this.everythingCollisionGroup.mask;
+
+        if (setCollisionGroup === undefined) { mask = this.boundsCollisionGroup.mask; }
+
+        if (this.walls.left)
+        {
+            this.walls.left.shapes[0].collisionGroup = mask;
+        }
+
+        if (this.walls.right)
+        {
+            this.walls.right.shapes[0].collisionGroup = mask;
+        }
+
+        if (this.walls.top)
+        {
+            this.walls.top.shapes[0].collisionGroup = mask;
+        }
+
+        if (this.walls.bottom)
+        {
+            this.walls.bottom.shapes[0].collisionGroup = mask;
+        }
+
+    },
+
+    /**
+    * Sets the bounds of the Physics world to match the given world pixel dimensions.
+    * You can optionally set which 'walls' to create: left, right, top or bottom.
+    * If none of the walls are given it will default to use the walls settings it had previously.
+    * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size
+    * the newly created bounds will also not have the left and right walls.
+    * Explicitly state them in the parameters to override this.
+    *
+    * @method Phaser.Physics.P2#setBounds
+    * @param {number} x - The x coordinate of the top-left corner of the bounds.
+    * @param {number} y - The y coordinate of the top-left corner of the bounds.
+    * @param {number} width - The width of the bounds.
+    * @param {number} height - The height of the bounds.
+    * @param {boolean} [left=true] - If true will create the left bounds wall.
+    * @param {boolean} [right=true] - If true will create the right bounds wall.
+    * @param {boolean} [top=true] - If true will create the top bounds wall.
+    * @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
+    * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
+    */
+    setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) {
+
+        if (left === undefined) { left = this._boundsLeft; }
+        if (right === undefined) { right = this._boundsRight; }
+        if (top === undefined) { top = this._boundsTop; }
+        if (bottom === undefined) { bottom = this._boundsBottom; }
+        if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; }
+
+        if (this.walls.left)
+        {
+            this.world.removeBody(this.walls.left);
+        }
+
+        if (this.walls.right)
+        {
+            this.world.removeBody(this.walls.right);
+        }
+
+        if (this.walls.top)
+        {
+            this.world.removeBody(this.walls.top);
+        }
+
+        if (this.walls.bottom)
+        {
+            this.world.removeBody(this.walls.bottom);
+        }
+
+        if (left)
+        {
+            this.walls.left = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: 1.5707963267948966 });
+            this.walls.left.addShape(new p2.Plane());
+
+            if (setCollisionGroup)
+            {
+                this.walls.left.shapes[0].collisionGroup = this.boundsCollisionGroup.mask;
+            }
+
+            this.world.addBody(this.walls.left);
+        }
+
+        if (right)
+        {
+            this.walls.right = new p2.Body({ mass: 0, position: [ this.pxmi(x + width), this.pxmi(y) ], angle: -1.5707963267948966 });
+            this.walls.right.addShape(new p2.Plane());
+
+            if (setCollisionGroup)
+            {
+                this.walls.right.shapes[0].collisionGroup = this.boundsCollisionGroup.mask;
+            }
+
+            this.world.addBody(this.walls.right);
+        }
+
+        if (top)
+        {
+            this.walls.top = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: -3.141592653589793 });
+            this.walls.top.addShape(new p2.Plane());
+
+            if (setCollisionGroup)
+            {
+                this.walls.top.shapes[0].collisionGroup = this.boundsCollisionGroup.mask;
+            }
+
+            this.world.addBody(this.walls.top);
+        }
+
+        if (bottom)
+        {
+            this.walls.bottom = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y + height) ] });
+            this.walls.bottom.addShape(new p2.Plane());
+
+            if (setCollisionGroup)
+            {
+                this.walls.bottom.shapes[0].collisionGroup = this.boundsCollisionGroup.mask;
+            }
+
+            this.world.addBody(this.walls.bottom);
+        }
+
+        //  Remember the bounds settings in case they change later on via World.setBounds
+        this._boundsLeft = left;
+        this._boundsRight = right;
+        this._boundsTop = top;
+        this._boundsBottom = bottom;
+        this._boundsOwnGroup = setCollisionGroup;
+
+    },
+
+    /**
+    * Pauses the P2 World independent of the game pause state.
+    *
+    * @method Phaser.Physics.P2#pause
+    */
+    pause: function() {
+
+        this.paused = true;
+
+    },
+    
+    /**
+    * Resumes a paused P2 World.
+    *
+    * @method Phaser.Physics.P2#resume
+    */
+    resume: function() {
+
+        this.paused = false;
+
+    },
+
+    /**
+    * Internal P2 update loop.
+    *
+    * @method Phaser.Physics.P2#update
+    */
+    update: function () {
+
+        // Do nothing if the physics engine was paused before
+        if (this.paused)
+        {
+            return;
+        }
+
+        if (this.useElapsedTime)
+        {
+            this.world.step(this.game.time.physicsElapsed);
+        }
+        else
+        {
+            this.world.step(this.frameRate);
+        }
+
+    },
+
+    /**
+    * Called by Phaser.Physics when a State swap occurs.
+    * Starts the begin and end Contact listeners again.
+    *
+    * @method Phaser.Physics.P2#reset
+    */
+    reset: function () {
+
+        this.world.on("beginContact", this.beginContactHandler, this);
+        this.world.on("endContact", this.endContactHandler, this);
+
+        this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
+        this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
+        this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
+
+        this._collisionGroupID = 2;
+
+        this.setBoundsToWorld(true, true, true, true, false);
+
+    },
+
+    /**
+    * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask.
+    * 
+    * The P2 world is also cleared:
+    * 
+    * * Removes all solver equations
+    * * Removes all constraints
+    * * Removes all bodies
+    * * Removes all springs
+    * * Removes all contact materials
+    * 
+    * This is called automatically when you switch state.
+    *
+    * @method Phaser.Physics.P2#clear
+    */
+    clear: function () {
+
+        this.world.time = 0;
+        this.world.fixedStepTime = 0;
+
+        // Remove all solver equations
+        if (this.world.solver && this.world.solver.equations.length)
+        {
+            this.world.solver.removeAllEquations();
+        }
+
+        // Remove all constraints
+        var cs = this.world.constraints;
+
+        for (var i = cs.length - 1; i >= 0; i--)
+        {
+            this.world.removeConstraint(cs[i]);
+        }
+
+        // Remove all bodies
+        var bodies = this.world.bodies;
+
+        for (var i = bodies.length - 1; i >= 0; i--)
+        {
+            this.world.removeBody(bodies[i]);
+        }
+
+        // Remove all springs
+        var springs = this.world.springs;
+
+        for (var i = springs.length - 1; i >= 0; i--)
+        {
+            this.world.removeSpring(springs[i]);
+        }
+
+        // Remove all contact materials
+        var cms = this.world.contactMaterials;
+
+        for (var i = cms.length - 1; i >= 0; i--)
+        {
+            this.world.removeContactMaterial(cms[i]);
+        }
+
+        this.world.off("beginContact", this.beginContactHandler, this);
+        this.world.off("endContact", this.endContactHandler, this);
+
+        this.postBroadphaseCallback = null;
+        this.callbackContext = null;
+        this.impactCallback = null;
+
+        this.collisionGroups = [];
+        this._toRemove = [];
+        this.boundsCollidesWith = [];
+
+    },
+
+    /**
+    * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change.
+    *
+    * @method Phaser.Physics.P2#destroy
+    */
+    destroy: function () {
+
+        this.clear();
+
+        this.game = null;
+
+    },
+
+    /**
+    * Add a body to the world.
+    *
+    * @method Phaser.Physics.P2#addBody
+    * @param {Phaser.Physics.P2.Body} body - The Body to add to the World.
+    * @return {boolean} True if the Body was added successfully, otherwise false.
+    */
+    addBody: function (body) {
+
+        if (body.data.world)
+        {
+            return false;
+        }
+        else
+        {
+            this.world.addBody(body.data);
+
+            this.onBodyAdded.dispatch(body);
+
+            return true;
+        }
+
+    },
+
+    /**
+    * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with.
+    *
+    * @method Phaser.Physics.P2#removeBody
+    * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World.
+    * @return {Phaser.Physics.P2.Body} The Body that was removed.
+    */
+    removeBody: function (body) {
+
+        if (body.data.world == this.world)
+        {
+            this.world.removeBody(body.data);
+
+            this.onBodyRemoved.dispatch(body);
+        }
+
+        return body;
+
+    },
+
+    /**
+    * Adds a Spring to the world.
+    *
+    * @method Phaser.Physics.P2#addSpring
+    * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World.
+    * @return {Phaser.Physics.P2.Spring} The Spring that was added.
+    */
+    addSpring: function (spring) {
+
+        if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring)
+        {
+            this.world.addSpring(spring.data);
+        }
+        else
+        {
+            this.world.addSpring(spring);
+        }
+
+        this.onSpringAdded.dispatch(spring);
+
+        return spring;
+
+    },
+
+    /**
+    * Removes a Spring from the world.
+    *
+    * @method Phaser.Physics.P2#removeSpring
+    * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World.
+    * @return {Phaser.Physics.P2.Spring} The Spring that was removed.
+    */
+    removeSpring: function (spring) {
+
+        if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring)
+        {
+            this.world.removeSpring(spring.data);
+        }
+        else
+        {
+            this.world.removeSpring(spring);
+        }
+
+        this.onSpringRemoved.dispatch(spring);
+
+        return spring;
+
+    },
+
+    /**
+    * Creates a constraint that tries to keep the distance between two bodies constant.
+    *
+    * @method Phaser.Physics.P2#createDistanceConstraint
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {number} distance - The distance to keep between the bodies.
+    * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
+    * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
+    * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
+    * @return {Phaser.Physics.P2.DistanceConstraint} The constraint
+    */
+    createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Constraint, invalid body objects given');
+        }
+        else
+        {
+            return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce));
+        }
+
+    },
+
+    /**
+    * Creates a constraint that tries to keep the distance between two bodies constant.
+    *
+    * @method Phaser.Physics.P2#createGearConstraint
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {number} [angle=0] - The relative angle
+    * @param {number} [ratio=1] - The gear ratio.
+    * @return {Phaser.Physics.P2.GearConstraint} The constraint
+    */
+    createGearConstraint: function (bodyA, bodyB, angle, ratio) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Constraint, invalid body objects given');
+        }
+        else
+        {
+            return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio));
+        }
+
+    },
+
+    /**
+    * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
+    * The pivot points are given in world (pixel) coordinates.
+    *
+    * @method Phaser.Physics.P2#createRevoluteConstraint
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+    * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
+    * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
+    * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint
+    */
+    createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Constraint, invalid body objects given');
+        }
+        else
+        {
+            return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot));
+        }
+
+    },
+
+    /**
+    * Locks the relative position between two bodies.
+    *
+    * @method Phaser.Physics.P2#createLockConstraint
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+    * @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
+    * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
+    * @return {Phaser.Physics.P2.LockConstraint} The constraint
+    */
+    createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Constraint, invalid body objects given');
+        }
+        else
+        {
+            return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce));
+        }
+
+    },
+
+    /**
+    * Constraint that only allows bodies to move along a line, relative to each other.
+    * See http://www.iforce2d.net/b2dtut/joints-prismatic
+    *
+    * @method Phaser.Physics.P2#createPrismaticConstraint
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
+    * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+    * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+    * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+    * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
+    * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint
+    */
+    createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Constraint, invalid body objects given');
+        }
+        else
+        {
+            return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce));
+        }
+
+    },
+
+    /**
+    * Adds a Constraint to the world.
+    *
+    * @method Phaser.Physics.P2#addConstraint
+    * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World.
+    * @return {Phaser.Physics.P2.Constraint} The Constraint that was added.
+    */
+    addConstraint: function (constraint) {
+
+        this.world.addConstraint(constraint);
+
+        this.onConstraintAdded.dispatch(constraint);
+
+        return constraint;
+
+    },
+
+    /**
+    * Removes a Constraint from the world.
+    *
+    * @method Phaser.Physics.P2#removeConstraint
+    * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World.
+    * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed.
+    */
+    removeConstraint: function (constraint) {
+
+        this.world.removeConstraint(constraint);
+
+        this.onConstraintRemoved.dispatch(constraint);
+
+        return constraint;
+
+    },
+
+    /**
+    * Adds a Contact Material to the world.
+    *
+    * @method Phaser.Physics.P2#addContactMaterial
+    * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World.
+    * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added.
+    */
+    addContactMaterial: function (material) {
+
+        this.world.addContactMaterial(material);
+
+        this.onContactMaterialAdded.dispatch(material);
+
+        return material;
+
+    },
+
+    /**
+    * Removes a Contact Material from the world.
+    *
+    * @method Phaser.Physics.P2#removeContactMaterial
+    * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World.
+    * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed.
+    */
+    removeContactMaterial: function (material) {
+
+        this.world.removeContactMaterial(material);
+
+        this.onContactMaterialRemoved.dispatch(material);
+
+        return material;
+
+    },
+
+    /**
+    * Gets a Contact Material based on the two given Materials.
+    *
+    * @method Phaser.Physics.P2#getContactMaterial
+    * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for.
+    * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for.
+    * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given.
+    */
+    getContactMaterial: function (materialA, materialB) {
+
+        return this.world.getContactMaterial(materialA, materialB);
+
+    },
+
+    /**
+    * Sets the given Material against all Shapes owned by all the Bodies in the given array.
+    *
+    * @method Phaser.Physics.P2#setMaterial
+    * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies.
+    * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on.
+    */
+    setMaterial: function (material, bodies) {
+
+        var i = bodies.length;
+
+        while (i--)
+        {
+            bodies[i].setMaterial(material);
+        }
+
+    },
+
+    /**
+    * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial().
+    * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials.
+    * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials.
+    *
+    * @method Phaser.Physics.P2#createMaterial
+    * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging.
+    * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes.
+    * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials.
+    */
+    createMaterial: function (name, body) {
+
+        name = name || '';
+
+        var material = new Phaser.Physics.P2.Material(name);
+
+        this.materials.push(material);
+
+        if (typeof body !== 'undefined')
+        {
+            body.setMaterial(material);
+        }
+
+        return material;
+
+    },
+
+    /**
+    * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly.
+    *
+    * @method Phaser.Physics.P2#createContactMaterial
+    * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first.
+    * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first.
+    * @param {object} [options] - Material options object.
+    * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created.
+    */
+    createContactMaterial: function (materialA, materialB, options) {
+
+        if (materialA === undefined) { materialA = this.createMaterial(); }
+        if (materialB === undefined) { materialB = this.createMaterial(); }
+
+        var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options);
+
+        return this.addContactMaterial(contact);
+
+    },
+
+    /**
+    * Populates and returns an array with references to of all current Bodies in the world.
+    *
+    * @method Phaser.Physics.P2#getBodies
+    * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world.
+    */
+    getBodies: function () {
+
+        var output = [];
+        var i = this.world.bodies.length;
+
+        while (i--)
+        {
+            output.push(this.world.bodies[i].parent);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Checks the given object to see if it has a p2.Body and if so returns it.
+    *
+    * @method Phaser.Physics.P2#getBody
+    * @param {object} object - The object to check for a p2.Body on.
+    * @return {p2.Body} The p2.Body, or null if not found.
+    */
+    getBody: function (object) {
+
+        if (object instanceof p2.Body)
+        {
+            //  Native p2 body
+            return object;
+        }
+        else if (object instanceof Phaser.Physics.P2.Body)
+        {
+            //  Phaser P2 Body
+            return object.data;
+        }
+        else if (object['body'] && object['body'].type === Phaser.Physics.P2JS)
+        {
+            //  Sprite, TileSprite, etc
+            return object.body.data;
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Populates and returns an array of all current Springs in the world.
+    *
+    * @method Phaser.Physics.P2#getSprings
+    * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world.
+    */
+    getSprings: function () {
+
+        var output = [];
+        var i = this.world.springs.length;
+
+        while (i--)
+        {
+            output.push(this.world.springs[i].parent);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Populates and returns an array of all current Constraints in the world.
+    * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain
+    * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type.
+    *
+    * @method Phaser.Physics.P2#getConstraints
+    * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world.
+    */
+    getConstraints: function () {
+
+        var output = [];
+        var i = this.world.constraints.length;
+
+        while (i--)
+        {
+            output.push(this.world.constraints[i]);
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to
+    * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property.
+    *
+    * @method Phaser.Physics.P2#hitTest
+    * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates.
+    * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies)
+    * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
+    * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array.
+    * @return {Array} Array of bodies that overlap the point.
+    */
+    hitTest: function (worldPoint, bodies, precision, filterStatic) {
+
+        if (bodies === undefined) { bodies = this.world.bodies; }
+        if (precision === undefined) { precision = 5; }
+        if (filterStatic === undefined) { filterStatic = false; }
+
+        var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ];
+
+        var query = [];
+        var i = bodies.length;
+
+        while (i--)
+        {
+            if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.type === p2.Body.STATIC))
+            {
+                query.push(bodies[i].data);
+            }
+            else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC))
+            {
+                query.push(bodies[i]);
+            }
+            else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC))
+            {
+                query.push(bodies[i].body.data);
+            }
+        }
+
+        return this.world.hitTest(physicsPosition, query, precision);
+
+    },
+
+    /**
+    * Converts the current world into a JSON object.
+    *
+    * @method Phaser.Physics.P2#toJSON
+    * @return {object} A JSON representation of the world.
+    */
+    toJSON: function () {
+
+        return this.world.toJSON();
+
+    },
+
+    /**
+    * Creates a new Collision Group and optionally applies it to the given object.
+    * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups.
+    *
+    * @method Phaser.Physics.P2#createCollisionGroup
+    * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
+    */
+    createCollisionGroup: function (object) {
+
+        var bitmask = Math.pow(2, this._collisionGroupID);
+
+        if (this.walls.left)
+        {
+            this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask;
+        }
+
+        if (this.walls.right)
+        {
+            this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask;
+        }
+
+        if (this.walls.top)
+        {
+            this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask;
+        }
+
+        if (this.walls.bottom)
+        {
+            this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask;
+        }
+
+        this._collisionGroupID++;
+
+        var group = new Phaser.Physics.P2.CollisionGroup(bitmask);
+
+        this.collisionGroups.push(group);
+
+        if (object)
+        {
+            this.setCollisionGroup(object, group);
+        }
+
+        return group;
+
+    },
+
+    /**
+    * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
+    * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them.
+    *
+    * @method Phaser.Physics.P2y#setCollisionGroup
+    * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
+    * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
+    */
+    setCollisionGroup: function (object, group) {
+
+        if (object instanceof Phaser.Group)
+        {
+            for (var i = 0; i < object.total; i++)
+            {
+                if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS)
+                {
+                    object.children[i].body.setCollisionGroup(group);
+                }
+            }
+        }
+        else
+        {
+            object.body.setCollisionGroup(group);
+        }
+
+    },
+
+    /**
+    * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
+    *
+    * @method Phaser.Physics.P2#createSpring
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {number} [restLength=1] - Rest length of the spring. A number > 0.
+    * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
+    * @param {number} [damping=1] - Damping of the spring. A number >= 0.
+    * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
+    * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
+    * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
+    * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
+    * @return {Phaser.Physics.P2.Spring} The spring
+    */
+    createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Spring, invalid body objects given');
+        }
+        else
+        {
+            return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB));
+        }
+
+    },
+
+    /**
+    * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
+    *
+    * @method Phaser.Physics.P2#createRotationalSpring
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
+    * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
+    * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
+    * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
+    * @param {number} [damping=1] - Damping of the spring. A number >= 0.
+    * @return {Phaser.Physics.P2.RotationalSpring} The spring
+    */
+    createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) {
+
+        bodyA = this.getBody(bodyA);
+        bodyB = this.getBody(bodyB);
+
+        if (!bodyA || !bodyB)
+        {
+            console.warn('Cannot create Rotational Spring, invalid body objects given');
+        }
+        else
+        {
+            return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping));
+        }
+
+    },
+
+    /**
+    * Creates a new Body and adds it to the World.
+    *
+    * @method Phaser.Physics.P2#createBody
+    * @param {number} x - The x coordinate of Body.
+    * @param {number} y - The y coordinate of Body.
+    * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
+    * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
+    * @param {object} options - An object containing the build options:
+    * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
+    * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
+    * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
+    * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
+    *                                       Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
+    *                                       or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
+    * @return {Phaser.Physics.P2.Body} The body
+    */
+    createBody: function (x, y, mass, addToWorld, options, data) {
+
+        if (addToWorld === undefined) { addToWorld = false; }
+
+        var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
+
+        if (data)
+        {
+            var result = body.addPolygon(options, data);
+
+            if (!result)
+            {
+                return false;
+            }
+        }
+
+        if (addToWorld)
+        {
+            this.world.addBody(body.data);
+        }
+
+        return body;
+
+    },
+
+    /**
+    * Creates a new Particle and adds it to the World.
+    *
+    * @method Phaser.Physics.P2#createParticle
+    * @param {number} x - The x coordinate of Body.
+    * @param {number} y - The y coordinate of Body.
+    * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
+    * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
+    * @param {object} options - An object containing the build options:
+    * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
+    * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
+    * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
+    * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
+    *                                       Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
+    *                                       or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
+    */
+    createParticle: function (x, y, mass, addToWorld, options, data) {
+
+        if (addToWorld === undefined) { addToWorld = false; }
+
+        var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
+
+        if (data)
+        {
+            var result = body.addPolygon(options, data);
+
+            if (!result)
+            {
+                return false;
+            }
+        }
+
+        if (addToWorld)
+        {
+            this.world.addBody(body.data);
+        }
+
+        return body;
+
+    },
+
+    /**
+    * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world.
+    * Note that the polylines must be created in such a way that they can withstand polygon decomposition.
+    *
+    * @method Phaser.Physics.P2#convertCollisionObjects
+    * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
+    * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world.
+    * @return {array} An array of the Phaser.Physics.Body objects that have been created.
+    */
+    convertCollisionObjects: function (map, layer, addToWorld) {
+
+        if (addToWorld === undefined) { addToWorld = true; }
+
+        var output = [];
+
+        for (var i = 0, len = map.collision[layer].length; i < len; i++)
+        {
+            // name: json.layers[i].objects[v].name,
+            // x: json.layers[i].objects[v].x,
+            // y: json.layers[i].objects[v].y,
+            // width: json.layers[i].objects[v].width,
+            // height: json.layers[i].objects[v].height,
+            // visible: json.layers[i].objects[v].visible,
+            // properties: json.layers[i].objects[v].properties,
+            // polyline: json.layers[i].objects[v].polyline
+
+            var object = map.collision[layer][i];
+
+            var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline);
+
+            if (body)
+            {
+                output.push(body);
+            }
+        }
+
+        return output;
+
+    },
+
+    /**
+    * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`.
+    *
+    * @method Phaser.Physics.P2#clearTilemapLayerBodies
+    * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
+    */
+    clearTilemapLayerBodies: function (map, layer) {
+
+        layer = map.getLayer(layer);
+
+        var i = map.layers[layer].bodies.length;
+
+        while (i--)
+        {
+            map.layers[layer].bodies[i].destroy();
+        }
+
+        map.layers[layer].bodies.length = 0;
+
+    },
+
+    /**
+    * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies.
+    * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc.
+    * Every time you call this method it will destroy any previously created bodies and remove them from the world.
+    * Therefore understand it's a very expensive operation and not to be done in a core game update loop.
+    *
+    * @method Phaser.Physics.P2#convertTilemap
+    * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
+    * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so.
+    * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses.
+    * @return {array} An array of the Phaser.Physics.P2.Body objects that were created.
+    */
+    convertTilemap: function (map, layer, addToWorld, optimize) {
+
+        layer = map.getLayer(layer);
+
+        if (addToWorld === undefined) { addToWorld = true; }
+        if (optimize === undefined) { optimize = true; }
+
+        //  If the bodies array is already populated we need to nuke it
+        this.clearTilemapLayerBodies(map, layer);
+
+        var width = 0;
+        var sx = 0;
+        var sy = 0;
+
+        for (var y = 0, h = map.layers[layer].height; y < h; y++)
+        {
+            width = 0;
+
+            for (var x = 0, w = map.layers[layer].width; x < w; x++)
+            {
+                var tile = map.layers[layer].data[y][x];
+
+                if (tile && tile.index > -1 && tile.collides)
+                {
+                    if (optimize)
+                    {
+                        var right = map.getTileRight(layer, x, y);
+
+                        if (width === 0)
+                        {
+                            sx = tile.x * tile.width;
+                            sy = tile.y * tile.height;
+                            width = tile.width;
+                        }
+
+                        if (right && right.collides)
+                        {
+                            width += tile.width;
+                        }
+                        else
+                        {
+                            var body = this.createBody(sx, sy, 0, false);
+
+                            body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0);
+
+                            if (addToWorld)
+                            {
+                                this.addBody(body);
+                            }
+
+                            map.layers[layer].bodies.push(body);
+
+                            width = 0;
+                        }
+                    }
+                    else
+                    {
+                        var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false);
+
+                        body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0);
+
+                        if (addToWorld)
+                        {
+                            this.addBody(body);
+                        }
+
+                        map.layers[layer].bodies.push(body);
+                    }
+                }
+            }
+        }
+
+        return map.layers[layer].bodies;
+
+    },
+
+    /**
+    * Convert p2 physics value (meters) to pixel scale.
+    * By default Phaser uses a scale of 20px per meter.
+    * If you need to modify this you can over-ride these functions via the Physics Configuration object.
+    *
+    * @method Phaser.Physics.P2#mpx
+    * @param {number} v - The value to convert.
+    * @return {number} The scaled value.
+    */
+    mpx: function (v) {
+
+        return v *= 20;
+
+    },
+
+    /**
+    * Convert pixel value to p2 physics scale (meters).
+    * By default Phaser uses a scale of 20px per meter.
+    * If you need to modify this you can over-ride these functions via the Physics Configuration object.
+    *
+    * @method Phaser.Physics.P2#pxm
+    * @param {number} v - The value to convert.
+    * @return {number} The scaled value.
+    */
+    pxm: function (v) {
+
+        return v * 0.05;
+
+    },
+
+    /**
+    * Convert p2 physics value (meters) to pixel scale and inverses it.
+    * By default Phaser uses a scale of 20px per meter.
+    * If you need to modify this you can over-ride these functions via the Physics Configuration object.
+    *
+    * @method Phaser.Physics.P2#mpxi
+    * @param {number} v - The value to convert.
+    * @return {number} The scaled value.
+    */
+    mpxi: function (v) {
+
+        return v *= -20;
+
+    },
+
+    /**
+    * Convert pixel value to p2 physics scale (meters) and inverses it.
+    * By default Phaser uses a scale of 20px per meter.
+    * If you need to modify this you can over-ride these functions via the Physics Configuration object.
+    *
+    * @method Phaser.Physics.P2#pxmi
+    * @param {number} v - The value to convert.
+    * @return {number} The scaled value.
+    */
+    pxmi: function (v) {
+
+        return v * -0.05;
+
+    }
+
+};
+
+/**
+* @name Phaser.Physics.P2#friction
+* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "friction", {
+
+    get: function () {
+
+        return this.world.defaultContactMaterial.friction;
+
+    },
+
+    set: function (value) {
+
+        this.world.defaultContactMaterial.friction = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#restitution
+* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", {
+
+    get: function () {
+
+        return this.world.defaultContactMaterial.restitution;
+
+    },
+
+    set: function (value) {
+
+        this.world.defaultContactMaterial.restitution = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#contactMaterial
+* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", {
+
+    get: function () {
+
+        return this.world.defaultContactMaterial;
+
+    },
+
+    set: function (value) {
+
+        this.world.defaultContactMaterial = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#applySpringForces
+* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", {
+
+    get: function () {
+
+        return this.world.applySpringForces;
+
+    },
+
+    set: function (value) {
+
+        this.world.applySpringForces = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#applyDamping
+* @property {boolean} applyDamping - Enable to automatically apply body damping each step.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", {
+
+    get: function () {
+
+        return this.world.applyDamping;
+
+    },
+
+    set: function (value) {
+
+        this.world.applyDamping = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#applyGravity
+* @property {boolean} applyGravity - Enable to automatically apply gravity each step.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", {
+
+    get: function () {
+
+        return this.world.applyGravity;
+
+    },
+
+    set: function (value) {
+
+        this.world.applyGravity = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#solveConstraints
+* @property {boolean} solveConstraints - Enable/disable constraint solving in each step.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", {
+
+    get: function () {
+
+        return this.world.solveConstraints;
+
+    },
+
+    set: function (value) {
+
+        this.world.solveConstraints = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#time
+* @property {boolean} time - The World time.
+* @readonly
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "time", {
+
+    get: function () {
+
+        return this.world.time;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#emitImpactEvent
+* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", {
+
+    get: function () {
+
+        return this.world.emitImpactEvent;
+
+    },
+
+    set: function (value) {
+
+        this.world.emitImpactEvent = value;
+
+    }
+
+});
+
+/**
+* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING.
+* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep.
+* @name Phaser.Physics.P2#sleepMode
+* @property {number} sleepMode
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", {
+
+    get: function () {
+
+        return this.world.sleepMode;
+
+    },
+
+    set: function (value) {
+
+        this.world.sleepMode = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2#total
+* @property {number} total - The total number of bodies in the world.
+* @readonly
+*/
+Object.defineProperty(Phaser.Physics.P2.prototype, "total", {
+
+    get: function () {
+
+        return this.world.bodies.length;
+
+    }
+
+});
+
+/* jshint noarg: false */
+
+/**
+* @author       Georgios Kaleadis https://github.com/georgiee
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Allow to access a list of created fixture (coming from Body#addPhaserPolygon)
+* which itself parse the input from PhysicsEditor with the custom phaser exporter.
+* You can access fixtures of a Body by a group index or even by providing a fixture Key.
+
+* You can set the fixture key and also the group index for a fixture in PhysicsEditor.
+* This gives you the power to create a complex body built of many fixtures and modify them
+* during runtime (to remove parts, set masks, categories & sensor properties)
+*
+* @class Phaser.Physics.P2.FixtureList
+* @constructor
+* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon)
+*/
+Phaser.Physics.P2.FixtureList = function (list) {
+
+    if (!Array.isArray(list))
+    {
+        list = [list];
+    }
+
+    this.rawList = list;
+    this.init();
+    this.parse(this.rawList);
+
+};
+
+Phaser.Physics.P2.FixtureList.prototype = {
+  
+    /**
+    * @method Phaser.Physics.P2.FixtureList#init
+    */
+    init: function () {
+
+        /**
+        * @property {object} namedFixtures - Collect all fixtures with a key
+        * @private
+        */
+        this.namedFixtures = {};
+
+        /**
+        * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group
+        * @private
+        */
+        this.groupedFixtures = [];
+
+        /**
+        * @property {Array} allFixtures - This is a list of everything in this collection
+        * @private
+        */
+        this.allFixtures = [];
+
+    },
+
+    /**
+    * @method Phaser.Physics.P2.FixtureList#setCategory
+    * @param {number} bit - The bit to set as the collision group.
+    * @param {string} fixtureKey - Only apply to the fixture with the given key.
+    */
+    setCategory: function (bit, fixtureKey) {
+
+        var setter = function(fixture) {
+            fixture.collisionGroup = bit;
+        };
+
+        this.getFixtures(fixtureKey).forEach(setter);
+
+    },
+  
+    /**
+    * @method Phaser.Physics.P2.FixtureList#setMask
+    * @param {number} bit - The bit to set as the collision mask
+    * @param {string} fixtureKey - Only apply to the fixture with the given key
+    */
+    setMask: function (bit, fixtureKey) {
+
+        var setter = function(fixture) {
+            fixture.collisionMask = bit;
+        };
+
+        this.getFixtures(fixtureKey).forEach(setter);
+
+    },
+  
+    /**
+    * @method Phaser.Physics.P2.FixtureList#setSensor
+    * @param {boolean} value - sensor true or false
+    * @param {string} fixtureKey - Only apply to the fixture with the given key
+    */
+    setSensor: function (value, fixtureKey) {
+
+        var setter = function(fixture) {
+            fixture.sensor = value;
+        };
+
+        this.getFixtures(fixtureKey).forEach(setter);
+
+    },
+
+    /**
+    * @method Phaser.Physics.P2.FixtureList#setMaterial
+    * @param {Object} material - The contact material for a fixture
+    * @param {string} fixtureKey - Only apply to the fixture with the given key
+    */
+    setMaterial: function (material, fixtureKey) {
+
+        var setter = function(fixture) {
+            fixture.material = material;
+        };
+
+        this.getFixtures(fixtureKey).forEach(setter);
+
+    },
+
+    /**
+    * Accessor to get either a list of specified fixtures by key or the whole fixture list
+    * 
+    * @method Phaser.Physics.P2.FixtureList#getFixtures
+    * @param {array} keys - A list of fixture keys
+    */
+    getFixtures: function (keys) {
+
+        var fixtures = [];
+
+        if (keys)
+        {
+            if (!(keys instanceof Array))
+            {
+                keys = [keys];
+            }
+
+            var self = this;
+            keys.forEach(function(key) {
+                if (self.namedFixtures[key])
+                {
+                    fixtures.push(self.namedFixtures[key]);
+                }
+            });
+
+            return this.flatten(fixtures);
+
+        }
+        else
+        {
+            return this.allFixtures;
+        }
+
+    },
+
+    /**
+    * Accessor to get either a single fixture by its key.
+    * 
+    * @method Phaser.Physics.P2.FixtureList#getFixtureByKey
+    * @param {string} key - The key of the fixture.
+    */
+    getFixtureByKey: function (key) {
+
+        return this.namedFixtures[key];
+
+    },
+
+    /**
+    * Accessor to get a group of fixtures by its group index.
+    * 
+    * @method Phaser.Physics.P2.FixtureList#getGroup
+    * @param {number} groupID - The group index.
+    */
+    getGroup: function (groupID) {
+
+        return this.groupedFixtures[groupID];
+
+    },
+  
+    /**
+    * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon
+    * 
+    * @method Phaser.Physics.P2.FixtureList#parse
+    */
+    parse: function () {
+
+        var key, value, _ref, _results;
+        _ref = this.rawList;
+        _results = [];
+
+        for (key in _ref)
+        {
+            value = _ref[key];
+
+            if (!isNaN(key - 0))
+            {
+                this.groupedFixtures[key] = this.groupedFixtures[key] || [];
+                this.groupedFixtures[key] = this.groupedFixtures[key].concat(value);
+            }
+            else
+            {
+                this.namedFixtures[key] = this.flatten(value);
+            }
+
+            _results.push(this.allFixtures = this.flatten(this.groupedFixtures));
+        }
+
+    },
+
+    /**
+    * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons.
+    * 
+    * @method Phaser.Physics.P2.FixtureList#flatten
+    * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow.
+    */
+    flatten: function (array) {
+
+        var result, self;
+        result = [];
+        self = arguments.callee;
+        
+        array.forEach(function(item) {
+            return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item]));
+        });
+
+        return result;
+
+    }
+
+};
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays.
+*
+* @class Phaser.Physics.P2.PointProxy
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {any} destination - The object to bind to.
+*/
+Phaser.Physics.P2.PointProxy = function (world, destination) {
+
+    this.world = world;
+	this.destination = destination;
+
+};
+
+Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy;
+
+/**
+* @name Phaser.Physics.P2.PointProxy#x
+* @property {number} x - The x property of this PointProxy get and set in pixels.
+*/
+Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", {
+
+    get: function () {
+
+        return this.world.mpx(this.destination[0]);
+
+    },
+
+    set: function (value) {
+
+        this.destination[0] = this.world.pxm(value);
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.PointProxy#y
+* @property {number} y - The y property of this PointProxy get and set in pixels.
+*/
+Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", {
+
+    get: function () {
+
+        return this.world.mpx(this.destination[1]);
+
+    },
+
+    set: function (value) {
+
+        this.destination[1] = this.world.pxm(value);
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.PointProxy#mx
+* @property {number} mx - The x property of this PointProxy get and set in meters.
+*/
+Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", {
+
+    get: function () {
+
+        return this.destination[0];
+
+    },
+
+    set: function (value) {
+
+        this.destination[0] = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.PointProxy#my
+* @property {number} my - The x property of this PointProxy get and set in meters.
+*/
+Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", {
+
+    get: function () {
+
+        return this.destination[1];
+
+    },
+
+    set: function (value) {
+
+        this.destination[1] = value;
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set.
+*
+* @class Phaser.Physics.P2.InversePointProxy
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {any} destination - The object to bind to.
+*/
+Phaser.Physics.P2.InversePointProxy = function (world, destination) {
+
+    this.world = world;
+	this.destination = destination;
+
+};
+
+Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy;
+
+/**
+* @name Phaser.Physics.P2.InversePointProxy#x
+* @property {number} x - The x property of this InversePointProxy get and set in pixels.
+*/
+Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", {
+
+    get: function () {
+
+        return this.world.mpxi(this.destination[0]);
+
+    },
+
+    set: function (value) {
+
+        this.destination[0] = this.world.pxmi(value);
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.InversePointProxy#y
+* @property {number} y - The y property of this InversePointProxy get and set in pixels.
+*/
+Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", {
+
+    get: function () {
+
+        return this.world.mpxi(this.destination[1]);
+
+    },
+
+    set: function (value) {
+
+        this.destination[1] = this.world.pxmi(value);
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.InversePointProxy#mx
+* @property {number} mx - The x property of this InversePointProxy get and set in meters.
+*/
+Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", {
+
+    get: function () {
+
+        return this.destination[0];
+
+    },
+
+    set: function (value) {
+
+        this.destination[0] = -value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.InversePointProxy#my
+* @property {number} my - The y property of this InversePointProxy get and set in meters.
+*/
+Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", {
+
+    get: function () {
+
+        return this.destination[1];
+
+    },
+
+    set: function (value) {
+
+        this.destination[1] = -value;
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated.
+* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene.
+* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene.
+* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body.
+* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127.
+* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered.
+*
+* @class Phaser.Physics.P2.Body
+* @constructor
+* @param {Phaser.Game} game - Game reference to the currently running game.
+* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to.
+* @param {number} [x=0] - The x coordinate of this Body.
+* @param {number} [y=0] - The y coordinate of this Body.
+* @param {number} [mass=1] - The default mass of this Body (0 = static).
+*/
+Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) {
+
+    sprite = sprite || null;
+    x = x || 0;
+    y = y || 0;
+    if (mass === undefined) { mass = 1; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to the P2 World.
+    */
+    this.world = game.physics.p2;
+
+    /**
+    * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
+    */
+    this.sprite = sprite;
+
+    /**
+    * @property {number} type - The type of physics system this body belongs to.
+    */
+    this.type = Phaser.Physics.P2JS;
+
+    /**
+    * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
+    */
+    this.offset = new Phaser.Point();
+
+    /**
+    * @property {p2.Body} data - The p2 Body data.
+    * @protected
+    */
+    this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass });
+
+    this.data.parent = this;
+
+    /**
+    * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down.
+    */
+    this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity);
+
+    /**
+    * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body.
+    */
+    this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force);
+
+    /**
+    * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented.
+    */
+    this.gravity = new Phaser.Point();
+
+    /**
+    * Dispatched when a first contact is created between shapes in two bodies. 
+    * This event is fired during the step, so collision has already taken place.
+    * 
+    * The event will be sent 5 arguments in this order:
+    * 
+    * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world.
+    * The p2.Body this Body is in contact with.
+    * The Shape from this body that caused the contact.
+    * The Shape from the contact body.
+    * The Contact Equation data array.
+    * 
+    * @property {Phaser.Signal} onBeginContact
+    */
+    this.onBeginContact = new Phaser.Signal();
+
+    /**
+    * Dispatched when contact ends between shapes in two bodies.
+    * This event is fired during the step, so collision has already taken place.
+    * 
+    * The event will be sent 4 arguments in this order:
+    * 
+    * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world.
+    * The p2.Body this Body has ended contact with.
+    * The Shape from this body that caused the original contact.
+    * The Shape from the contact body.
+    * 
+    * @property {Phaser.Signal} onEndContact
+    */
+    this.onEndContact = new Phaser.Signal();
+
+    /**
+    * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with.
+    */
+    this.collidesWith = [];
+
+    /**
+    * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate.
+    */
+    this.removeNextStep = false;
+
+    /**
+    * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body.
+    */
+    this.debugBody = null;
+
+    /**
+    * @property {boolean} dirty - Internally used by Sprite.x/y
+    */
+    this.dirty = false;
+
+    /**
+    * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not.
+    * @private
+    */
+    this._collideWorldBounds = true;
+
+    /**
+    * @property {object} _bodyCallbacks - Array of Body callbacks.
+    * @private
+    */
+    this._bodyCallbacks = {};
+
+    /**
+    * @property {object} _bodyCallbackContext - Array of Body callback contexts.
+    * @private
+    */
+    this._bodyCallbackContext = {};
+
+    /**
+    * @property {object} _groupCallbacks - Array of Group callbacks.
+    * @private
+    */
+    this._groupCallbacks = {};
+
+    /**
+    * @property {object} _bodyCallbackContext - Array of Grouo callback contexts.
+    * @private
+    */
+    this._groupCallbackContext = {};
+
+    /**
+    * @property {boolean} _reset - Internal var.
+    * @private
+    */
+    this._reset = false;
+
+    //  Set-up the default shape
+    if (sprite)
+    {
+        this.setRectangleFromSprite(sprite);
+
+        if (sprite.exists)
+        {
+            this.game.physics.p2.addBody(this);
+        }
+    }
+
+};
+
+Phaser.Physics.P2.Body.prototype = {
+
+    /**
+    * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values.
+    * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
+    * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening.
+    * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate.
+    *
+    * @method Phaser.Physics.P2.Body#createBodyCallback
+    * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for.
+    * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
+    * @param {object} callbackContext - The context under which the callback will fire.
+    */
+    createBodyCallback: function (object, callback, callbackContext) {
+
+        var id = -1;
+
+        if (object['id'])
+        {
+            id = object.id;
+        }
+        else if (object['body'])
+        {
+            id = object.body.id;
+        }
+
+        if (id > -1)
+        {
+            if (callback === null)
+            {
+                delete (this._bodyCallbacks[id]);
+                delete (this._bodyCallbackContext[id]);
+            }
+            else
+            {
+                this._bodyCallbacks[id] = callback;
+                this._bodyCallbackContext[id] = callbackContext;
+            }
+        }
+
+    },
+
+    /**
+    * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values.
+    * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
+    * This callback will only fire if this Body has been assigned a collision group.
+    * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening.
+    * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate.
+    *
+    * @method Phaser.Physics.P2.Body#createGroupCallback
+    * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for.
+    * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
+    * @param {object} callbackContext - The context under which the callback will fire.
+    */
+    createGroupCallback: function (group, callback, callbackContext) {
+
+        if (callback === null)
+        {
+            delete (this._groupCallbacks[group.mask]);
+            delete (this._groupCallbackContext[group.mask]);
+        }
+        else
+        {
+            this._groupCallbacks[group.mask] = callback;
+            this._groupCallbackContext[group.mask] = callbackContext;
+        }
+
+    },
+
+    /**
+    * Gets the collision bitmask from the groups this body collides with.
+    *
+    * @method Phaser.Physics.P2.Body#getCollisionMask
+    * @return {number} The bitmask.
+    */
+    getCollisionMask: function () {
+
+        var mask = 0;
+
+        if (this._collideWorldBounds)
+        {
+            mask = this.game.physics.p2.boundsCollisionGroup.mask;
+        }
+
+        for (var i = 0; i < this.collidesWith.length; i++)
+        {
+            mask = mask | this.collidesWith[i].mask;
+        }
+
+        return mask;
+
+    },
+
+    /**
+    * Updates the collisionMask.
+    *
+    * @method Phaser.Physics.P2.Body#updateCollisionMask
+    * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
+    */
+    updateCollisionMask: function (shape) {
+
+        var mask = this.getCollisionMask();
+
+        if (shape === undefined)
+        {
+            for (var i = this.data.shapes.length - 1; i >= 0; i--)
+            {
+                this.data.shapes[i].collisionMask = mask;
+            }
+        }
+        else
+        {
+            shape.collisionMask = mask;
+        }
+
+    },
+
+    /**
+    * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
+    * This also resets the collisionMask.
+    *
+    * @method Phaser.Physics.P2.Body#setCollisionGroup
+    * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
+    * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
+    */
+    setCollisionGroup: function (group, shape) {
+
+        var mask = this.getCollisionMask();
+
+        if (shape === undefined)
+        {
+            for (var i = this.data.shapes.length - 1; i >= 0; i--)
+            {
+                this.data.shapes[i].collisionGroup = group.mask;
+                this.data.shapes[i].collisionMask = mask;
+            }
+        }
+        else
+        {
+            shape.collisionGroup = group.mask;
+            shape.collisionMask = mask;
+        }
+
+    },
+
+    /**
+    * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask.
+    *
+    * @method Phaser.Physics.P2.Body#clearCollision
+    * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s?
+    * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s?
+    * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body.
+    */
+    clearCollision: function (clearGroup, clearMask, shape) {
+
+        if (clearGroup === undefined) { clearGroup = true; }
+        if (clearMask === undefined) { clearMask = true; }
+
+        if (shape === undefined)
+        {
+            for (var i = this.data.shapes.length - 1; i >= 0; i--)
+            {
+                if (clearGroup)
+                {
+                    this.data.shapes[i].collisionGroup = null;
+                }
+
+                if (clearMask)
+                {
+                    this.data.shapes[i].collisionMask = null;
+                }
+            }
+        }
+        else
+        {
+            if (clearGroup)
+            {
+                shape.collisionGroup = null;
+            }
+
+            if (clearMask)
+            {
+                shape.collisionMask = null;
+            }
+        }
+
+        if (clearGroup)
+        {
+            this.collidesWith.length = 0;
+        }
+
+    },
+
+    /**
+    * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks.
+    *
+    * @method Phaser.Physics.P2.Body#collides
+    * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with.
+    * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group.
+    * @param {object} [callbackContext] - The context under which the callback will be called.
+    * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body.
+    */
+    collides: function (group, callback, callbackContext, shape) {
+
+        if (Array.isArray(group))
+        {
+            for (var i = 0; i < group.length; i++)
+            {
+                if (this.collidesWith.indexOf(group[i]) === -1)
+                {
+                    this.collidesWith.push(group[i]);
+
+                    if (callback)
+                    {
+                        this.createGroupCallback(group[i], callback, callbackContext);
+                    }
+                }
+            }
+        }
+        else
+        {
+            if (this.collidesWith.indexOf(group) === -1)
+            {
+                this.collidesWith.push(group);
+
+                if (callback)
+                {
+                    this.createGroupCallback(group, callback, callbackContext);
+                }
+            }
+        }
+
+        var mask = this.getCollisionMask();
+
+        if (shape === undefined)
+        {
+            for (var i = this.data.shapes.length - 1; i >= 0; i--)
+            {
+                this.data.shapes[i].collisionMask = mask;
+            }
+        }
+        else
+        {
+            shape.collisionMask = mask;
+        }
+
+    },
+
+    /**
+    * Moves the shape offsets so their center of mass becomes the body center of mass.
+    *
+    * @method Phaser.Physics.P2.Body#adjustCenterOfMass
+    */
+    adjustCenterOfMass: function () {
+
+        this.data.adjustCenterOfMass();
+        this.shapeChanged();
+
+    },
+
+    /**
+    * Gets the velocity of a point in the body.
+    *
+    * @method Phaser.Physics.P2.Body#getVelocityAtPoint
+    * @param {Array} result - A vector to store the result in.
+    * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from.
+    * @return {Array} The result vector.
+    */
+    getVelocityAtPoint: function (result, relativePoint) {
+
+        return this.data.getVelocityAtPoint(result, relativePoint);
+
+    },
+
+    /**
+    * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details.
+    *
+    * @method Phaser.Physics.P2.Body#applyDamping
+    * @param {number} dt - Current time step.
+    */
+    applyDamping: function (dt) {
+
+        this.data.applyDamping(dt);
+
+    },
+
+    /**
+    * Apply impulse to a point relative to the body.
+    * This could for example be a point on the Body surface. An impulse is a force added to a body during a short 
+    * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
+    *
+    * @method Phaser.Physics.P2.Body#applyImpulse
+    * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space.
+    * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.
+    * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.
+    */
+    applyImpulse: function (impulse, worldX, worldY) {
+
+        this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]);
+
+    },
+
+    /**
+    * Apply impulse to a point local to the body.
+    * This could for example be a point on the Body surface. An impulse is a force added to a body during a short 
+    * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
+    *
+    * @method Phaser.Physics.P2.Body#applyImpulseLocal
+    * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space.
+    * @param {number} localX - A local point on the body.
+    * @param {number} localY - A local point on the body.
+    */
+    applyImpulseLocal: function (force, localX, localY) {
+
+        this.data.applyImpulseLocal(force, [this.world.pxmi(localX), this.world.pxmi(localY)]);
+
+    },
+
+    /**
+    * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce.
+    *
+    * @method Phaser.Physics.P2.Body#applyForce
+    * @param {Float32Array|Array} force - The force vector to add.
+    * @param {number} worldX - The world x point to apply the force on.
+    * @param {number} worldY - The world y point to apply the force on.
+    */
+    applyForce: function (force, worldX, worldY) {
+
+        this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]);
+
+    },
+
+    /**
+    * Sets the force on the body to zero.
+    *
+    * @method Phaser.Physics.P2.Body#setZeroForce
+    */
+    setZeroForce: function () {
+
+        this.data.setZeroForce();
+
+    },
+
+    /**
+    * If this Body is dynamic then this will zero its angular velocity.
+    *
+    * @method Phaser.Physics.P2.Body#setZeroRotation
+    */
+    setZeroRotation: function () {
+
+        this.data.angularVelocity = 0;
+
+    },
+
+    /**
+    * If this Body is dynamic then this will zero its velocity on both axis.
+    *
+    * @method Phaser.Physics.P2.Body#setZeroVelocity
+    */
+    setZeroVelocity: function () {
+
+        this.data.velocity[0] = 0;
+        this.data.velocity[1] = 0;
+
+    },
+
+    /**
+    * Sets the Body damping and angularDamping to zero.
+    *
+    * @method Phaser.Physics.P2.Body#setZeroDamping
+    */
+    setZeroDamping: function () {
+
+        this.data.damping = 0;
+        this.data.angularDamping = 0;
+
+    },
+
+    /**
+    * Transform a world point to local body frame.
+    *
+    * @method Phaser.Physics.P2.Body#toLocalFrame
+    * @param {Float32Array|Array} out - The vector to store the result in.
+    * @param {Float32Array|Array} worldPoint - The input world vector.
+    */
+    toLocalFrame: function (out, worldPoint) {
+
+        return this.data.toLocalFrame(out, worldPoint);
+
+    },
+
+    /**
+    * Transform a local point to world frame.
+    *
+    * @method Phaser.Physics.P2.Body#toWorldFrame
+    * @param {Array} out - The vector to store the result in.
+    * @param {Array} localPoint - The input local vector.
+    */
+    toWorldFrame: function (out, localPoint) {
+
+        return this.data.toWorldFrame(out, localPoint);
+
+    },
+
+    /**
+    * This will rotate the Body by the given speed to the left (counter-clockwise).
+    *
+    * @method Phaser.Physics.P2.Body#rotateLeft
+    * @param {number} speed - The speed at which it should rotate.
+    */
+    rotateLeft: function (speed) {
+
+        this.data.angularVelocity = this.world.pxm(-speed);
+
+    },
+
+    /**
+    * This will rotate the Body by the given speed to the left (clockwise).
+    *
+    * @method Phaser.Physics.P2.Body#rotateRight
+    * @param {number} speed - The speed at which it should rotate.
+    */
+    rotateRight: function (speed) {
+
+        this.data.angularVelocity = this.world.pxm(speed);
+
+    },
+
+    /**
+    * Moves the Body forwards based on its current angle and the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#moveForward
+    * @param {number} speed - The speed at which it should move forwards.
+    */
+    moveForward: function (speed) {
+
+        var magnitude = this.world.pxmi(-speed);
+        var angle = this.data.angle + Math.PI / 2;
+
+        this.data.velocity[0] = magnitude * Math.cos(angle);
+        this.data.velocity[1] = magnitude * Math.sin(angle);
+
+    },
+
+    /**
+    * Moves the Body backwards based on its current angle and the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#moveBackward
+    * @param {number} speed - The speed at which it should move backwards.
+    */
+    moveBackward: function (speed) {
+
+        var magnitude = this.world.pxmi(-speed);
+        var angle = this.data.angle + Math.PI / 2;
+
+        this.data.velocity[0] = -(magnitude * Math.cos(angle));
+        this.data.velocity[1] = -(magnitude * Math.sin(angle));
+
+    },
+
+    /**
+    * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#thrust
+    * @param {number} speed - The speed at which it should thrust.
+    */
+    thrust: function (speed) {
+
+        var magnitude = this.world.pxmi(-speed);
+        var angle = this.data.angle + Math.PI / 2;
+
+        this.data.force[0] += magnitude * Math.cos(angle);
+        this.data.force[1] += magnitude * Math.sin(angle);
+
+    },
+
+    /**
+    * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#reverse
+    * @param {number} speed - The speed at which it should reverse.
+    */
+    reverse: function (speed) {
+
+        var magnitude = this.world.pxmi(-speed);
+        var angle = this.data.angle + Math.PI / 2;
+
+        this.data.force[0] -= magnitude * Math.cos(angle);
+        this.data.force[1] -= magnitude * Math.sin(angle);
+
+    },
+
+    /**
+    * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#moveLeft
+    * @param {number} speed - The speed at which it should move to the left, in pixels per second.
+    */
+    moveLeft: function (speed) {
+
+        this.data.velocity[0] = this.world.pxmi(-speed);
+
+    },
+
+    /**
+    * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#moveRight
+    * @param {number} speed - The speed at which it should move to the right, in pixels per second.
+    */
+    moveRight: function (speed) {
+
+        this.data.velocity[0] = this.world.pxmi(speed);
+
+    },
+
+    /**
+    * If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#moveUp
+    * @param {number} speed - The speed at which it should move up, in pixels per second.
+    */
+    moveUp: function (speed) {
+
+        this.data.velocity[1] = this.world.pxmi(-speed);
+
+    },
+
+    /**
+    * If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
+    * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
+    *
+    * @method Phaser.Physics.P2.Body#moveDown
+    * @param {number} speed - The speed at which it should move down, in pixels per second.
+    */
+    moveDown: function (speed) {
+
+        this.data.velocity[1] = this.world.pxmi(speed);
+
+    },
+
+    /**
+    * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
+    *
+    * @method Phaser.Physics.P2.Body#preUpdate
+    * @protected
+    */
+    preUpdate: function () {
+
+        this.dirty = true;
+
+        if (this.removeNextStep)
+        {
+            this.removeFromWorld();
+            this.removeNextStep = false;
+        }
+
+    },
+
+    /**
+    * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
+    *
+    * @method Phaser.Physics.P2.Body#postUpdate
+    * @protected
+    */
+    postUpdate: function () {
+
+        this.sprite.x = this.world.mpxi(this.data.position[0]);
+        this.sprite.y = this.world.mpxi(this.data.position[1]);
+
+        if (!this.fixedRotation)
+        {
+            this.sprite.rotation = this.data.angle;
+        }
+
+        if (this.debugBody)
+        {
+            this.debugBody.updateSpriteTransform();
+        }
+
+        this.dirty = false;
+
+    },
+
+    /**
+    * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass.
+    *
+    * @method Phaser.Physics.P2.Body#reset
+    * @param {number} x - The new x position of the Body.
+    * @param {number} y - The new x position of the Body.
+    * @param {boolean} [resetDamping=false] - Resets the linear and angular damping.
+    * @param {boolean} [resetMass=false] - Sets the Body mass back to 1.
+    */
+    reset: function (x, y, resetDamping, resetMass) {
+
+        if (resetDamping === undefined) { resetDamping = false; }
+        if (resetMass === undefined) { resetMass = false; }
+
+        this.setZeroForce();
+        this.setZeroVelocity();
+        this.setZeroRotation();
+
+        if (resetDamping)
+        {
+            this.setZeroDamping();
+        }
+
+        if (resetMass)
+        {
+            this.mass = 1;
+        }
+
+        this.x = x;
+        this.y = y;
+
+    },
+
+    /**
+    * Adds this physics body to the world.
+    *
+    * @method Phaser.Physics.P2.Body#addToWorld
+    */
+    addToWorld: function () {
+
+        if (this.game.physics.p2._toRemove)
+        {
+            for (var i = 0; i < this.game.physics.p2._toRemove.length; i++)
+            {
+                if (this.game.physics.p2._toRemove[i] === this)
+                {
+                    this.game.physics.p2._toRemove.splice(i, 1);
+                }
+            }
+        }
+
+        if (this.data.world !== this.game.physics.p2.world)
+        {
+            this.game.physics.p2.addBody(this);
+        }
+
+    },
+
+    /**
+    * Removes this physics body from the world.
+    *
+    * @method Phaser.Physics.P2.Body#removeFromWorld
+    */
+    removeFromWorld: function () {
+
+        if (this.data.world === this.game.physics.p2.world)
+        {
+            this.game.physics.p2.removeBodyNextStep(this);
+        }
+
+    },
+
+    /**
+    * Destroys this Body and all references it holds to other objects.
+    *
+    * @method Phaser.Physics.P2.Body#destroy
+    */
+    destroy: function () {
+
+        this.removeFromWorld();
+
+        this.clearShapes();
+
+        this._bodyCallbacks = {};
+        this._bodyCallbackContext = {};
+        this._groupCallbacks = {};
+        this._groupCallbackContext = {};
+
+        if (this.debugBody)
+        {
+            this.debugBody.destroy(true, true);
+        }
+
+        this.debugBody = null;
+
+        if (this.sprite)
+        {
+            this.sprite.body = null;
+            this.sprite = null;
+        }
+
+    },
+
+    /**
+    * Removes all Shapes from this Body.
+    *
+    * @method Phaser.Physics.P2.Body#clearShapes
+    */
+    clearShapes: function () {
+
+        var i = this.data.shapes.length;
+
+        while (i--)
+        {
+            this.data.removeShape(this.data.shapes[i]);
+        }
+
+        this.shapeChanged();
+
+    },
+
+    /**
+    * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass.
+    * Will automatically update the mass properties and bounding radius.
+    * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
+    *
+    * @method Phaser.Physics.P2.Body#addShape
+    * @param {p2.Shape} shape - The shape to add to the body.
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Shape} The shape that was added to the body.
+    */
+    addShape: function (shape, offsetX, offsetY, rotation) {
+
+        if (offsetX === undefined) { offsetX = 0; }
+        if (offsetY === undefined) { offsetY = 0; }
+        if (rotation === undefined) { rotation = 0; }
+
+        this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation);
+        this.shapeChanged();
+
+        return shape;
+
+    },
+
+    /**
+    * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation.
+    *
+    * @method Phaser.Physics.P2.Body#addCircle
+    * @param {number} radius - The radius of this circle (in pixels)
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Circle} The Circle shape that was added to the Body.
+    */
+    addCircle: function (radius, offsetX, offsetY, rotation) {
+
+        var shape = new p2.Circle({ radius: this.world.pxm(radius) });
+
+        return this.addShape(shape, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation.
+    *
+    * @method Phaser.Physics.P2.Body#addRectangle
+    * @param {number} width - The width of the rectangle in pixels.
+    * @param {number} height - The height of the rectangle in pixels.
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Box} The shape that was added to the Body.
+    */
+    addRectangle: function (width, height, offsetX, offsetY, rotation) {
+
+        var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)});
+
+        return this.addShape(shape, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation.
+    *
+    * @method Phaser.Physics.P2.Body#addPlane
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Plane} The Plane shape that was added to the Body.
+    */
+    addPlane: function (offsetX, offsetY, rotation) {
+
+        var shape = new p2.Plane();
+
+        return this.addShape(shape, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation.
+    *
+    * @method Phaser.Physics.P2.Body#addParticle
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Particle} The Particle shape that was added to the Body.
+    */
+    addParticle: function (offsetX, offsetY, rotation) {
+
+        var shape = new p2.Particle();
+
+        return this.addShape(shape, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Adds a Line shape to this Body.
+    * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
+    * You can control the offset from the center of the body and the rotation.
+    *
+    * @method Phaser.Physics.P2.Body#addLine
+    * @param {number} length - The length of this line (in pixels)
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Line} The Line shape that was added to the Body.
+    */
+    addLine: function (length, offsetX, offsetY, rotation) {
+
+        var shape = new p2.Line({ length: this.world.pxm(length)});
+
+        return this.addShape(shape, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Adds a Capsule shape to this Body.
+    * You can control the offset from the center of the body and the rotation.
+    *
+    * @method Phaser.Physics.P2.Body#addCapsule
+    * @param {number} length - The distance between the end points in pixels.
+    * @param {number} radius - Radius of the capsule in pixels.
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Capsule} The Capsule shape that was added to the Body.
+    */
+    addCapsule: function (length, radius, offsetX, offsetY, rotation) {
+
+        var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) });
+
+        return this.addShape(shape, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes.
+    * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly.
+    *
+    * @method Phaser.Physics.P2.Body#addPolygon
+    * @param {object} options - An object containing the build options:
+    * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
+    * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
+    * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
+    * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
+    *                                       Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
+    *                                       or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
+    * @return {boolean} True on success, else false.
+    */
+    addPolygon: function (options, points) {
+
+        options = options || {};
+
+        if (!Array.isArray(points))
+        {
+            points = Array.prototype.slice.call(arguments, 1);
+        }
+
+        var path = [];
+
+        //  Did they pass in a single array of points?
+        if (points.length === 1 && Array.isArray(points[0]))
+        {
+            path = points[0].slice(0);
+        }
+        else if (Array.isArray(points[0]))
+        {
+            path = points.slice();
+        }
+        else if (typeof points[0] === 'number')
+        {
+            //  We've a list of numbers
+            for (var i = 0, len = points.length; i < len; i += 2)
+            {
+                path.push([points[i], points[i + 1]]);
+            }
+        }
+
+        //  top and tail
+        var idx = path.length - 1;
+
+        if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1])
+        {
+            path.pop();
+        }
+
+        //  Now process them into p2 values
+        for (var p = 0; p < path.length; p++)
+        {
+            path[p][0] = this.world.pxmi(path[p][0]);
+            path[p][1] = this.world.pxmi(path[p][1]);
+        }
+
+        var result = this.data.fromPolygon(path, options);
+
+        this.shapeChanged();
+
+        return result;
+
+    },
+
+    /**
+    * Remove a shape from the body. Will automatically update the mass properties and bounding radius.
+    *
+    * @method Phaser.Physics.P2.Body#removeShape
+    * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body.
+    * @return {boolean} True if the shape was found and removed, else false.
+    */
+    removeShape: function (shape) {
+
+		var result = this.data.removeShape(shape);
+
+		this.shapeChanged();
+
+        return result;
+    },
+
+    /**
+    * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body.
+    * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
+    *
+    * @method Phaser.Physics.P2.Body#setCircle
+    * @param {number} radius - The radius of this circle (in pixels)
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    */
+    setCircle: function (radius, offsetX, offsetY, rotation) {
+
+        this.clearShapes();
+
+        return this.addCircle(radius, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body.
+    * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite.
+    * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
+    *
+    * @method Phaser.Physics.P2.Body#setRectangle
+    * @param {number} [width=16] - The width of the rectangle in pixels.
+    * @param {number} [height=16] - The height of the rectangle in pixels.
+    * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
+    * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
+    * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
+    * @return {p2.Rectangle} The Rectangle shape that was added to the Body.
+    */
+    setRectangle: function (width, height, offsetX, offsetY, rotation) {
+
+        if (width === undefined) { width = 16; }
+        if (height === undefined) { height = 16; }
+
+        this.clearShapes();
+
+        return this.addRectangle(width, height, offsetX, offsetY, rotation);
+
+    },
+
+    /**
+    * Clears any previously set shapes.
+    * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given.
+    * If no Sprite is given it defaults to using the parent of this Body.
+    * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
+    *
+    * @method Phaser.Physics.P2.Body#setRectangleFromSprite
+    * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions.
+    * @return {p2.Rectangle} The Rectangle shape that was added to the Body.
+    */
+    setRectangleFromSprite: function (sprite) {
+
+        if (sprite === undefined) { sprite = this.sprite; }
+
+        this.clearShapes();
+
+        return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation);
+
+    },
+
+    /**
+    * Adds the given Material to all Shapes that belong to this Body.
+    * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter.
+    *
+    * @method Phaser.Physics.P2.Body#setMaterial
+    * @param {Phaser.Physics.P2.Material} material - The Material that will be applied.
+    * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body.
+    */
+    setMaterial: function (material, shape) {
+
+        if (shape === undefined)
+        {
+            for (var i = this.data.shapes.length - 1; i >= 0; i--)
+            {
+                this.data.shapes[i].material = material;
+            }
+        }
+        else
+        {
+            shape.material = material;
+        }
+
+    },
+
+    /**
+    * Updates the debug draw if any body shapes change.
+    *
+    * @method Phaser.Physics.P2.Body#shapeChanged
+    */
+    shapeChanged: function() {
+
+        if (this.debugBody)
+        {
+            this.debugBody.draw();
+        }
+
+    },
+
+    /**
+    * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
+    * The shape data format is based on the custom phaser export in.
+    *
+    * @method Phaser.Physics.P2.Body#addPhaserPolygon
+    * @param {string} key - The key of the Physics Data file as stored in Game.Cache.
+    * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from.
+    */
+    addPhaserPolygon: function (key, object) {
+
+        var data = this.game.cache.getPhysicsData(key, object);
+        var createdFixtures = [];
+
+        //  Cycle through the fixtures
+        for (var i = 0; i < data.length; i++)
+        {
+            var fixtureData = data[i];
+            var shapesOfFixture = this.addFixture(fixtureData);
+
+            //  Always add to a group
+            createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || [];
+            createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture);
+
+            //  if (unique) fixture key is provided
+            if (fixtureData.fixtureKey)
+            {
+                createdFixtures[fixtureData.fixtureKey] = shapesOfFixture;
+            }
+        }
+
+        this.data.aabbNeedsUpdate = true;
+        this.shapeChanged();
+
+        return createdFixtures;
+
+    },
+
+    /**
+    * Add a polygon fixture. This is used during #loadPolygon.
+    *
+    * @method Phaser.Physics.P2.Body#addFixture
+    * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes.
+    * @return {array} An array containing the generated shapes for the given polygon.
+    */
+    addFixture: function (fixtureData) {
+
+        var generatedShapes = [];
+
+        if (fixtureData.circle)
+        {
+            var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) });
+            shape.collisionGroup = fixtureData.filter.categoryBits;
+            shape.collisionMask = fixtureData.filter.maskBits;
+            shape.sensor = fixtureData.isSensor;
+
+            var offset = p2.vec2.create();
+            offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2);
+            offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2);
+
+            this.data.addShape(shape, offset);
+            generatedShapes.push(shape);
+        }
+        else
+        {
+            var polygons = fixtureData.polygons;
+            var cm = p2.vec2.create();
+
+            for (var i = 0; i < polygons.length; i++)
+            {
+                var shapes = polygons[i];
+                var vertices = [];
+
+                for (var s = 0; s < shapes.length; s += 2)
+                {
+                    vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]);
+                }
+
+                var shape = new p2.Convex({ vertices: vertices });
+
+                //  Move all vertices so its center of mass is in the local center of the convex
+                for (var j = 0; j !== shape.vertices.length; j++)
+                {
+                    var v = shape.vertices[j];
+                    p2.vec2.sub(v, v, shape.centerOfMass);
+                }
+
+                p2.vec2.scale(cm, shape.centerOfMass, 1);
+
+                cm[0] -= this.world.pxmi(this.sprite.width / 2);
+                cm[1] -= this.world.pxmi(this.sprite.height / 2);
+
+                shape.updateTriangles();
+                shape.updateCenterOfMass();
+                shape.updateBoundingRadius();
+
+                shape.collisionGroup = fixtureData.filter.categoryBits;
+                shape.collisionMask = fixtureData.filter.maskBits;
+                shape.sensor = fixtureData.isSensor;
+
+                this.data.addShape(shape, cm);
+
+                generatedShapes.push(shape);
+            }
+        }
+
+        return generatedShapes;
+
+    },
+
+    /**
+    * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
+    * 
+    * As well as reading the data from the Cache you can also pass `null` as the first argument and a
+    * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance.
+    * 
+    * For more details see the format of the Lime / Corona Physics Editor export.
+    *
+    * @method Phaser.Physics.P2.Body#loadPolygon
+    * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the 
+    *     data as the 2nd argument.
+    * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, 
+    *     or if key is null pass the actual physics data object itself as this parameter.
+    * @return {boolean} True on success, else false.
+    */
+    loadPolygon: function (key, object) {
+
+        if (key === null)
+        {
+            var data = object;
+        }
+        else
+        {
+            var data = this.game.cache.getPhysicsData(key, object);
+        }
+
+        //  We've multiple Convex shapes, they should be CCW automatically
+        var cm = p2.vec2.create();
+
+        for (var i = 0; i < data.length; i++)
+        {
+            var vertices = [];
+
+            for (var s = 0; s < data[i].shape.length; s += 2)
+            {
+                vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]);
+            }
+
+            var c = new p2.Convex({ vertices: vertices });
+
+            // Move all vertices so its center of mass is in the local center of the convex
+            for (var j = 0; j !== c.vertices.length; j++)
+            {
+                var v = c.vertices[j];
+                p2.vec2.sub(v, v, c.centerOfMass);
+            }
+
+            p2.vec2.scale(cm, c.centerOfMass, 1);
+
+            cm[0] -= this.world.pxmi(this.sprite.width / 2);
+            cm[1] -= this.world.pxmi(this.sprite.height / 2);
+
+            c.updateTriangles();
+            c.updateCenterOfMass();
+            c.updateBoundingRadius();
+
+            this.data.addShape(c, cm);
+        }
+
+        this.data.aabbNeedsUpdate = true;
+        this.shapeChanged();
+
+        return true;
+
+    }
+
+};
+
+Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body;
+
+/**
+ * Dynamic body. Dynamic bodies body can move and respond to collisions and forces.
+ * @property DYNAMIC
+ * @type {Number}
+ * @static
+ */
+Phaser.Physics.P2.Body.DYNAMIC = 1;
+
+/**
+ * Static body. Static bodies do not move, and they do not respond to forces or collision.
+ * @property STATIC
+ * @type {Number}
+ * @static
+ */
+Phaser.Physics.P2.Body.STATIC = 2;
+
+/**
+ * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.
+ * @property KINEMATIC
+ * @type {Number}
+ * @static
+ */
+Phaser.Physics.P2.Body.KINEMATIC = 4;
+
+/**
+* @name Phaser.Physics.P2.Body#static
+* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", {
+
+    get: function () {
+
+        return (this.data.type === Phaser.Physics.P2.Body.STATIC);
+
+    },
+
+    set: function (value) {
+
+        if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC)
+        {
+            this.data.type = Phaser.Physics.P2.Body.STATIC;
+            this.mass = 0;
+        }
+        else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC)
+        {
+            this.data.type = Phaser.Physics.P2.Body.DYNAMIC;
+
+            if (this.mass === 0)
+            {
+                this.mass = 1;
+            }
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#dynamic
+* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", {
+
+    get: function () {
+
+        return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC);
+
+    },
+
+    set: function (value) {
+
+        if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC)
+        {
+            this.data.type = Phaser.Physics.P2.Body.DYNAMIC;
+
+            if (this.mass === 0)
+            {
+                this.mass = 1;
+            }
+        }
+        else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC)
+        {
+            this.data.type = Phaser.Physics.P2.Body.STATIC;
+            this.mass = 0;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#kinematic
+* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", {
+
+    get: function () {
+
+        return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC);
+
+    },
+
+    set: function (value) {
+
+        if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC)
+        {
+            this.data.type = Phaser.Physics.P2.Body.KINEMATIC;
+            this.mass = 4;
+        }
+        else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC)
+        {
+            this.data.type = Phaser.Physics.P2.Body.STATIC;
+            this.mass = 0;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#allowSleep
+* @property {boolean} allowSleep -
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", {
+
+    get: function () {
+
+        return this.data.allowSleep;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this.data.allowSleep)
+        {
+            this.data.allowSleep = value;
+        }
+
+    }
+
+});
+
+/**
+* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
+* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90.
+* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values.
+*
+* @name Phaser.Physics.P2.Body#angle
+* @property {number} angle - The angle of this Body in degrees.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", {
+
+    get: function() {
+
+        return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle));
+
+    },
+
+    set: function(value) {
+
+        this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
+
+    }
+
+});
+
+/**
+* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
+* @name Phaser.Physics.P2.Body#angularDamping
+* @property {number} angularDamping - The angular damping acting acting on the body.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", {
+
+    get: function () {
+
+        return this.data.angularDamping;
+
+    },
+
+    set: function (value) {
+
+        this.data.angularDamping = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#angularForce
+* @property {number} angularForce - The angular force acting on the body.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", {
+
+    get: function () {
+
+        return this.data.angularForce;
+
+    },
+
+    set: function (value) {
+
+        this.data.angularForce = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#angularVelocity
+* @property {number} angularVelocity - The angular velocity of the body.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", {
+
+    get: function () {
+
+        return this.data.angularVelocity;
+
+    },
+
+    set: function (value) {
+
+        this.data.angularVelocity = value;
+
+    }
+
+});
+
+/**
+* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
+* @name Phaser.Physics.P2.Body#damping
+* @property {number} damping - The linear damping acting on the body in the velocity direction.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", {
+
+    get: function () {
+
+        return this.data.damping;
+
+    },
+
+    set: function (value) {
+
+        this.data.damping = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#fixedRotation
+* @property {boolean} fixedRotation -
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", {
+
+    get: function () {
+
+        return this.data.fixedRotation;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this.data.fixedRotation)
+        {
+            this.data.fixedRotation = value;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#inertia
+* @property {number} inertia - The inertia of the body around the Z axis..
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", {
+
+    get: function () {
+
+        return this.data.inertia;
+
+    },
+
+    set: function (value) {
+
+        this.data.inertia = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#mass
+* @property {number} mass - The mass of the body.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", {
+
+    get: function () {
+
+        return this.data.mass;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this.data.mass)
+        {
+            this.data.mass = value;
+            this.data.updateMassProperties();
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#motionState
+* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity).
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", {
+
+    get: function () {
+
+        return this.data.type;
+
+    },
+
+    set: function (value) {
+
+        if (value !== this.data.type)
+        {
+            this.data.type = value;
+        }
+
+    }
+
+});
+
+/**
+* The angle of the Body in radians.
+* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values.
+*
+* @name Phaser.Physics.P2.Body#rotation
+* @property {number} rotation - The angle of this Body in radians.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", {
+
+    get: function() {
+
+        return this.data.angle;
+
+    },
+
+    set: function(value) {
+
+        this.data.angle = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#sleepSpeedLimit
+* @property {number} sleepSpeedLimit - .
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", {
+
+    get: function () {
+
+        return this.data.sleepSpeedLimit;
+
+    },
+
+    set: function (value) {
+
+        this.data.sleepSpeedLimit = value;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#x
+* @property {number} x - The x coordinate of this Body.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", {
+
+    get: function () {
+
+        return this.world.mpxi(this.data.position[0]);
+
+    },
+
+    set: function (value) {
+
+        this.data.position[0] = this.world.pxmi(value);
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#y
+* @property {number} y - The y coordinate of this Body.
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", {
+
+    get: function () {
+
+        return this.world.mpxi(this.data.position[1]);
+
+    },
+
+    set: function (value) {
+
+        this.data.position[1] = this.world.pxmi(value);
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#id
+* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID.
+* @readonly
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", {
+
+    get: function () {
+
+        return this.data.id;
+
+    }
+
+});
+
+/**
+* @name Phaser.Physics.P2.Body#debug
+* @property {boolean} debug - Enable or disable debug drawing of this body
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", {
+
+    get: function () {
+
+        return (this.debugBody !== null);
+
+    },
+
+    set: function (value) {
+
+        if (value && !this.debugBody)
+        {
+            //  This will be added to the global space
+            this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data);
+        }
+        else if (!value && this.debugBody)
+        {
+            this.debugBody.destroy();
+            this.debugBody = null;
+        }
+
+    }
+
+});
+
+/**
+* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World.
+* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials.
+* Also note that when you set this it will only effect Body shapes that already exist. If you then add further shapes to your Body
+* after setting this it will *not* proactively set them to collide with the bounds.
+*
+* @name Phaser.Physics.P2.Body#collideWorldBounds
+* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
+*/
+Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", {
+
+    get: function () {
+
+        return this._collideWorldBounds;
+
+    },
+
+    set: function (value) {
+
+        if (value && !this._collideWorldBounds)
+        {
+            this._collideWorldBounds = true;
+            this.updateCollisionMask();
+        }
+        else if (!value && this._collideWorldBounds)
+        {
+            this._collideWorldBounds = false;
+            this.updateCollisionMask();
+        }
+
+    }
+
+});
+
+/**
+* @author       George https://github.com/georgiee
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Draws a P2 Body to a Graphics instance for visual debugging.
+* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead.
+* So use sparingly and rarely (if ever) in production code.
+*
+* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you
+* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will
+* need to manually adjust its BodyDebug as well.
+*
+* @class Phaser.Physics.P2.BodyDebug
+* @constructor
+* @extends Phaser.Group
+* @param {Phaser.Game} game - Game reference to the currently running game.
+* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
+* @param {object} settings - Settings object.
+*/
+Phaser.Physics.P2.BodyDebug = function(game, body, settings) {
+
+    Phaser.Group.call(this, game);
+
+    /**
+    * @property {object} defaultSettings - Default debug settings.
+    * @private
+    */
+    var defaultSettings = {
+        pixelsPerLengthUnit: 20,
+        debugPolygons: false,
+        lineWidth: 1,
+        alpha: 0.5
+    };
+
+    this.settings = Phaser.Utils.extend(defaultSettings, settings);
+
+    /**
+    * @property {number} ppu - Pixels per Length Unit.
+    */
+    this.ppu = this.settings.pixelsPerLengthUnit;
+    this.ppu = -1 * this.ppu;
+
+    /**
+    * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
+    */
+    this.body = body;
+
+    /**
+    * @property {Phaser.Graphics} canvas - The canvas to render the debug info to.
+    */
+    this.canvas = new Phaser.Graphics(game);
+
+    this.canvas.alpha = this.settings.alpha;
+
+    this.add(this.canvas);
+
+    this.draw();
+
+    this.updateSpriteTransform();
+
+};
+
+Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype);
+Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug;
+
+Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, {
+
+    /**
+    * Core update.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform
+    */
+    updateSpriteTransform: function() {
+
+        this.position.x = this.body.position[0] * this.ppu;
+        this.position.y = this.body.position[1] * this.ppu;
+        this.rotation = this.body.angle;
+
+    },
+
+    /**
+    * Draws the P2 shapes to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#draw
+    */
+    draw: function() {
+
+        var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1;
+
+        obj = this.body;
+        sprite = this.canvas;
+        sprite.clear();
+        color = parseInt(this.randomPastelHex(), 16);
+        lineColor = 0xff0000;
+        lw = this.lineWidth;
+
+        if (obj instanceof p2.Body && obj.shapes.length)
+        {
+            var l = obj.shapes.length;
+
+            i = 0;
+
+            while (i !== l)
+            {
+                child = obj.shapes[i];
+                offset = child.position || 0;
+                angle = child.angle || 0;
+
+                if (child instanceof p2.Circle)
+                {
+                    this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw);
+                }
+                else if (child instanceof p2.Capsule)
+                {
+                    this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw);
+                }
+                else if (child instanceof p2.Plane)
+                {
+                    this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle);
+                }
+                else if (child instanceof p2.Line)
+                {
+                    this.drawLine(sprite, child.length * this.ppu, lineColor, lw);
+                }
+                else if (child instanceof p2.Box)
+                {
+                    this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw);
+                }
+                else if (child instanceof p2.Convex)
+                {
+                    verts = [];
+                    vrot = p2.vec2.create();
+
+                    for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j)
+                    {
+                        v = child.vertices[j];
+                        p2.vec2.rotate(vrot, v, angle);
+                        verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]);
+                    }
+
+                    this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]);
+                }
+
+                i++;
+            }
+        }
+
+    },
+
+    /**
+    * Draws a p2.Box to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawRectangle
+    * @private
+    */
+    drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) {
+
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color = 0x000000; }
+
+        g.lineStyle(lineWidth, color, 1);
+        g.beginFill(fillColor);
+        g.drawRect(x - w / 2, y - h / 2, w, h);
+
+    },
+
+    /**
+    * Draws a p2.Circle to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawCircle
+    * @private
+    */
+    drawCircle: function(g, x, y, angle, radius, color, lineWidth) {
+
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color = 0xffffff; }
+        g.lineStyle(lineWidth, 0x000000, 1);
+        g.beginFill(color, 1.0);
+        g.drawCircle(x, y, -radius*2);
+        g.endFill();
+        g.moveTo(x, y);
+        g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle));
+
+    },
+
+    /**
+    * Draws a p2.Line to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawLine
+    * @private
+    */
+    drawLine: function(g, len, color, lineWidth) {
+
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color = 0x000000; }
+
+        g.lineStyle(lineWidth * 5, color, 1);
+        g.moveTo(-len / 2, 0);
+        g.lineTo(len / 2, 0);
+
+    },
+
+    /**
+    * Draws a p2.Convex to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawConvex
+    * @private
+    */
+    drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) {
+
+        var colors, i, v, v0, v1, x, x0, x1, y, y0, y1;
+
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color = 0x000000; }
+
+        if (!debug)
+        {
+            g.lineStyle(lineWidth, color, 1);
+            g.beginFill(fillColor);
+            i = 0;
+
+            while (i !== verts.length)
+            {
+                v = verts[i];
+                x = v[0];
+                y = v[1];
+
+                if (i === 0)
+                {
+                    g.moveTo(x, -y);
+                }
+                else
+                {
+                    g.lineTo(x, -y);
+                }
+
+                i++;
+            }
+
+            g.endFill();
+
+            if (verts.length > 2)
+            {
+                g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]);
+                return g.lineTo(verts[0][0], -verts[0][1]);
+            }
+        }
+        else
+        {
+            colors = [0xff0000, 0x00ff00, 0x0000ff];
+            i = 0;
+
+            while (i !== verts.length + 1)
+            {
+                v0 = verts[i % verts.length];
+                v1 = verts[(i + 1) % verts.length];
+                x0 = v0[0];
+                y0 = v0[1];
+                x1 = v1[0];
+                y1 = v1[1];
+                g.lineStyle(lineWidth, colors[i % colors.length], 1);
+                g.moveTo(x0, -y0);
+                g.lineTo(x1, -y1);
+                g.drawCircle(x0, -y0, lineWidth * 2);
+                i++;
+            }
+
+            g.lineStyle(lineWidth, 0x000000, 1);
+            return g.drawCircle(offset[0], offset[1], lineWidth * 2);
+        }
+
+    },
+
+    /**
+    * Draws a p2.Path to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawPath
+    * @private
+    */
+    drawPath: function(g, path, color, fillColor, lineWidth) {
+
+        var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y;
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color = 0x000000; }
+
+        g.lineStyle(lineWidth, color, 1);
+
+        if (typeof fillColor === "number")
+        {
+            g.beginFill(fillColor);
+        }
+
+        lastx = null;
+        lasty = null;
+        i = 0;
+
+        while (i < path.length)
+        {
+            v = path[i];
+            x = v[0];
+            y = v[1];
+
+            if (x !== lastx || y !== lasty)
+            {
+                if (i === 0)
+                {
+                    g.moveTo(x, y);
+                }
+                else
+                {
+                    p1x = lastx;
+                    p1y = lasty;
+                    p2x = x;
+                    p2y = y;
+                    p3x = path[(i + 1) % path.length][0];
+                    p3y = path[(i + 1) % path.length][1];
+                    area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y));
+
+                    if (area !== 0)
+                    {
+                        g.lineTo(x, y);
+                    }
+                }
+                lastx = x;
+                lasty = y;
+            }
+
+            i++;
+
+        }
+
+        if (typeof fillColor === "number")
+        {
+            g.endFill();
+        }
+
+        if (path.length > 2 && typeof fillColor === "number")
+        {
+            g.moveTo(path[path.length - 1][0], path[path.length - 1][1]);
+            g.lineTo(path[0][0], path[0][1]);
+        }
+
+    },
+
+    /**
+    * Draws a p2.Plane to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawPlane
+    * @private
+    */
+    drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) {
+
+        var max, xd, yd;
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color = 0xffffff; }
+
+        g.lineStyle(lineWidth, lineColor, 11);
+        g.beginFill(color);
+        max = maxLength;
+
+        g.moveTo(x0, -x1);
+        xd = x0 + Math.cos(angle) * this.game.width;
+        yd = x1 + Math.sin(angle) * this.game.height;
+        g.lineTo(xd, -yd);
+
+        g.moveTo(x0, -x1);
+        xd = x0 + Math.cos(angle) * -this.game.width;
+        yd = x1 + Math.sin(angle) * -this.game.height;
+        g.lineTo(xd, -yd);
+
+    },
+
+    /**
+    * Draws a p2.Capsule to the Graphics object.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#drawCapsule
+    * @private
+    */
+    drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) {
+
+        if (lineWidth === undefined) { lineWidth = 1; }
+        if (color === undefined) { color =  0x000000; }
+
+        g.lineStyle(lineWidth, color, 1);
+
+        // Draw circles at ends
+        var c = Math.cos(angle);
+        var s = Math.sin(angle);
+
+        g.beginFill(fillColor, 1);
+        g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2);
+        g.drawCircle( len/2*c + x,  len/2*s + y, -radius * 2);
+        g.endFill();
+
+        // Draw rectangle
+        g.lineStyle(lineWidth, color, 0);
+        g.beginFill(fillColor, 1);
+        g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y);
+        g.lineTo( len/2*c + radius*s + x,  len/2*s + radius*c + y);
+        g.lineTo( len/2*c - radius*s + x,  len/2*s - radius*c + y);
+        g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y);
+        g.endFill();
+
+        // Draw lines in between
+        g.lineStyle(lineWidth, color, 1);
+        g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y);
+        g.lineTo( len/2*c + radius*s + x,  len/2*s + radius*c + y);
+        g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y);
+        g.lineTo( len/2*c - radius*s + x,  len/2*s - radius*c + y);
+
+    },
+
+    /**
+    * Picks a random pastel color.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#randomPastelHex
+    * @private
+    */
+    randomPastelHex: function() {
+
+        var blue, green, mix, red;
+        mix = [255, 255, 255];
+
+        red = Math.floor(Math.random() * 256);
+        green = Math.floor(Math.random() * 256);
+        blue = Math.floor(Math.random() * 256);
+
+        red = Math.floor((red + 3 * mix[0]) / 4);
+        green = Math.floor((green + 3 * mix[1]) / 4);
+        blue = Math.floor((blue + 3 * mix[2]) / 4);
+
+        return this.rgbToHex(red, green, blue);
+
+    },
+
+    /**
+    * Converts from RGB to Hex.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#rgbToHex
+    * @private
+    */
+    rgbToHex: function(r, g, b) {
+        return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
+    },
+
+    /**
+    * Component to hex conversion.
+    *
+    * @method Phaser.Physics.P2.BodyDebug#componentToHex
+    * @private
+    */
+    componentToHex: function(c) {
+
+        var hex;
+        hex = c.toString(16);
+
+        if (hex.len === 2)
+        {
+            return hex;
+        }
+        else
+        {
+            return hex + '0';
+        }
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
+*
+* @class Phaser.Physics.P2.Spring
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {p2.Body} bodyB - Second connected body.
+* @param {number} [restLength=1] - Rest length of the spring. A number > 0.
+* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
+* @param {number} [damping=1] - Damping of the spring. A number >= 0.
+* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
+*/
+Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    if (restLength === undefined) { restLength = 1; }
+    if (stiffness === undefined) { stiffness = 100; }
+    if (damping === undefined) { damping = 1; }
+
+    restLength = world.pxm(restLength);
+
+    var options = {
+        restLength: restLength,
+        stiffness: stiffness,
+        damping: damping
+    };
+
+    if (typeof worldA !== 'undefined' && worldA !== null)
+    {
+        options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ];
+    }
+
+    if (typeof worldB !== 'undefined' && worldB !== null)
+    {
+        options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ];
+    }
+
+    if (typeof localA !== 'undefined' && localA !== null)
+    {
+        options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ];
+    }
+
+    if (typeof localB !== 'undefined' && localB !== null)
+    {
+        options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ];
+    }
+
+    /**
+    * @property {p2.LinearSpring} data - The actual p2 spring object.
+    */
+    this.data = new p2.LinearSpring(bodyA, bodyB, options);
+
+    this.data.parent = this;
+
+};
+
+Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
+*
+* @class Phaser.Physics.P2.RotationalSpring
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {p2.Body} bodyB - Second connected body.
+* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
+* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
+* @param {number} [damping=1] - Damping of the spring. A number >= 0.
+*/
+Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) {
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    if (restAngle === undefined) { restAngle = null; }
+    if (stiffness === undefined) { stiffness = 100; }
+    if (damping === undefined) { damping = 1; }
+
+    if (restAngle)
+    {
+        restAngle = world.pxm(restAngle);
+    }
+
+    var options = {
+        restAngle: restAngle,
+        stiffness: stiffness,
+        damping: damping
+    };
+
+    /**
+    * @property {p2.RotationalSpring} data - The actual p2 spring object.
+    */
+    this.data = new p2.RotationalSpring(bodyA, bodyB, options);
+
+    this.data.parent = this;
+
+};
+
+Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A P2 Material.
+* 
+* \o/ ~ "Because I'm a Material girl"
+*
+* @class Phaser.Physics.P2.Material
+* @constructor
+* @param {string} name - The user defined name given to this Material.
+*/
+Phaser.Physics.P2.Material = function (name) {
+
+    /**
+    * @property {string} name - The user defined name given to this Material.
+    * @default
+    */
+    this.name = name;
+
+    p2.Material.call(this);
+
+};
+
+Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype);
+Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Defines a physics material
+*
+* @class Phaser.Physics.P2.ContactMaterial
+* @constructor
+* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
+* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material.
+* @param {object} [options] - Additional configuration options.
+*/
+Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) {
+
+	/**
+	* @property {number} id - The contact material identifier.
+	*/
+
+	/**
+	* @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
+	*/
+
+	/**
+	* @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material.
+	*/
+
+	/**
+	* @property {number} [friction=0.3] - Friction to use in the contact of these two materials.
+	*/
+
+	/**
+	* @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials.
+	*/
+
+	/**
+	* @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generate.
+	*/
+
+	/**
+	* @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generate.
+	*/
+
+	/**
+	* @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generate.
+	*/
+
+	/**
+	* @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generate.
+	*/
+
+	/**
+	* @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
+	*/
+
+    p2.ContactMaterial.call(this, materialA, materialB, options);
+
+};
+
+Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype);
+Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Collision Group
+*
+* @class Phaser.Physics.P2.CollisionGroup
+* @constructor
+* @param {number} bitmask - The CollisionGroup bitmask.
+*/
+Phaser.Physics.P2.CollisionGroup = function (bitmask) {
+
+    /**
+    * @property {number} mask - The CollisionGroup bitmask.
+    */
+    this.mask = bitmask;
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A constraint that tries to keep the distance between two bodies constant.
+*
+* @class Phaser.Physics.P2.DistanceConstraint
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {p2.Body} bodyB - Second connected body.
+* @param {number} distance - The distance to keep between the bodies.
+* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
+* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
+* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply.
+*/
+Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) {
+
+    if (distance === undefined) { distance = 100; }
+    if (localAnchorA === undefined) { localAnchorA = [0, 0]; }
+    if (localAnchorB === undefined) { localAnchorB = [0, 0]; }
+    if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    distance = world.pxm(distance);
+
+    localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ];
+    localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ];
+
+    var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce };
+
+    p2.DistanceConstraint.call(this, bodyA, bodyB, options);
+
+};
+
+Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype);
+Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
+*
+* @class Phaser.Physics.P2.GearConstraint
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {p2.Body} bodyB - Second connected body.
+* @param {number} [angle=0] - The relative angle
+* @param {number} [ratio=1] - The gear ratio.
+*/
+Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) {
+
+    if (angle === undefined) { angle = 0; }
+    if (ratio === undefined) { ratio = 1; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    var options = { angle: angle, ratio: ratio };
+
+    p2.GearConstraint.call(this, bodyA, bodyB, options);
+
+};
+
+Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype);
+Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Locks the relative position between two bodies.
+*
+* @class Phaser.Physics.P2.LockConstraint
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {p2.Body} bodyB - Second connected body.
+* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
+* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
+*/
+Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) {
+
+    if (offset === undefined) { offset = [0, 0]; }
+    if (angle === undefined) { angle = 0; }
+    if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ];
+
+    var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce };
+
+    p2.LockConstraint.call(this, bodyA, bodyB, options);
+
+};
+
+Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype);
+Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
+*
+* @class Phaser.Physics.P2.PrismaticConstraint
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {p2.Body} bodyB - Second connected body.
+* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
+* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
+*/
+Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
+
+    if (lockRotation === undefined) { lockRotation = true; }
+    if (anchorA === undefined) { anchorA = [0, 0]; }
+    if (anchorB === undefined) { anchorB = [0, 0]; }
+    if (axis === undefined) { axis = [0, 0]; }
+    if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ];
+    anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ];
+
+    var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation };
+
+    p2.PrismaticConstraint.call(this, bodyA, bodyB, options);
+
+};
+
+Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype);
+Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
+* The pivot points are given in world (pixel) coordinates.
+*
+* @class Phaser.Physics.P2.RevoluteConstraint
+* @constructor
+* @param {Phaser.Physics.P2} world - A reference to the P2 World.
+* @param {p2.Body} bodyA - First connected body.
+* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {p2.Body} bodyB - Second connected body.
+* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
+* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
+* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
+*/
+Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
+
+    if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
+    if (worldPivot === undefined) { worldPivot = null; }
+
+    /**
+    * @property {Phaser.Game} game - Local reference to game.
+    */
+    this.game = world.game;
+
+    /**
+    * @property {Phaser.Physics.P2} world - Local reference to P2 World.
+    */
+    this.world = world;
+
+    pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ];
+    pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ];
+
+    if (worldPivot)
+    {
+        worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ];
+    }
+
+    var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce };
+
+    p2.RevoluteConstraint.call(this, bodyA, bodyB, options);
+
+};
+
+Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype);
+Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* An Image Collection is a special tileset containing mulitple images, with no slicing into each image.
+*
+* Image Collections are normally created automatically when Tiled data is loaded.
+*
+* @class Phaser.ImageCollection
+* @constructor
+* @param {string} name - The name of the image collection in the map data.
+* @param {integer} firstgid - The first image index this image collection contains.
+* @param {integer} [width=32] - Width of widest image (in pixels).
+* @param {integer} [height=32] - Height of tallest image (in pixels).
+* @param {integer} [margin=0] - The margin around all images in the collection (in pixels).
+* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels).
+* @param {object} [properties={}] - Custom Image Collection properties.
+*/
+Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) {
+
+    if (width === undefined || width <= 0) { width = 32; }
+    if (height === undefined || height <= 0) { height = 32; }
+    if (margin === undefined) { margin = 0; }
+    if (spacing === undefined) { spacing = 0; }
+
+    /**
+    * The name of the Image Collection.
+    * @property {string} name
+    */
+    this.name = name;
+
+    /**
+    * The Tiled firstgid value.
+    * This is the starting index of the first image index this Image Collection contains.
+    * @property {integer} firstgid
+    */
+    this.firstgid = firstgid | 0;
+
+    /**
+    * The width of the widest image (in pixels).
+    * @property {integer} imageWidth
+    * @readonly
+    */
+    this.imageWidth = width | 0;
+
+    /**
+    * The height of the tallest image (in pixels).
+    * @property {integer} imageHeight
+    * @readonly
+    */
+    this.imageHeight = height | 0;
+
+    /**
+    * The margin around the images in the collection (in pixels).
+    * Use `setSpacing` to change.
+    * @property {integer} imageMarge
+    * @readonly
+    */
+    // Modified internally
+    this.imageMargin = margin | 0;
+
+    /**
+    * The spacing between each image in the collection (in pixels).
+    * Use `setSpacing` to change.
+    * @property {integer} imageSpacing
+    * @readonly
+    */
+    this.imageSpacing = spacing | 0;
+
+    /**
+    * Image Collection-specific properties that are typically defined in the Tiled editor.
+    * @property {object} properties
+    */
+    this.properties = properties || {};
+
+    /**
+    * The cached images that are a part of this collection.
+    * @property {array} images
+    * @readonly
+    */
+    // Modified internally
+    this.images = [];
+
+    /**
+    * The total number of images in the image collection.
+    * @property {integer} total
+    * @readonly
+    */
+    // Modified internally
+    this.total = 0;
+};
+
+Phaser.ImageCollection.prototype = {
+
+    /**
+    * Returns true if and only if this image collection contains the given image index.
+    *
+    * @method Phaser.ImageCollection#containsImageIndex
+    * @param {integer} imageIndex - The image index to search for.
+    * @return {boolean} True if this Image Collection contains the given index.
+    */
+    containsImageIndex: function (imageIndex) {
+
+        return (
+            imageIndex >= this.firstgid &&
+            imageIndex < (this.firstgid + this.total)
+        );
+
+    },
+
+    /**
+    * Add an image to this Image Collection.
+    *
+    * @method Phaser.ImageCollection#addImage
+    * @param {integer} gid - The gid of the image in the Image Collection.
+    * @param {string} image - The the key of the image in the Image Collection and in the cache.
+    */
+    addImage: function (gid, image) {
+
+        this.images.push({ gid: gid, image: image });
+        this.total++;
+
+    }
+
+};
+
+Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Tile is a representation of a single tile within the Tilemap.
+*
+* @class Phaser.Tile
+* @constructor
+* @param {object} layer - The layer in the Tilemap data that this tile belongs to.
+* @param {number} index - The index of this tile type in the core map data.
+* @param {number} x - The x coordinate of this tile.
+* @param {number} y - The y coordinate of this tile.
+* @param {number} width - Width of the tile.
+* @param {number} height - Height of the tile.
+*/
+Phaser.Tile = function (layer, index, x, y, width, height) {
+
+    /**
+    * @property {object} layer - The layer in the Tilemap data that this tile belongs to.
+    */
+    this.layer = layer;
+
+    /**
+    * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile.
+    */
+    this.index = index;
+
+    /**
+    * @property {number} x - The x map coordinate of this tile.
+    */
+    this.x = x;
+
+    /**
+    * @property {number} y - The y map coordinate of this tile.
+    */
+    this.y = y;
+    
+    /**
+    * @property {number} rotation - The rotation angle of this tile.
+    */
+    this.rotation = 0;
+
+    /**
+    * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not.
+    */
+    this.flipped = false;
+    
+    /**
+    * @property {number} x - The x map coordinate of this tile.
+    */
+    this.worldX = x * width;
+
+    /**
+    * @property {number} y - The y map coordinate of this tile.
+    */
+    this.worldY = y * height;
+
+    /**
+    * @property {number} width - The width of the tile in pixels.
+    */
+    this.width = width;
+
+    /**
+    * @property {number} height - The height of the tile in pixels.
+    */
+    this.height = height;
+
+    /**
+    * @property {number} width - The width of the tile in pixels.
+    */
+    this.centerX = Math.abs(width / 2);
+
+    /**
+    * @property {number} height - The height of the tile in pixels.
+    */
+    this.centerY = Math.abs(height / 2);
+
+    /**
+    * @property {number} alpha - The alpha value at which this tile is drawn to the canvas.
+    */
+    this.alpha = 1;
+
+    /**
+    * @property {object} properties - Tile specific properties.
+    */
+    this.properties = {};
+
+    /**
+    * @property {boolean} scanned - Has this tile been walked / turned into a poly?
+    */
+    this.scanned = false;
+
+    /**
+    * @property {boolean} faceTop - Is the top of this tile an interesting edge?
+    */
+    this.faceTop = false;
+
+    /**
+    * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge?
+    */
+    this.faceBottom = false;
+
+    /**
+    * @property {boolean} faceLeft - Is the left of this tile an interesting edge?
+    */
+    this.faceLeft = false;
+
+    /**
+    * @property {boolean} faceRight - Is the right of this tile an interesting edge?
+    */
+    this.faceRight = false;
+
+    /**
+    * @property {boolean} collideLeft - Indicating collide with any object on the left.
+    * @default
+    */
+    this.collideLeft = false;
+
+    /**
+    * @property {boolean} collideRight - Indicating collide with any object on the right.
+    * @default
+    */
+    this.collideRight = false;
+
+    /**
+    * @property {boolean} collideUp - Indicating collide with any object on the top.
+    * @default
+    */
+    this.collideUp = false;
+
+    /**
+    * @property {boolean} collideDown - Indicating collide with any object on the bottom.
+    * @default
+    */
+    this.collideDown = false;
+
+    /**
+    * @property {function} collisionCallback - Tile collision callback.
+    * @default
+    */
+    this.collisionCallback = null;
+
+    /**
+    * @property {object} collisionCallbackContext - The context in which the collision callback will be called.
+    * @default
+    */
+    this.collisionCallbackContext = this;
+
+};
+
+Phaser.Tile.prototype = {
+
+    /**
+    * Check if the given x and y world coordinates are within this Tile.
+    *
+    * @method Phaser.Tile#containsPoint
+    * @param {number} x - The x coordinate to test.
+    * @param {number} y - The y coordinate to test.
+    * @return {boolean} True if the coordinates are within this Tile, otherwise false.
+    */
+    containsPoint: function (x, y) {
+
+        return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom);
+
+    },
+
+    /**
+    * Check for intersection with this tile.
+    *
+    * @method Phaser.Tile#intersects
+    * @param {number} x - The x axis in pixels.
+    * @param {number} y - The y axis in pixels.
+    * @param {number} right - The right point.
+    * @param {number} bottom - The bottom point.
+    */
+    intersects: function (x, y, right, bottom) {
+
+        if (right <= this.worldX)
+        {
+            return false;
+        }
+
+        if (bottom <= this.worldY)
+        {
+            return false;
+        }
+
+        if (x >= this.worldX + this.width)
+        {
+            return false;
+        }
+
+        if (y >= this.worldY + this.height)
+        {
+            return false;
+        }
+
+        return true;
+
+    },
+
+    /**
+    * Set a callback to be called when this tile is hit by an object.
+    * The callback must true true for collision processing to take place.
+    *
+    * @method Phaser.Tile#setCollisionCallback
+    * @param {function} callback - Callback function.
+    * @param {object} context - Callback will be called within this context.
+    */
+    setCollisionCallback: function (callback, context) {
+
+        this.collisionCallback = callback;
+        this.collisionCallbackContext = context;
+
+    },
+
+    /**
+    * Clean up memory.
+    *
+    * @method Phaser.Tile#destroy
+    */
+    destroy: function () {
+
+        this.collisionCallback = null;
+        this.collisionCallbackContext = null;
+        this.properties = null;
+
+    },
+
+    /**
+    * Sets the collision flags for each side of this tile and updates the interesting faces list.
+    *
+    * @method Phaser.Tile#setCollision
+    * @param {boolean} left - Indicating collide with any object on the left.
+    * @param {boolean} right - Indicating collide with any object on the right.
+    * @param {boolean} up - Indicating collide with any object on the top.
+    * @param {boolean} down - Indicating collide with any object on the bottom.
+    */
+    setCollision: function (left, right, up, down) {
+
+        this.collideLeft = left;
+        this.collideRight = right;
+        this.collideUp = up;
+        this.collideDown = down;
+
+        this.faceLeft = left;
+        this.faceRight = right;
+        this.faceTop = up;
+        this.faceBottom = down;
+
+    },
+
+    /**
+    * Reset collision status flags.
+    *
+    * @method Phaser.Tile#resetCollision
+    */
+    resetCollision: function () {
+
+        this.collideLeft = false;
+        this.collideRight = false;
+        this.collideUp = false;
+        this.collideDown = false;
+
+        this.faceTop = false;
+        this.faceBottom = false;
+        this.faceLeft = false;
+        this.faceRight = false;
+
+    },
+
+    /**
+    * Is this tile interesting?
+    *
+    * @method Phaser.Tile#isInteresting
+    * @param {boolean} collides - If true will check any collides value.
+    * @param {boolean} faces - If true will check any face value.
+    * @return {boolean} True if the Tile is interesting, otherwise false.
+    */
+    isInteresting: function (collides, faces) {
+
+        if (collides && faces)
+        {
+            //  Does this tile have any collide flags OR interesting face?
+            return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback);
+        }
+        else if (collides)
+        {
+            //  Does this tile collide?
+            return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
+        }
+        else if (faces)
+        {
+            //  Does this tile have an interesting face?
+            return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight);
+        }
+
+        return false;
+
+    },
+
+    /**
+    * Copies the tile data and properties from the given tile to this tile.
+    *
+    * @method Phaser.Tile#copy
+    * @param {Phaser.Tile} tile - The tile to copy from.
+    */
+    copy: function (tile) {
+
+        this.index = tile.index;
+        this.alpha = tile.alpha;
+        this.properties = tile.properties;
+
+        this.collideUp = tile.collideUp;
+        this.collideDown = tile.collideDown;
+        this.collideLeft = tile.collideLeft;
+        this.collideRight = tile.collideRight;
+
+        this.collisionCallback = tile.collisionCallback;
+        this.collisionCallbackContext = tile.collisionCallbackContext;
+
+    }
+
+};
+
+Phaser.Tile.prototype.constructor = Phaser.Tile;
+
+/**
+* @name Phaser.Tile#collides
+* @property {boolean} collides - True if this tile can collide on any of its faces.
+* @readonly
+*/
+Object.defineProperty(Phaser.Tile.prototype, "collides", {
+
+    get: function () {
+        return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
+    }
+
+});
+
+/**
+* @name Phaser.Tile#canCollide
+* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set.
+* @readonly
+*/
+Object.defineProperty(Phaser.Tile.prototype, "canCollide", {
+
+    get: function () {
+        return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback);
+    }
+
+});
+
+/**
+* @name Phaser.Tile#left
+* @property {number} left - The x value in pixels.
+* @readonly
+*/
+Object.defineProperty(Phaser.Tile.prototype, "left", {
+
+    get: function () {
+        return this.worldX;
+    }
+
+});
+
+/**
+* @name Phaser.Tile#right
+* @property {number} right - The sum of the x and width properties.
+* @readonly
+*/
+Object.defineProperty(Phaser.Tile.prototype, "right", {
+
+    get: function () {
+        return this.worldX + this.width;
+    }
+
+});
+
+/**
+* @name Phaser.Tile#top
+* @property {number} top - The y value.
+* @readonly
+*/
+Object.defineProperty(Phaser.Tile.prototype, "top", {
+
+    get: function () {
+        return this.worldY;
+    }
+
+});
+
+/**
+* @name Phaser.Tile#bottom
+* @property {number} bottom - The sum of the y and height properties.
+* @readonly
+*/
+Object.defineProperty(Phaser.Tile.prototype, "bottom", {
+
+    get: function () {
+        return this.worldY + this.height;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
+* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
+* When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
+* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
+* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
+* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself.
+* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around.
+*
+* @class Phaser.Tilemap
+* @constructor
+* @param {Phaser.Game} game - Game reference to the currently running game.
+* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
+* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+*/
+Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {string} key - The key of this map data in the Phaser.Cache.
+    */
+    this.key = key;
+
+    var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height);
+
+    if (data === null)
+    {
+        return;
+    }
+
+    /**
+    * @property {number} width - The width of the map (in tiles).
+    */
+    this.width = data.width;
+
+    /**
+    * @property {number} height - The height of the map (in tiles).
+    */
+    this.height = data.height;
+
+    /**
+    * @property {number} tileWidth - The base width of the tiles in the map (in pixels).
+    */
+    this.tileWidth = data.tileWidth;
+
+    /**
+    * @property {number} tileHeight - The base height of the tiles in the map (in pixels).
+    */
+    this.tileHeight = data.tileHeight;
+
+    /**
+    * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'.
+    */
+    this.orientation = data.orientation;
+
+    /**
+    * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
+    */
+    this.format = data.format;
+
+    /**
+    * @property {number} version - The version of the map data (as specified in Tiled, usually 1).
+    */
+    this.version = data.version;
+
+    /**
+    * @property {object} properties - Map specific properties as specified in Tiled.
+    */
+    this.properties = data.properties;
+
+    /**
+    * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth.
+    */
+    this.widthInPixels = data.widthInPixels;
+
+    /**
+    * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight.
+    */
+    this.heightInPixels = data.heightInPixels;
+
+    /**
+    * @property {array} layers - An array of Tilemap layer data.
+    */
+    this.layers = data.layers;
+
+    /**
+    * @property {array} tilesets - An array of Tilesets.
+    */
+    this.tilesets = data.tilesets;
+    
+    /**
+    * @property {array} imagecollections - An array of Image Collections.
+    */
+    this.imagecollections = data.imagecollections;
+
+    /**
+    * @property {array} tiles - The super array of Tiles.
+    */
+    this.tiles = data.tiles;
+
+    /**
+    * @property {array} objects - An array of Tiled Object Layers.
+    */
+    this.objects = data.objects;
+
+    /**
+    * @property {array} collideIndexes - An array of tile indexes that collide.
+    */
+    this.collideIndexes = [];
+
+    /**
+    * @property {array} collision - An array of collision data (polylines, etc).
+    */
+    this.collision = data.collision;
+
+    /**
+    * @property {array} images - An array of Tiled Image Layers.
+    */
+    this.images = data.images;
+
+    /**
+    * @property {number} currentLayer - The current layer.
+    */
+    this.currentLayer = 0;
+
+    /**
+    * @property {array} debugMap - Map data used for debug values only.
+    */
+    this.debugMap = [];
+
+    /**
+    * @property {array} _results - Internal var.
+    * @private
+    */
+    this._results = [];
+
+    /**
+    * @property {number} _tempA - Internal var.
+    * @private
+    */
+    this._tempA = 0;
+
+    /**
+    * @property {number} _tempB - Internal var.
+    * @private
+    */
+    this._tempB = 0;
+
+};
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Tilemap.CSV = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Tilemap.TILED_JSON = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Tilemap.NORTH = 0;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Tilemap.EAST = 1;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Tilemap.SOUTH = 2;
+
+/**
+* @constant
+* @type {number}
+*/
+Phaser.Tilemap.WEST = 3;
+
+Phaser.Tilemap.prototype = {
+
+    /**
+    * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased.
+    *
+    * @method Phaser.Tilemap#create
+    * @param {string} name - The name of the default layer of the map.
+    * @param {number} width - The width of the map in tiles.
+    * @param {number} height - The height of the map in tiles.
+    * @param {number} tileWidth - The width of the tiles the map uses for calculations.
+    * @param {number} tileHeight - The height of the tiles the map uses for calculations.
+    * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
+    * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
+    */
+    create: function (name, width, height, tileWidth, tileHeight, group) {
+
+        if (group === undefined) { group = this.game.world; }
+
+        this.width = width;
+        this.height = height;
+
+        this.setTileSize(tileWidth, tileHeight);
+
+        this.layers.length = 0;
+
+        return this.createBlankLayer(name, width, height, tileWidth, tileHeight, group);
+
+    },
+
+    /**
+    * Sets the base tile size for the map.
+    *
+    * @method Phaser.Tilemap#setTileSize
+    * @param {number} tileWidth - The width of the tiles the map uses for calculations.
+    * @param {number} tileHeight - The height of the tiles the map uses for calculations.
+    */
+    setTileSize: function (tileWidth, tileHeight) {
+
+        this.tileWidth = tileWidth;
+        this.tileHeight = tileHeight;
+        this.widthInPixels = this.width * tileWidth;
+        this.heightInPixels = this.height * tileHeight;
+
+    },
+
+    /**
+    * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets.
+    * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor.
+    *
+    * @method Phaser.Tilemap#addTilesetImage
+    * @param {string} tileset - The name of the tileset as specified in the map data.
+    * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset.
+    *     If `undefined` or `null` it will look for an image with a key matching the tileset parameter.
+    *     You can also pass in a BitmapData which can be used instead of an Image.
+    * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32.
+    * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32.
+    * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value.
+    * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value.
+    * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here.
+    * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed.
+    */
+    addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) {
+
+        if (tileset === undefined) { return null; }
+        if (tileWidth === undefined) { tileWidth = this.tileWidth; }
+        if (tileHeight === undefined) { tileHeight = this.tileHeight; }
+        if (tileMargin === undefined) { tileMargin = 0; }
+        if (tileSpacing === undefined) { tileSpacing = 0; }
+        if (gid === undefined) { gid = 0; }
+
+        //  In-case we're working from a blank map
+        if (tileWidth === 0)
+        {
+            tileWidth = 32;
+        }
+
+        if (tileHeight === 0)
+        {
+            tileHeight = 32;
+        }
+
+        var img = null;
+
+        if (key === undefined || key === null)
+        {
+            key = tileset;
+        }
+
+        if (key instanceof Phaser.BitmapData)
+        {
+            img = key.canvas;
+        }
+        else
+        {
+            if (!this.game.cache.checkImageKey(key))
+            {
+                console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"');
+                return null;
+            }
+
+            img = this.game.cache.getImage(key);
+        }
+
+        var idx = this.getTilesetIndex(tileset);
+
+        if (idx === null && this.format === Phaser.Tilemap.TILED_JSON)
+        {
+            console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + key + '"');
+            return null;
+        }
+
+        if (this.tilesets[idx])
+        {
+            this.tilesets[idx].setImage(img);
+            return this.tilesets[idx];
+        }
+        else
+        {
+            var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {});
+
+            newSet.setImage(img);
+
+            this.tilesets.push(newSet);
+
+            var i = this.tilesets.length - 1;
+            var x = tileMargin;
+            var y = tileMargin;
+
+            var count = 0;
+            var countX = 0;
+            var countY = 0;
+
+            for (var t = gid; t < gid + newSet.total; t++)
+            {
+                this.tiles[t] = [x, y, i];
+
+                x += tileWidth + tileSpacing;
+
+                count++;
+
+                if (count === newSet.total)
+                {
+                    break;
+                }
+
+                countX++;
+
+                if (countX === newSet.columns)
+                {
+                    x = tileMargin;
+                    y += tileHeight + tileSpacing;
+
+                    countX = 0;
+                    countY++;
+
+                    if (countY === newSet.rows)
+                    {
+                        break;
+                    }
+                }
+            }
+
+            return newSet;
+
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Creates a Sprite for every object matching the given gid in the map data. You can optionally specify the group that the Sprite will be created in. If none is
+    * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to
+    * configure Sprite properties from within the map editor. For example giving an object a property of alpha: 0.5 in the map editor will duplicate that when the
+    * Sprite is created. You could also give it a value like: body.velocity.x: 100 to set it moving automatically.
+    *
+    * @method Phaser.Tilemap#createFromObjects
+    * @param {string} name - The name of the Object Group to create Sprites from.
+    * @param {number} gid - The layer array index value, or if a string is given the layer name within the map data.
+    * @param {string} key - The Game.cache key of the image that this Sprite will use.
+    * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
+    * @param {boolean} [exists=true] - The default exists state of the Sprite.
+    * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range.
+    * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
+    * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters.
+    * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height.
+    */
+    createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY) {
+
+        if (exists === undefined) { exists = true; }
+        if (autoCull === undefined) { autoCull = false; }
+        if (group === undefined) { group = this.game.world; }
+        if (CustomClass === undefined) { CustomClass = Phaser.Sprite; }
+        if (adjustY === undefined) { adjustY = true; }
+
+        if (!this.objects[name])
+        {
+            console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name);
+            return;
+        }
+
+        var sprite;
+        var found = false;
+
+        for (var i = 0, len = this.objects[name].length; i < len; i++)
+        {
+            if (typeof this.objects[name][i].gid !== 'undefined' && typeof gid === 'number')
+            {
+                if (this.objects[name][i].gid === gid)
+                {
+                    found = true;
+                }
+            }
+
+            if (typeof this.objects[name][i].id !== 'undefined' && typeof gid === 'number')
+            {
+                if (this.objects[name][i].id === gid)
+                {
+                    found = true;
+                }
+            }
+
+            if (typeof this.objects[name][i].name !== 'undefined' && typeof gid === 'string')
+            {
+                if (this.objects[name][i].name === gid)
+                {
+                    found = true;
+                }
+            }
+
+            if (found)
+            {
+                sprite = new CustomClass(this.game, this.objects[name][i].x, this.objects[name][i].y, key, frame);
+
+                sprite.name = this.objects[name][i].name;
+                sprite.visible = this.objects[name][i].visible;
+                sprite.autoCull = autoCull;
+                sprite.exists = exists;
+
+                sprite.width = this.objects[name][i].width;
+                sprite.height = this.objects[name][i].height;
+
+                if (this.objects[name][i].rotation)
+                {
+                    sprite.angle = this.objects[name][i].rotation;
+                }
+
+                if (adjustY)
+                {
+                    sprite.y -= sprite.height;
+                }
+
+                group.add(sprite);
+
+                for (var property in this.objects[name][i].properties)
+                {
+                    group.set(sprite, property, this.objects[name][i].properties[property], false, false, 0, true);
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Creates a Sprite for every object matching the given tile indexes in the map data.
+    * You can specify the group that the Sprite will be created in. If none is given it will be created in the World.
+    * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special 
+    * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted.
+    *
+    * @method Phaser.Tilemap#createFromTiles
+    * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from.
+    * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change.
+    * @param {string} key - The Game.cache key of the image that this Sprite will use.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
+    * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set.
+    * @return {integer} The number of Sprites that were created.
+    */
+    createFromTiles: function (tiles, replacements, key, layer, group, properties) {
+
+        if (typeof tiles === 'number') { tiles = [tiles]; }
+
+        if (replacements === undefined || replacements === null)
+        {
+            replacements = [];
+        }
+        else if (typeof replacements === 'number')
+        {
+            replacements = [replacements];
+        }
+
+        layer = this.getLayer(layer);
+
+        if (group === undefined) { group = this.game.world; }
+        if (properties === undefined) { properties = {}; }
+
+        if (properties.customClass === undefined)
+        {
+            properties.customClass = Phaser.Sprite;
+        }
+
+        if (properties.adjustY === undefined)
+        {
+            properties.adjustY = true;
+        }
+
+        var lw = this.layers[layer].width;
+        var lh = this.layers[layer].height;
+
+        this.copy(0, 0, lw, lh, layer);
+
+        if (this._results.length < 2)
+        {
+            return 0;
+        }
+
+        var total = 0;
+        var sprite;
+
+        for (var i = 1, len = this._results.length; i < len; i++)
+        {
+            if (tiles.indexOf(this._results[i].index) !== -1)
+            {
+                sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key);
+
+                for (var property in properties)
+                {
+                    sprite[property] = properties[property];
+                }
+
+                group.add(sprite);
+                total++;
+            }
+
+        }
+
+        if (replacements.length === 1)
+        {
+            //  Assume 1 replacement for all types of tile given
+            for (i = 0; i < tiles.length; i++)
+            {
+                this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer);
+            }
+        }
+        else if (replacements.length > 1)
+        {
+            //  Assume 1 for 1 mapping
+            for (i = 0; i < tiles.length; i++)
+            {
+                this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer);
+            }
+        }
+
+        return total;
+
+    },
+
+    /**
+    * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera.
+    * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name.
+    * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match.
+    * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer.
+    *
+    * @method Phaser.Tilemap#createLayer
+    * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents.
+    * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width.
+    * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height.
+    * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
+    * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly.
+    */
+    createLayer: function (layer, width, height, group) {
+
+        //  Add Buffer support for the left of the canvas
+
+        if (width === undefined) { width = this.game.width; }
+        if (height === undefined) { height = this.game.height; }
+        if (group === undefined) { group = this.game.world; }
+
+        var index = layer;
+
+        if (typeof layer === 'string')
+        {
+            index = this.getLayerIndex(layer);
+        }
+
+        if (index === null || index > this.layers.length)
+        {
+            console.warn('Tilemap.createLayer: Invalid layer ID given: ' + index);
+            return;
+        }
+
+        return group.add(new Phaser.TilemapLayer(this.game, this, index, width, height));
+
+    },
+
+    /**
+    * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera.
+    *
+    * @method Phaser.Tilemap#createBlankLayer
+    * @param {string} name - The name of this layer. Must be unique within the map.
+    * @param {number} width - The width of the layer in tiles.
+    * @param {number} height - The height of the layer in tiles.
+    * @param {number} tileWidth - The width of the tiles the layer uses for calculations.
+    * @param {number} tileHeight - The height of the tiles the layer uses for calculations.
+    * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
+    * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
+    */
+    createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) {
+
+        if (group === undefined) { group = this.game.world; }
+
+        if (this.getLayerIndex(name) !== null)
+        {
+            console.warn('Tilemap.createBlankLayer: Layer with matching name already exists');
+            return;
+        }
+
+        var layer = {
+
+            name: name,
+            x: 0,
+            y: 0,
+            width: width,
+            height: height,
+            widthInPixels: width * tileWidth,
+            heightInPixels: height * tileHeight,
+            alpha: 1,
+            visible: true,
+            properties: {},
+            indexes: [],
+            callbacks: [],
+            bodies: [],
+            data: null
+
+        };
+
+        var row;
+        var output = [];
+
+        for (var y = 0; y < height; y++)
+        {
+            row = [];
+
+            for (var x = 0; x < width; x++)
+            {
+                // row.push(null);
+                row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight));
+            }
+
+            output.push(row);
+        }
+
+        layer.data = output;
+
+        this.layers.push(layer);
+
+        this.currentLayer = this.layers.length - 1;
+
+        var w = layer.widthInPixels;
+        var h = layer.heightInPixels;
+
+        if (w > this.game.width)
+        {
+            w = this.game.width;
+        }
+
+        if (h > this.game.height)
+        {
+            h = this.game.height;
+        }
+
+        var output = new Phaser.TilemapLayer(this.game, this, this.layers.length - 1, w, h);
+        output.name = name;
+
+        return group.add(output);
+
+    },
+
+    /**
+    * Gets the layer index based on the layers name.
+    *
+    * @method Phaser.Tilemap#getIndex
+    * @protected
+    * @param {array} location - The local array to search.
+    * @param {string} name - The name of the array element to get.
+    * @return {number} The index of the element in the array, or null if not found.
+    */
+    getIndex: function (location, name) {
+
+        for (var i = 0; i < location.length; i++)
+        {
+            if (location[i].name === name)
+            {
+                return i;
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Gets the layer index based on its name.
+    *
+    * @method Phaser.Tilemap#getLayerIndex
+    * @param {string} name - The name of the layer to get.
+    * @return {number} The index of the layer in this tilemap, or null if not found.
+    */
+    getLayerIndex: function (name) {
+
+        return this.getIndex(this.layers, name);
+
+    },
+
+    /**
+    * Gets the tileset index based on its name.
+    *
+    * @method Phaser.Tilemap#getTilesetIndex
+    * @param {string} name - The name of the tileset to get.
+    * @return {number} The index of the tileset in this tilemap, or null if not found.
+    */
+    getTilesetIndex: function (name) {
+
+        return this.getIndex(this.tilesets, name);
+
+    },
+
+    /**
+    * Gets the image index based on its name.
+    *
+    * @method Phaser.Tilemap#getImageIndex
+    * @param {string} name - The name of the image to get.
+    * @return {number} The index of the image in this tilemap, or null if not found.
+    */
+    getImageIndex: function (name) {
+
+        return this.getIndex(this.images, name);
+
+    },
+
+    /**
+    * Gets the object index based on its name.
+    *
+    * @method Phaser.Tilemap#getObjectIndex
+    * @param {string} name - The name of the object to get.
+    * @return {number} The index of the object in this tilemap, or null if not found.
+    */
+    getObjectIndex: function (name) {
+
+        return this.getIndex(this.objects, name);
+
+    },
+
+    /**
+    * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index.
+    * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
+    * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
+    *
+    * @method Phaser.Tilemap#setTileIndexCallback
+    * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for.
+    * @param {function} callback - The callback that will be invoked when the tile is collided with.
+    * @param {object} callbackContext - The context under which the callback is called.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
+    */
+    setTileIndexCallback: function (indexes, callback, callbackContext, layer) {
+
+        layer = this.getLayer(layer);
+
+        if (typeof indexes === 'number')
+        {
+            //  This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much
+            //  less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit.
+            this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext };
+        }
+        else
+        {
+            for (var i = 0, len = indexes.length; i < len; i++)
+            {
+                this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext };
+            }
+        }
+
+    },
+
+    /**
+    * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area.
+    * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
+    * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
+    *
+    * @method Phaser.Tilemap#setTileLocationCallback
+    * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
+    * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
+    * @param {number} width - The width of the area to copy (given in tiles, not pixels)
+    * @param {number} height - The height of the area to copy (given in tiles, not pixels)
+    * @param {function} callback - The callback that will be invoked when the tile is collided with.
+    * @param {object} callbackContext - The context under which the callback is called.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
+    */
+    setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        for (var i = 1; i < this._results.length; i++)
+        {
+            this._results[i].setCollisionCallback(callback, callbackContext);
+        }
+
+    },
+
+    /**
+    * Sets collision the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [ 2, 3, 15, 20].
+    * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
+    *
+    * @method Phaser.Tilemap#setCollision
+    * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision.
+    * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
+    * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
+    */
+    setCollision: function (indexes, collides, layer, recalculate) {
+
+        if (collides === undefined) { collides = true; }
+        if (recalculate === undefined) { recalculate = true; }
+        
+        layer = this.getLayer(layer);
+
+        if (typeof indexes === 'number')
+        {
+            return this.setCollisionByIndex(indexes, collides, layer, true);
+        }
+        else if (Array.isArray(indexes))
+        {
+            //  Collide all of the IDs given in the indexes array
+            for (var i = 0; i < indexes.length; i++)
+            {
+                this.setCollisionByIndex(indexes[i], collides, layer, false);
+            }
+
+            if (recalculate)
+            {
+                //  Now re-calculate interesting faces
+                this.calculateFaces(layer);
+            }
+        }
+
+    },
+
+    /**
+    * Sets collision on a range of tiles where the tile IDs increment sequentially.
+    * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14.
+    * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
+    *
+    * @method Phaser.Tilemap#setCollisionBetween
+    * @param {number} start - The first index of the tile to be set for collision.
+    * @param {number} stop - The last index of the tile to be set for collision.
+    * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
+    * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
+    */
+    setCollisionBetween: function (start, stop, collides, layer, recalculate) {
+
+        if (collides === undefined) { collides = true; }
+        if (recalculate === undefined) { recalculate = true; }
+        
+        layer = this.getLayer(layer);
+
+        if (start > stop)
+        {
+            return;
+        }
+
+        for (var index = start; index <= stop; index++)
+        {
+            this.setCollisionByIndex(index, collides, layer, false);
+        }
+
+        if (recalculate)
+        {
+            //  Now re-calculate interesting faces
+            this.calculateFaces(layer);
+        }
+
+    },
+
+    /**
+    * Sets collision on all tiles in the given layer, except for the IDs of those in the given array.
+    * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
+    *
+    * @method Phaser.Tilemap#setCollisionByExclusion
+    * @param {array} indexes - An array of the tile IDs to not be counted for collision.
+    * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
+    * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
+    */
+    setCollisionByExclusion: function (indexes, collides, layer, recalculate) {
+
+        if (collides === undefined) { collides = true; }
+        if (recalculate === undefined) { recalculate = true; }
+        
+        layer = this.getLayer(layer);
+
+        //  Collide everything, except the IDs given in the indexes array
+        for (var i = 0, len = this.tiles.length; i < len; i++)
+        {
+            if (indexes.indexOf(i) === -1)
+            {
+                this.setCollisionByIndex(i, collides, layer, false);
+            }
+        }
+
+        if (recalculate)
+        {
+            //  Now re-calculate interesting faces
+            this.calculateFaces(layer);
+        }
+
+    },
+
+    /**
+    * Sets collision values on a tile in the set.
+    * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion.
+    *
+    * @method Phaser.Tilemap#setCollisionByIndex
+    * @protected
+    * @param {number} index - The index of the tile on the layer.
+    * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile.
+    * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer.
+    * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
+    */
+    setCollisionByIndex: function (index, collides, layer, recalculate) {
+
+        if (collides === undefined) { collides = true; }
+        if (layer === undefined) { layer = this.currentLayer; }
+        if (recalculate === undefined) { recalculate = true; }
+
+        if (collides)
+        {
+            this.collideIndexes.push(index);
+        }
+        else
+        {
+            var i = this.collideIndexes.indexOf(index);
+
+            if (i > -1)
+            {
+                this.collideIndexes.splice(i, 1);
+            }
+        }
+
+        for (var y = 0; y < this.layers[layer].height; y++)
+        {
+            for (var x = 0; x < this.layers[layer].width; x++)
+            {
+                var tile = this.layers[layer].data[y][x];
+
+                if (tile && tile.index === index)
+                {
+                    if (collides)
+                    {
+                        tile.setCollision(true, true, true, true);
+                    }
+                    else
+                    {
+                        tile.resetCollision();
+                    }
+
+                    tile.faceTop = collides;
+                    tile.faceBottom = collides;
+                    tile.faceLeft = collides;
+                    tile.faceRight = collides;
+                }
+            }
+        }
+
+        if (recalculate)
+        {
+            //  Now re-calculate interesting faces
+            this.calculateFaces(layer);
+        }
+
+        return layer;
+
+    },
+
+    /**
+    * Gets the TilemapLayer index as used in the setCollision calls.
+    *
+    * @method Phaser.Tilemap#getLayer
+    * @protected
+    * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer.
+    * @return {number} The TilemapLayer index.
+    */
+    getLayer: function (layer) {
+
+        if (layer === undefined)
+        {
+            layer = this.currentLayer;
+        }
+        else if (typeof layer === 'string')
+        {
+            layer = this.getLayerIndex(layer);
+        }
+        else if (layer instanceof Phaser.TilemapLayer)
+        {
+            layer = layer.index;
+        }
+
+        return layer;
+
+    },
+
+    /**
+    * Turn off/on the recalculation of faces for tile or collision updates. 
+    * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers.
+    *
+    * @method Phaser.Tilemap#setPreventRecalculate
+    * @param {boolean} value - If true it will put the recalculation on hold.
+    */
+    setPreventRecalculate: function (value) {
+
+        if (value === true && this.preventingRecalculate !== true)
+        {
+            this.preventingRecalculate = true;
+            this.needToRecalculate = {};
+        }
+
+        if (value === false && this.preventingRecalculate === true)
+        {
+            this.preventingRecalculate = false;
+
+            for (var i in this.needToRecalculate)
+            {
+                this.calculateFaces(i);
+            }
+
+            this.needToRecalculate = false;
+        }
+
+    },
+
+    /**
+    * Internal function.
+    *
+    * @method Phaser.Tilemap#calculateFaces
+    * @protected
+    * @param {number} layer - The index of the TilemapLayer to operate on.
+    */
+    calculateFaces: function (layer) {
+
+        if (this.preventingRecalculate)
+        {
+            this.needToRecalculate[layer] = true;
+            return;
+        }
+        
+        var above = null;
+        var below = null;
+        var left = null;
+        var right = null;
+
+        for (var y = 0, h = this.layers[layer].height; y < h; y++)
+        {
+            for (var x = 0, w = this.layers[layer].width; x < w; x++)
+            {
+                var tile = this.layers[layer].data[y][x];
+
+                if (tile)
+                {
+                    above = this.getTileAbove(layer, x, y);
+                    below = this.getTileBelow(layer, x, y);
+                    left = this.getTileLeft(layer, x, y);
+                    right = this.getTileRight(layer, x, y);
+
+                    if (tile.collides)
+                    {
+                        tile.faceTop = true;
+                        tile.faceBottom = true;
+                        tile.faceLeft = true;
+                        tile.faceRight = true;
+                    }
+
+                    if (above && above.collides)
+                    {
+                        //  There is a tile above this one that also collides, so the top of this tile is no longer interesting
+                        tile.faceTop = false;
+                    }
+
+                    if (below && below.collides)
+                    {
+                        //  There is a tile below this one that also collides, so the bottom of this tile is no longer interesting
+                        tile.faceBottom = false;
+                    }
+
+                    if (left && left.collides)
+                    {
+                        //  There is a tile left this one that also collides, so the left of this tile is no longer interesting
+                        tile.faceLeft = false;
+                    }
+
+                    if (right && right.collides)
+                    {
+                        //  There is a tile right this one that also collides, so the right of this tile is no longer interesting
+                        tile.faceRight = false;
+                    }
+                }
+            }
+        }
+
+    },
+
+    /**
+    * Gets the tile above the tile coordinates given.
+    * Mostly used as an internal function by calculateFaces.
+    *
+    * @method Phaser.Tilemap#getTileAbove
+    * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
+    * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
+    * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
+    */
+    getTileAbove: function (layer, x, y) {
+
+        if (y > 0)
+        {
+            return this.layers[layer].data[y - 1][x];
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Gets the tile below the tile coordinates given.
+    * Mostly used as an internal function by calculateFaces.
+    *
+    * @method Phaser.Tilemap#getTileBelow
+    * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
+    * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
+    * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
+    */
+    getTileBelow: function (layer, x, y) {
+
+        if (y < this.layers[layer].height - 1)
+        {
+            return this.layers[layer].data[y + 1][x];
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Gets the tile to the left of the tile coordinates given.
+    * Mostly used as an internal function by calculateFaces.
+    *
+    * @method Phaser.Tilemap#getTileLeft
+    * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
+    * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
+    * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
+    */
+    getTileLeft: function (layer, x, y) {
+
+        if (x > 0)
+        {
+            return this.layers[layer].data[y][x - 1];
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Gets the tile to the right of the tile coordinates given.
+    * Mostly used as an internal function by calculateFaces.
+    *
+    * @method Phaser.Tilemap#getTileRight
+    * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
+    * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
+    * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
+    */
+    getTileRight: function (layer, x, y) {
+
+        if (x < this.layers[layer].width - 1)
+        {
+            return this.layers[layer].data[y][x + 1];
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Sets the current layer to the given index.
+    *
+    * @method Phaser.Tilemap#setLayer
+    * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
+    */
+    setLayer: function (layer) {
+
+        layer = this.getLayer(layer);
+
+        if (this.layers[layer])
+        {
+            this.currentLayer = layer;
+        }
+
+    },
+
+    /**
+    * Checks if there is a tile at the given location.
+    *
+    * @method Phaser.Tilemap#hasTile
+    * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels)
+    * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels)
+    * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
+    * @return {boolean} True if there is a tile at the given location, otherwise false.
+    */
+    hasTile: function (x, y, layer) {
+
+        layer = this.getLayer(layer);
+
+        return (this.layers[layer].data[y][x].index > -1);
+
+    },
+
+    /**
+    * Removes the tile located at the given coordinates and updates the collision data.
+    *
+    * @method Phaser.Tilemap#removeTile
+    * @param {number} x - X position to place the tile (given in tile units, not pixels)
+    * @param {number} y - Y position to place the tile (given in tile units, not pixels)
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
+    * @return {Phaser.Tile} The Tile object that was removed from this map.
+    */
+    removeTile: function (x, y, layer) {
+
+        layer = this.getLayer(layer);
+
+        if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
+        {
+            if (this.hasTile(x, y, layer))
+            {
+                var tile = this.layers[layer].data[y][x];
+
+                this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight);
+
+                this.layers[layer].dirty = true;
+
+                this.calculateFaces(layer);
+
+                return tile;
+            }
+        }
+
+    },
+
+    /**
+    * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values.
+    *
+    * @method Phaser.Tilemap#removeTileWorldXY
+    * @param {number} x - X position to insert the tile (given in pixels)
+    * @param {number} y - Y position to insert the tile (given in pixels)
+    * @param {number} tileWidth - The width of the tile in pixels.
+    * @param {number} tileHeight - The height of the tile in pixels.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
+    * @return {Phaser.Tile} The Tile object that was removed from this map.
+    */
+    removeTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
+
+        layer = this.getLayer(layer);
+
+        x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
+        y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
+
+        return this.removeTile(x, y, layer);
+
+    },
+
+    /**
+    * Puts a tile of the given index value at the coordinate specified.
+    * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead.
+    *
+    * @method Phaser.Tilemap#putTile
+    * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map.
+    * @param {number} x - X position to place the tile (given in tile units, not pixels)
+    * @param {number} y - Y position to place the tile (given in tile units, not pixels)
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
+    * @return {Phaser.Tile} The Tile object that was created or added to this map.
+    */
+    putTile: function (tile, x, y, layer) {
+
+        if (tile === null)
+        {
+            return this.removeTile(x, y, layer);
+        }
+
+        layer = this.getLayer(layer);
+
+        if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
+        {
+            var index;
+
+            if (tile instanceof Phaser.Tile)
+            {
+                index = tile.index;
+
+                if (this.hasTile(x, y, layer))
+                {
+                    this.layers[layer].data[y][x].copy(tile);
+                }
+                else
+                {
+                    this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height);
+                }
+            }
+            else
+            {
+                index = tile;
+
+                if (this.hasTile(x, y, layer))
+                {
+                    this.layers[layer].data[y][x].index = index;
+                }
+                else
+                {
+                    this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight);
+                }
+            }
+
+            if (this.collideIndexes.indexOf(index) > -1)
+            {
+                this.layers[layer].data[y][x].setCollision(true, true, true, true);
+            }
+            else
+            {
+                this.layers[layer].data[y][x].resetCollision();
+            }
+
+            this.layers[layer].dirty = true;
+
+            this.calculateFaces(layer);
+
+            return this.layers[layer].data[y][x];
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Puts a tile into the Tilemap layer. The coordinates are given in pixel values.
+    *
+    * @method Phaser.Tilemap#putTileWorldXY
+    * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object.
+    * @param {number} x - X position to insert the tile (given in pixels)
+    * @param {number} y - Y position to insert the tile (given in pixels)
+    * @param {number} tileWidth - The width of the tile in pixels.
+    * @param {number} tileHeight - The height of the tile in pixels.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
+    * @return {Phaser.Tile} The Tile object that was created or added to this map.
+    */
+    putTileWorldXY: function (tile, x, y, tileWidth, tileHeight, layer) {
+
+        layer = this.getLayer(layer);
+
+        x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
+        y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
+
+        return this.putTile(tile, x, y, layer);
+
+    },
+
+    /**
+    * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object.
+    * If no match is found it returns null.
+    * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column.
+    * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left.
+    *
+    * @method Phaser.Tilemap#searchTileIndex
+    * @param {number} index - The tile index value to search for.
+    * @param {number} [skip=0] - The number of times to skip a matching tile before returning.
+    * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
+    * @return {Phaser.Tile} The first (or n skipped) tile with the matching index.
+    */
+    searchTileIndex: function (index, skip, reverse, layer) {
+
+        if (skip === undefined) { skip = 0; }
+        if (reverse === undefined) { reverse = false; }
+
+        layer = this.getLayer(layer);
+
+        var c = 0;
+
+        if (reverse)
+        {
+            for (var y = this.layers[layer].height - 1; y >= 0; y--)
+            {
+                for (var x = this.layers[layer].width - 1; x >= 0; x--)
+                {
+                    if (this.layers[layer].data[y][x].index === index)
+                    {
+                        if (c === skip)
+                        {
+                            return this.layers[layer].data[y][x];
+                        }
+                        else
+                        {
+                            c++;
+                        }
+                    }
+                }
+            }
+        }
+        else
+        {
+            for (var y = 0; y < this.layers[layer].height; y++)
+            {
+                for (var x = 0; x < this.layers[layer].width; x++)
+                {
+                    if (this.layers[layer].data[y][x].index === index)
+                    {
+                        if (c === skip)
+                        {
+                            return this.layers[layer].data[y][x];
+                        }
+                        else
+                        {
+                            c++;
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+
+    },
+
+    /**
+    * Gets a tile from the Tilemap Layer. The coordinates are given in tile values.
+    *
+    * @method Phaser.Tilemap#getTile
+    * @param {number} x - X position to get the tile from (given in tile units, not pixels)
+    * @param {number} y - Y position to get the tile from (given in tile units, not pixels)
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
+    * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
+    * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid.
+    */
+    getTile: function (x, y, layer, nonNull) {
+
+        if (nonNull === undefined) { nonNull = false; }
+
+        layer = this.getLayer(layer);
+
+        if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
+        {
+            if (this.layers[layer].data[y][x].index === -1)
+            {
+                if (nonNull)
+                {
+                    return this.layers[layer].data[y][x];
+                }
+                else
+                {
+                    return null;
+                }
+            }
+            else
+            {
+                return this.layers[layer].data[y][x];
+            }
+        }
+        else
+        {
+            return null;
+        }
+
+    },
+
+    /**
+    * Gets a tile from the Tilemap layer. The coordinates are given in pixel values.
+    *
+    * @method Phaser.Tilemap#getTileWorldXY
+    * @param {number} x - X position to get the tile from (given in pixels)
+    * @param {number} y - Y position to get the tile from (given in pixels)
+    * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used.
+    * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
+    * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
+    * @return {Phaser.Tile} The tile at the given coordinates.
+    */
+    getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) {
+
+        if (tileWidth === undefined) { tileWidth = this.tileWidth; }
+        if (tileHeight === undefined) { tileHeight = this.tileHeight; }
+
+        layer = this.getLayer(layer);
+
+        x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
+        y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
+
+        return this.getTile(x, y, layer, nonNull);
+
+    },
+
+    /**
+    * Copies all of the tiles in the given rectangular block into the tilemap data buffer.
+    *
+    * @method Phaser.Tilemap#copy
+    * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels)
+    * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels)
+    * @param {integer} width - The width of the area to copy (given in tiles, not pixels)
+    * @param {integer} height - The height of the area to copy (given in tiles, not pixels)
+    * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from.
+    * @return {array} An array of the tiles that were copied.
+    */
+    copy: function (x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        if (!this.layers[layer])
+        {
+            this._results.length = 0;
+            return;
+        }
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+        if (width === undefined) { width = this.layers[layer].width; }
+        if (height === undefined) { height = this.layers[layer].height; }
+        
+        if (x < 0)
+        {
+            x = 0;
+        }
+
+        if (y < 0)
+        {
+            y = 0;
+        }
+
+        if (width > this.layers[layer].width)
+        {
+            width = this.layers[layer].width;
+        }
+
+        if (height > this.layers[layer].height)
+        {
+            height = this.layers[layer].height;
+        }
+
+        this._results.length = 0;
+
+        this._results.push({ x: x, y: y, width: width, height: height, layer: layer });
+
+        for (var ty = y; ty < y + height; ty++)
+        {
+            for (var tx = x; tx < x + width; tx++)
+            {
+                this._results.push(this.layers[layer].data[ty][tx]);
+            }
+        }
+
+        return this._results;
+
+    },
+
+    /**
+    * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy.
+    *
+    * @method Phaser.Tilemap#paste
+    * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels)
+    * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels)
+    * @param {array} tileblock - The block of tiles to paste.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into.
+    */
+    paste: function (x, y, tileblock, layer) {
+
+        if (x === undefined) { x = 0; }
+        if (y === undefined) { y = 0; }
+
+        layer = this.getLayer(layer);
+
+        if (!tileblock || tileblock.length < 2)
+        {
+            return;
+        }
+
+        //  Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste
+        var diffX = x - tileblock[1].x;
+        var diffY = y - tileblock[1].y;
+
+        for (var i = 1; i < tileblock.length; i++)
+        {
+            this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]);
+        }
+
+		this.layers[layer].dirty = true;
+        this.calculateFaces(layer);
+
+    },
+
+    /**
+    * Scans the given area for tiles with an index matching tileA and swaps them with tileB.
+    *
+    * @method Phaser.Tilemap#swap
+    * @param {number} tileA - First tile index.
+    * @param {number} tileB - Second tile index.
+    * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} width - The width in tiles of the area to operate on.
+    * @param {number} height - The height in tiles of the area to operate on.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    */
+    swap: function (tileA, tileB, x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        this._tempA = tileA;
+        this._tempB = tileB;
+
+        this._results.forEach(this.swapHandler, this);
+
+        this.paste(x, y, this._results, layer);
+
+    },
+
+    /**
+    * Internal function that handles the swapping of tiles.
+    *
+    * @method Phaser.Tilemap#swapHandler
+    * @private
+    * @param {number} value
+    */
+    swapHandler: function (value) {
+
+        if (value.index === this._tempA)
+        {
+            //  Swap A with B
+            value.index = this._tempB;
+        }
+        else if (value.index === this._tempB)
+        {
+            //  Swap B with A
+            value.index = this._tempA;
+        }
+
+    },
+
+    /**
+    * For each tile in the given area defined by x/y and width/height run the given callback.
+    *
+    * @method Phaser.Tilemap#forEach
+    * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
+    * @param {number} context - The context under which the callback should be run.
+    * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} width - The width in tiles of the area to operate on.
+    * @param {number} height - The height in tiles of the area to operate on.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    */
+    forEach: function (callback, context, x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        this._results.forEach(callback, context);
+
+        this.paste(x, y, this._results, layer);
+
+    },
+
+    /**
+    * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`.
+    *
+    * @method Phaser.Tilemap#replace
+    * @param {number} source - The tile index value to scan for.
+    * @param {number} dest - The tile index value to replace found tiles with.
+    * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} width - The width in tiles of the area to operate on.
+    * @param {number} height - The height in tiles of the area to operate on.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    */
+    replace: function (source, dest, x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        for (var i = 1; i < this._results.length; i++)
+        {
+            if (this._results[i].index === source)
+            {
+                this._results[i].index = dest;
+            }
+        }
+
+        this.paste(x, y, this._results, layer);
+
+    },
+
+    /**
+    * Randomises a set of tiles in a given area.
+    *
+    * @method Phaser.Tilemap#random
+    * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} width - The width in tiles of the area to operate on.
+    * @param {number} height - The height in tiles of the area to operate on.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    */
+    random: function (x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        var indexes = [];
+
+        for (var t = 1; t < this._results.length; t++)
+        {
+            if (this._results[t].index)
+            {
+                var idx = this._results[t].index;
+
+                if (indexes.indexOf(idx) === -1)
+                {
+                    indexes.push(idx);
+                }
+            }
+        }
+
+        for (var i = 1; i < this._results.length; i++)
+        {
+            this._results[i].index = this.game.rnd.pick(indexes);
+        }
+
+        this.paste(x, y, this._results, layer);
+
+    },
+
+    /**
+    * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed!
+    *
+    * @method Phaser.Tilemap#shuffle
+    * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} width - The width in tiles of the area to operate on.
+    * @param {number} height - The height in tiles of the area to operate on.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    */
+    shuffle: function (x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        var indexes = [];
+
+        for (var t = 1; t < this._results.length; t++)
+        {
+            if (this._results[t].index)
+            {
+                indexes.push(this._results[t].index);
+            }
+        }
+
+        Phaser.Utils.shuffle(indexes);
+
+        for (var i = 1; i < this._results.length; i++)
+        {
+            this._results[i].index = indexes[i - 1];
+        }
+
+        this.paste(x, y, this._results, layer);
+
+    },
+
+    /**
+    * Fills the given area with the specified tile.
+    *
+    * @method Phaser.Tilemap#fill
+    * @param {number} index - The index of the tile that the area will be filled with.
+    * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
+    * @param {number} width - The width in tiles of the area to operate on.
+    * @param {number} height - The height in tiles of the area to operate on.
+    * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
+    */
+    fill: function (index, x, y, width, height, layer) {
+
+        layer = this.getLayer(layer);
+
+        this.copy(x, y, width, height, layer);
+
+        if (this._results.length < 2)
+        {
+            return;
+        }
+
+        for (var i = 1; i < this._results.length; i++)
+        {
+            this._results[i].index = index;
+        }
+
+        this.paste(x, y, this._results, layer);
+
+    },
+
+    /**
+    * Removes all layers from this tile map.
+    *
+    * @method Phaser.Tilemap#removeAllLayers
+    */
+    removeAllLayers: function () {
+
+        this.layers.length = 0;
+        this.currentLayer = 0;
+
+    },
+
+    /**
+    * Dumps the tilemap data out to the console.
+    *
+    * @method Phaser.Tilemap#dump
+    */
+    dump: function () {
+
+        var txt = '';
+        var args = [''];
+
+        for (var y = 0; y < this.layers[this.currentLayer].height; y++)
+        {
+            for (var x = 0; x < this.layers[this.currentLayer].width; x++)
+            {
+                txt += "%c  ";
+
+                if (this.layers[this.currentLayer].data[y][x] > 1)
+                {
+                    if (this.debugMap[this.layers[this.currentLayer].data[y][x]])
+                    {
+                        args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]);
+                    }
+                    else
+                    {
+                        args.push("background: #ffffff");
+                    }
+                }
+                else
+                {
+                    args.push("background: rgb(0, 0, 0)");
+                }
+            }
+
+            txt += "\n";
+        }
+
+        args[0] = txt;
+        console.log.apply(console, args);
+
+    },
+
+    /**
+    * Removes all layer data from this tile map and nulls the game reference.
+    * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them.
+    *
+    * @method Phaser.Tilemap#destroy
+    */
+    destroy: function () {
+
+        this.removeAllLayers();
+        this.data = [];
+        this.game = null;
+
+    }
+
+};
+
+Phaser.Tilemap.prototype.constructor = Phaser.Tilemap;
+
+/**
+* @name Phaser.Tilemap#layer
+* @property {number|string|Phaser.TilemapLayer} layer - The current layer object.
+*/
+Object.defineProperty(Phaser.Tilemap.prototype, "layer", {
+
+    get: function () {
+
+        return this.layers[this.currentLayer];
+
+    },
+
+    set: function (value) {
+
+        if (value !== this.currentLayer)
+        {
+            this.setLayer(value);
+        }
+
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap.
+*
+* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc.
+*
+* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior.
+*
+* @class Phaser.TilemapLayer
+* @extends Phaser.Sprite
+* @constructor
+* @param {Phaser.Game} game - Game reference to the currently running game.
+* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
+* @param {integer} index - The index of the TileLayer to render within the Tilemap.
+* @param {integer} width - Width of the renderable area of the layer (in pixels).
+* @param {integer} height - Height of the renderable area of the layer (in pixels).
+*/
+Phaser.TilemapLayer = function (game, tilemap, index, width, height) {
+
+    width |= 0;
+    height |= 0;
+
+    Phaser.Sprite.call(this, game, 0, 0);
+
+    /**
+    * The Tilemap to which this layer is bound.
+    * @property {Phaser.Tilemap} map
+    * @protected
+    * @readonly
+    */
+    this.map = tilemap;
+
+    /**
+    * The index of this layer within the Tilemap.
+    * @property {number} index
+    * @protected
+    * @readonly
+    */
+    this.index = index;
+
+    /**
+    * The layer object within the Tilemap that this layer represents.
+    * @property {object} layer
+    * @protected
+    * @readonly
+    */
+    this.layer = tilemap.layers[index];
+
+    /**
+    * The canvas to which this TilemapLayer draws.
+    * @property {HTMLCanvasElement} canvas
+    * @protected
+    */
+    this.canvas = Phaser.Canvas.create(width, height);
+
+    /**
+    * The 2d context of the canvas.
+    * @property {CanvasRenderingContext2D} context
+    * @private
+    */
+    this.context = this.canvas.getContext('2d');
+
+    this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas)));
+
+    /**
+    * The const type of this object.
+    * @property {number} type
+    * @readonly
+    * @protected
+    * @default Phaser.TILEMAPLAYER
+    */
+    this.type = Phaser.TILEMAPLAYER;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.TILEMAPLAYER;
+
+    /**
+    * Settings that control standard (non-diagnostic) rendering.
+    *
+    * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view.
+    *     This can greatly improve scrolling rendering performance, especially when there are many small tiles.
+    *     It should only be disabled in rare cases.
+    *
+    * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas.
+    *     Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior
+    *     in some browsers, notably Safari. 
+    *
+    * @default
+    */
+    this.renderSettings = {
+        enableScrollDelta: false,
+        overdrawRatio: 0.20,
+        copyCanvas: null
+    };
+
+    /**
+    * Enable an additional "debug rendering" pass to display collision information.
+    *
+    * @property {boolean} debug
+    * @default
+    */
+    this.debug = false;
+
+    /**
+    * @property {boolean} exists - Controls if the core game loop and physics update this game object or not.
+    */
+    this.exists = true;
+
+    /**
+    * Settings used for debugging and diagnostics.
+    *
+    * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._
+    *
+    * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._
+    *
+    * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed.
+    *
+    * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer.
+    *
+    * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges.
+    *
+    * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill.
+    *
+    */
+    this.debugSettings = {
+
+        missingImageFill: 'rgb(255,255,255)',
+        debuggedTileOverfill: 'rgba(0,255,0,0.4)',
+
+        forceFullRedraw: true,
+
+        debugAlpha: 0.5,
+        facingEdgeStroke: 'rgba(0,255,0,1)',
+        collidingTileOverfill: 'rgba(0,255,0,0.2)'
+
+    };
+
+    /**
+    * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do).
+    * @property {number} scrollFactorX
+    * @public
+    * @default
+    */
+    this.scrollFactorX = 1;
+
+    /**
+    * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do)
+    * @property {number} scrollFactorY
+    * @public
+    * @default
+    */
+    this.scrollFactorY = 1;
+
+    /**
+    * If true tiles will be force rendered, even if such is not believed to be required.
+    * @property {boolean} dirty
+    * @protected
+    */
+    this.dirty = true;
+
+    /**
+    * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance.
+    * @property {integer} rayStepRate
+    * @default
+    */
+    this.rayStepRate = 4;
+
+    /**
+    * Flag controlling if the layer tiles wrap at the edges.
+    * @property {boolean} _wrap
+    * @private
+    */
+    this._wrap = false;
+
+    /**
+    * Local map data and calculation cache.
+    * @property {object} _mc
+    * @private
+    */
+    this._mc = {
+
+        // Used to bypass rendering without reliance on `dirty` and detect changes.
+        scrollX: 0,
+        scrollY: 0,
+        renderWidth: 0,
+        renderHeight: 0,
+
+        tileWidth: tilemap.tileWidth,
+        tileHeight: tilemap.tileHeight,
+
+        // Collision width/height (pixels)
+        // What purpose do these have? Most things use tile width/height directly.
+        // This also only extends collisions right and down.       
+        cw: tilemap.tileWidth,
+        ch: tilemap.tileHeight,
+
+        // Cached tilesets from index -> Tileset
+        tilesets: []
+
+    };
+
+    /**
+    * The current canvas left after scroll is applied.
+    * @property {number} _scrollX
+    * @private
+    */
+    this._scrollX = 0;
+
+    /**
+    * The current canvas top after scroll is applied.
+    * @propety {number} _scrollY
+    * @private
+    */
+    this._scrollY = 0;
+
+    /**
+    * Used for caching the tiles / array of tiles.
+    * @property {Phaser.Tile[]} _results
+    * @private
+    */
+    this._results = [];
+
+    if (!game.device.canvasBitBltShift)
+    {
+        this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas();
+    }
+
+    this.fixedToCamera = true;
+
+};
+
+Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype);
+Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer;
+
+Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
+
+/**
+* The shared double-copy canvas, created as needed.
+*
+* @private
+* @static
+*/
+Phaser.TilemapLayer.sharedCopyCanvas = null;
+
+/**
+* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers.
+*
+* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate.
+*
+* @protected
+* @static
+*/
+Phaser.TilemapLayer.ensureSharedCopyCanvas = function () {
+
+    if (!this.sharedCopyCanvas)
+    {
+        this.sharedCopyCanvas = Phaser.Canvas.create(2, 2);
+    }
+
+    return this.sharedCopyCanvas;
+
+};
+
+/**
+* Automatically called by World.preUpdate.
+*
+* @method Phaser.Image#preUpdate
+* @memberof Phaser.Image
+*/
+Phaser.TilemapLayer.prototype.preUpdate = function() {
+
+    return this.preUpdateCore();
+
+};
+
+/**
+* Automatically called by World.postUpdate. Handles cache updates.
+*
+* @method Phaser.TilemapLayer#postUpdate
+* @protected
+*/
+Phaser.TilemapLayer.prototype.postUpdate = function () {
+
+    Phaser.Component.FixedToCamera.postUpdate.call(this);
+
+    //  Stops you being able to auto-scroll the camera if it's not following a sprite
+    var camera = this.game.camera;
+
+    this.scrollX = camera.x * this.scrollFactorX / this.scale.x;
+    this.scrollY = camera.y * this.scrollFactorY / this.scale.y;
+
+    this.render();
+
+};
+
+/**
+* Resizes the internal canvas and texture frame used by this TilemapLayer.
+*
+* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully
+* selected times.
+*
+* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not
+* modified either. You will have to handle both of these things from your game code if required.
+* 
+* @method Phaser.TilemapLayer#resize
+* @param {number} width - The new width of the TilemapLayer
+* @param {number} height - The new height of the TilemapLayer
+*/
+Phaser.TilemapLayer.prototype.resize = function (width, height) {
+
+    this.canvas.width = width;
+    this.canvas.height = height;
+
+    this.texture.frame.resize(width, height);
+
+    this.texture.width = width;
+    this.texture.height = height;
+
+    this.texture.crop.width = width;
+    this.texture.crop.height = height;
+
+    this.texture.baseTexture.width = width;
+    this.texture.baseTexture.height = height;
+
+    this.texture.baseTexture.dirty();
+    this.texture.requiresUpdate = true;
+
+    this.texture._updateUvs();
+
+    this.dirty = true;
+
+};
+
+/**
+* Sets the world size to match the size of this layer.
+*
+* @method Phaser.TilemapLayer#resizeWorld
+* @public
+*/
+Phaser.TilemapLayer.prototype.resizeWorld = function () {
+
+    this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y);
+
+};
+
+/**
+* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space.
+*
+* @method Phaser.TilemapLayer#_fixX
+* @private
+* @param {number} x - x coordinate in camera space
+* @return {number} x coordinate in scrollFactor-adjusted dimensions
+*/
+Phaser.TilemapLayer.prototype._fixX = function (x) {
+
+    if (x < 0)
+    {
+        x = 0;
+    }
+
+    if (this.scrollFactorX === 1)
+    {
+        return x;
+    }
+
+    return this._scrollX + (x - (this._scrollX / this.scrollFactorX));
+
+};
+
+/**
+* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space.
+*
+* @method Phaser.TilemapLayer#_unfixX
+* @private
+* @param {number} x - x coordinate in scrollFactor-adjusted dimensions
+* @return {number} x coordinate in camera space
+*/
+Phaser.TilemapLayer.prototype._unfixX = function (x) {
+
+    if (this.scrollFactorX === 1)
+    {
+        return x;
+    }
+
+    return (this._scrollX / this.scrollFactorX) + (x - this._scrollX);
+
+};
+
+/**
+* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space.
+*
+* @method Phaser.TilemapLayer#_fixY
+* @private
+* @param {number} y - y coordinate in camera space
+* @return {number} y coordinate in scrollFactor-adjusted dimensions
+*/
+Phaser.TilemapLayer.prototype._fixY = function (y) {
+
+    if (y < 0)
+    {
+        y = 0;
+    }
+
+    if (this.scrollFactorY === 1)
+    {
+        return y;
+    }
+
+    return this._scrollY + (y - (this._scrollY / this.scrollFactorY));
+
+};
+
+/**
+* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space.
+*
+* @method Phaser.TilemapLayer#_unfixY
+* @private
+* @param {number} y - y coordinate in scrollFactor-adjusted dimensions
+* @return {number} y coordinate in camera space
+*/
+Phaser.TilemapLayer.prototype._unfixY = function (y) {
+
+    if (this.scrollFactorY === 1)
+    {
+        return y;
+    }
+
+    return (this._scrollY / this.scrollFactorY) + (y - this._scrollY);
+
+};
+
+/**
+* Convert a pixel value to a tile coordinate.
+*
+* @method Phaser.TilemapLayer#getTileX
+* @public
+* @param {number} x - X position of the point in target tile (in pixels).
+* @return {integer} The X map location of the tile.
+*/
+Phaser.TilemapLayer.prototype.getTileX = function (x) {
+
+    // var tileWidth = this.tileWidth * this.scale.x;
+    return Math.floor(this._fixX(x) / this._mc.tileWidth);
+
+};
+
+/**
+* Convert a pixel value to a tile coordinate.
+*
+* @method Phaser.TilemapLayer#getTileY
+* @public
+* @param {number} y - Y position of the point in target tile (in pixels).
+* @return {integer} The Y map location of the tile.
+*/
+Phaser.TilemapLayer.prototype.getTileY = function (y) {
+
+    // var tileHeight = this.tileHeight * this.scale.y;
+    return Math.floor(this._fixY(y) / this._mc.tileHeight);
+
+};
+
+/**
+* Convert a pixel coordinate to a tile coordinate.
+*
+* @method Phaser.TilemapLayer#getTileXY
+* @public
+* @param {number} x - X position of the point in target tile (in pixels).
+* @param {number} y - Y position of the point in target tile (in pixels).
+* @param {(Phaser.Point|object)} point - The Point/object to update.
+* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set.
+*/
+Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) {
+
+    point.x = this.getTileX(x);
+    point.y = this.getTileY(y);
+
+    return point;
+
+};
+
+/**
+* Gets all tiles that intersect with the given line.
+*
+* @method Phaser.TilemapLayer#getRayCastTiles
+* @public
+* @param {Phaser.Line} line - The line used to determine which tiles to return.
+* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`.
+* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces.
+* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces.
+* @return {Phaser.Tile[]} An array of Phaser.Tiles.
+*/
+Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) {
+
+    if (!stepRate) { stepRate = this.rayStepRate; }
+    if (collides === undefined) { collides = false; }
+    if (interestingFace === undefined) { interestingFace = false; }
+
+    //  First get all tiles that touch the bounds of the line
+    var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace);
+
+    if (tiles.length === 0)
+    {
+        return [];
+    }
+
+    //  Now we only want the tiles that intersect with the points on this line
+    var coords = line.coordinatesOnLine(stepRate);
+    var results = [];
+
+    for (var i = 0; i < tiles.length; i++)
+    {
+        for (var t = 0; t < coords.length; t++)
+        {
+            var tile = tiles[i];
+            var coord = coords[t];
+            if (tile.containsPoint(coord[0], coord[1]))
+            {
+                results.push(tile);
+                break;
+            }
+        }
+    }
+
+    return results;
+
+};
+
+/**
+* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles.
+*
+* @method Phaser.TilemapLayer#getTiles
+* @public
+* @param {number} x - X position of the top left corner (in pixels).
+* @param {number} y - Y position of the top left corner (in pixels).
+* @param {number} width - Width of the area to get (in pixels).
+* @param {number} height - Height of the area to get (in pixels).
+* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces.
+* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces.
+* @return {array<Phaser.Tile>} An array of Tiles.
+*/
+Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) {
+
+    //  Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
+    if (collides === undefined) { collides = false; }
+    if (interestingFace === undefined) { interestingFace = false; }
+
+    var fetchAll = !(collides || interestingFace);
+
+    //  Adjust the x,y coordinates for scrollFactor
+    x = this._fixX(x);
+    y = this._fixY(y);
+
+    //  Convert the pixel values into tile coordinates
+    var tx = Math.floor(x / (this._mc.cw * this.scale.x));
+    var ty = Math.floor(y / (this._mc.ch * this.scale.y));
+    //  Don't just use ceil(width/cw) to allow account for x/y diff within cell
+    var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx;
+    var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty;
+
+    while (this._results.length)
+    {
+        this._results.pop();
+    }
+
+    for (var wy = ty; wy < ty + th; wy++)
+    {
+        for (var wx = tx; wx < tx + tw; wx++)
+        {
+            var row = this.layer.data[wy];
+
+            if (row && row[wx])
+            {
+                if (fetchAll || row[wx].isInteresting(collides, interestingFace))
+                {
+                    this._results.push(row[wx]);
+                }
+            }
+        }
+    }
+
+    return this._results.slice();
+
+};
+
+/**
+* Returns the appropriate tileset for the index, updating the internal cache as required.
+* This should only be called if `tilesets[index]` evaluates to undefined.
+*
+* @method Phaser.TilemapLayer#resolveTileset
+* @private
+* @param {integer} Tile index
+* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping.
+*/
+Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) {
+
+    var tilesets = this._mc.tilesets;
+
+    //  Try for dense array if reasonable
+    if (tileIndex < 2000)
+    {
+        while (tilesets.length < tileIndex)
+        {
+            tilesets.push(undefined);
+        }
+    }
+
+    var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2];
+
+    if (setIndex != null) // number: not null or undefined
+    {
+        var tileset = this.map.tilesets[setIndex];
+
+        if (tileset && tileset.containsTileIndex(tileIndex))
+        {
+            return (tilesets[tileIndex] = tileset);
+        }
+    }
+
+    return (tilesets[tileIndex] = null);
+
+};
+
+/**
+* The TilemapLayer caches tileset look-ups.
+*
+* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered.
+*
+* @method Phaser.TilemapLayer#resetTilesetCache
+* @public
+*/
+Phaser.TilemapLayer.prototype.resetTilesetCache = function () {
+
+    var tilesets = this._mc.tilesets;
+
+    while (tilesets.length)
+    {
+        tilesets.pop();
+    }
+
+};
+
+/**
+ * This method will set the scale of the tilemap as well as update the underlying block data of this layer
+ * 
+ * @method Phaser.TilemapLayer#setScale
+ * @param {number} [xScale=1] - The scale factor along the X-plane 
+ * @param {number} [yScale] - The scale factor along the Y-plane
+ */
+Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) {
+
+    xScale = xScale || 1;
+    yScale = yScale || xScale;
+
+    for (var y = 0; y < this.layer.data.length; y++)
+    {
+        var row = this.layer.data[y];
+
+        for (var x = 0; x < row.length; x++)
+        {
+            var tile = row[x];
+
+            tile.width = this.map.tileWidth * xScale;
+            tile.height = this.map.tileHeight * yScale;
+
+            tile.worldX = tile.x * tile.width;
+            tile.worldY = tile.y * tile.height;
+        }
+    }
+
+    this.scale.setTo(xScale, yScale);
+
+};
+
+/**
+* Shifts the contents of the canvas - does extra math so that different browsers agree on the result.
+*
+* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in.
+*
+* @method Phaser.TilemapLayer#shiftCanvas
+* @private
+* @param {CanvasRenderingContext2D} context - The context to shift
+* @param {integer} x
+* @param {integer} y
+*/
+Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) {
+
+    var canvas = context.canvas;
+    var copyW = canvas.width - Math.abs(x);
+    var copyH = canvas.height - Math.abs(y);
+
+    //  When x/y non-negative
+    var dx = 0;
+    var dy = 0;
+    var sx = x;
+    var sy = y;
+
+    if (x < 0)
+    {
+        dx = -x;
+        sx = 0;
+    }
+
+    if (y < 0)
+    {
+        dy = -y;
+        sy = 0;
+    }
+
+    var copyCanvas = this.renderSettings.copyCanvas;
+
+    if (copyCanvas)
+    {
+        // Use a second copy buffer, without slice support, for Safari .. again.
+        // Ensure copy canvas is large enough
+        if (copyCanvas.width < copyW || copyCanvas.height < copyH)
+        {
+            copyCanvas.width = copyW;
+            copyCanvas.height = copyH;
+        }
+
+        var copyContext = copyCanvas.getContext('2d');
+        copyContext.clearRect(0, 0, copyW, copyH);
+        copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH);
+        // clear allows default 'source-over' semantics
+        context.clearRect(sx, sy, copyW, copyH);
+        context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH);
+    }
+    else
+    {
+        // Avoids a second copy but flickers in Safari / Safari Mobile
+        // Ref. https://github.com/photonstorm/phaser/issues/1439
+        context.save();
+        context.globalCompositeOperation = 'copy';
+        context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH);
+        context.restore();
+    }
+    
+};
+
+/**
+* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor.
+* This will constrain the tile coordinates based on wrapping but not physical coordinates.
+*
+* @method Phaser.TilemapLayer#renderRegion
+* @private
+* @param {integer} scrollX - Render x offset/scroll.
+* @param {integer} scrollY - Render y offset/scroll.
+* @param {integer} left - Leftmost column to render.
+* @param {integer} top - Topmost row to render.
+* @param {integer} right - Rightmost column to render.
+* @param {integer} bottom - Bottommost row to render.
+*/
+Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) {
+
+    var context = this.context;
+
+    var width = this.layer.width;
+    var height = this.layer.height;
+    var tw = this._mc.tileWidth;
+    var th = this._mc.tileHeight;
+
+    var tilesets = this._mc.tilesets;
+    var lastAlpha = NaN;
+
+    if (!this._wrap)
+    {
+        if (left <= right) // Only adjust if going to render
+        {
+            left = Math.max(0, left);
+            right = Math.min(width - 1, right);
+        }
+        if (top <= bottom)
+        {
+            top = Math.max(0, top);
+            bottom = Math.min(height - 1, bottom);
+        }
+    }
+   
+    // top-left pixel of top-left cell
+    var baseX = (left * tw) - scrollX;
+    var baseY = (top * th) - scrollY;
+
+    // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values.
+    var normStartX = (left + ((1 << 20) * width)) % width;
+    var normStartY = (top + ((1 << 20) * height)) % height;
+
+    // tx/ty - are pixel coordinates where tile is drawn
+    // x/y - is cell location, normalized [0..width/height) in loop
+    // xmax/ymax - remaining cells to render on column/row
+    var tx, ty, x, y, xmax, ymax;
+
+    context.fillStyle = this.tileColor;
+
+    for (y = normStartY, ymax = bottom - top, ty = baseY;
+        ymax >= 0;
+        y++, ymax--, ty += th)
+    {
+
+        if (y >= height) { y -= height; }
+
+        var row = this.layer.data[y];
+
+        for (x = normStartX, xmax = right - left, tx = baseX;
+            xmax >= 0;
+            x++, xmax--, tx += tw)
+        {
+
+            if (x >= width) { x -= width; }
+
+            var tile = row[x];
+
+            if (!tile || tile.index < 0)
+            {
+                continue;
+            }
+
+            var index = tile.index;
+
+            var set = tilesets[index];
+
+            if (set === undefined)
+            {
+                set = this.resolveTileset(index);
+            }
+
+            //  Setting the globalAlpha is "surprisingly expensive" in Chrome (38)
+            if (tile.alpha !== lastAlpha && !this.debug)
+            {
+                context.globalAlpha = tile.alpha;
+                lastAlpha = tile.alpha;
+            }
+
+            if (set)
+            {
+                if (tile.rotation || tile.flipped)
+                {
+                    context.save();
+                    context.translate(tx + tile.centerX, ty + tile.centerY);
+                    context.rotate(tile.rotation);
+
+                    if (tile.flipped)
+                    {
+                        context.scale(-1, 1);
+                    }
+
+                    set.draw(context, -tile.centerX, -tile.centerY, index);
+                    context.restore();
+                }
+                else
+                {
+                    set.draw(context, tx, ty, index);
+                }
+            }
+            else if (this.debugSettings.missingImageFill)
+            {
+                context.fillStyle = this.debugSettings.missingImageFill;
+                context.fillRect(tx, ty, tw, th);
+            }
+
+            if (tile.debug && this.debugSettings.debuggedTileOverfill)
+            {
+                context.fillStyle = this.debugSettings.debuggedTileOverfill;
+                context.fillRect(tx, ty, tw, th);
+            }
+           
+        }
+
+    }
+
+};
+
+/**
+* Shifts the canvas and render damaged edge tiles.
+*
+* @method Phaser.TilemapLayer#renderDeltaScroll
+* @private
+*/
+Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) {
+
+    var scrollX = this._mc.scrollX;
+    var scrollY = this._mc.scrollY;
+
+    var renderW = this.canvas.width;
+    var renderH = this.canvas.height;
+
+    var tw = this._mc.tileWidth;
+    var th = this._mc.tileHeight;
+
+    // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds.
+
+    // Start in pixels
+    var left = 0;
+    var right = -tw;
+    var top = 0;
+    var bottom = -th;
+
+    if (shiftX < 0) // layer moving left, damage right
+    {
+        left = renderW + shiftX; // shiftX neg.
+        right = renderW - 1;
+    }
+    else if (shiftX > 0)
+    {
+        // left -> 0
+        right = shiftX;
+    }
+
+    if (shiftY < 0) // layer moving down, damage top
+    {
+        top = renderH + shiftY; // shiftY neg.
+        bottom = renderH - 1;
+    }
+    else if (shiftY > 0)
+    {
+        // top -> 0
+        bottom = shiftY;
+    }
+
+    this.shiftCanvas(this.context, shiftX, shiftY);
+
+    // Transform into tile-space
+    left = Math.floor((left + scrollX) / tw);
+    right = Math.floor((right + scrollX) / tw);
+    top = Math.floor((top + scrollY) / th);
+    bottom = Math.floor((bottom + scrollY) / th);
+
+    if (left <= right)
+    {
+        // Clear left or right edge
+        this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH);
+
+        var trueTop = Math.floor((0 + scrollY) / th);
+        var trueBottom = Math.floor((renderH - 1 + scrollY) / th);
+        this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom);
+    }
+
+    if (top <= bottom)
+    {
+        // Clear top or bottom edge
+        this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th);
+
+        var trueLeft = Math.floor((0 + scrollX) / tw);
+        var trueRight = Math.floor((renderW - 1 + scrollX) / tw);
+        this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom);
+    }
+
+};
+
+/**
+* Clear and render the entire canvas.
+*
+* @method Phaser.TilemapLayer#renderFull
+* @private
+*/
+Phaser.TilemapLayer.prototype.renderFull = function () {
+    
+    var scrollX = this._mc.scrollX;
+    var scrollY = this._mc.scrollY;
+
+    var renderW = this.canvas.width;
+    var renderH = this.canvas.height;
+
+    var tw = this._mc.tileWidth;
+    var th = this._mc.tileHeight;
+
+    var left = Math.floor(scrollX / tw);
+    var right = Math.floor((renderW - 1 + scrollX) / tw);
+    var top = Math.floor(scrollY / th);
+    var bottom = Math.floor((renderH - 1 + scrollY) / th);
+
+    this.context.clearRect(0, 0, renderW, renderH);
+
+    this.renderRegion(scrollX, scrollY, left, top, right, bottom);
+
+};
+
+/**
+* Renders the tiles to the layer canvas and pushes to the display.
+*
+* @method Phaser.TilemapLayer#render
+* @protected
+*/
+Phaser.TilemapLayer.prototype.render = function () {
+
+    var redrawAll = false;
+
+    if (!this.visible)
+    {
+        return;
+    }
+
+    if (this.dirty || this.layer.dirty)
+    {
+        this.layer.dirty = false;
+        redrawAll = true;
+    }
+
+    var renderWidth = this.canvas.width; // Use Sprite.width/height?
+    var renderHeight = this.canvas.height;
+
+    //  Scrolling bias; whole pixels only
+    var scrollX = this._scrollX | 0;
+    var scrollY = this._scrollY | 0;
+
+    var mc = this._mc;
+    var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down
+    var shiftY = mc.scrollY - scrollY;
+
+    if (!redrawAll &&
+        shiftX === 0 && shiftY === 0 &&
+        mc.renderWidth === renderWidth && mc.renderHeight === renderHeight)
+    {
+        //  No reason to redraw map, looking at same thing and not invalidated.
+        return;
+    }
+
+    this.context.save();
+    
+    mc.scrollX = scrollX;
+    mc.scrollY = scrollY;
+
+    if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight)
+    {
+        //  Could support automatic canvas resizing
+        mc.renderWidth = renderWidth;
+        mc.renderHeight = renderHeight;
+    }
+
+    if (this.debug)
+    {
+        this.context.globalAlpha = this.debugSettings.debugAlpha;
+
+        if (this.debugSettings.forceFullRedraw)
+        {
+            redrawAll = true;
+        }
+    }
+
+    if (!redrawAll &&
+        this.renderSettings.enableScrollDelta &&
+        (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight))
+    {
+        this.renderDeltaScroll(shiftX, shiftY);
+    }
+    else
+    {
+        // Too much change or otherwise requires full render
+        this.renderFull();
+    }
+
+    if (this.debug)
+    {
+        this.context.globalAlpha = 1;
+        this.renderDebug();
+    }
+
+    this.texture.baseTexture.dirty();
+
+    this.dirty = false;
+
+    this.context.restore();
+
+    return true;
+
+};
+
+/**
+* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true.
+*
+* See `debugSettings` for assorted configuration options.
+*
+* @method Phaser.TilemapLayer#renderDebug
+* @private
+*/
+Phaser.TilemapLayer.prototype.renderDebug = function () {
+
+    var scrollX = this._mc.scrollX;
+    var scrollY = this._mc.scrollY;
+
+    var context = this.context;
+    var renderW = this.canvas.width;
+    var renderH = this.canvas.height;
+
+    var width = this.layer.width;
+    var height = this.layer.height;
+    var tw = this._mc.tileWidth;
+    var th = this._mc.tileHeight;
+
+    var left = Math.floor(scrollX / tw);
+    var right = Math.floor((renderW - 1 + scrollX) / tw);
+    var top = Math.floor(scrollY / th);
+    var bottom = Math.floor((renderH - 1 + scrollY) / th);
+
+    var baseX = (left * tw) - scrollX;
+    var baseY = (top * th) - scrollY;
+
+    var normStartX = (left + ((1 << 20) * width)) % width;
+    var normStartY = (top + ((1 << 20) * height)) % height;
+
+    var tx, ty, x, y, xmax, ymax;
+
+    context.strokeStyle = this.debugSettings.facingEdgeStroke;
+
+    for (y = normStartY, ymax = bottom - top, ty = baseY;
+        ymax >= 0;
+        y++, ymax--, ty += th)
+    {
+
+        if (y >= height) { y -= height; }
+
+        var row = this.layer.data[y];
+
+        for (x = normStartX, xmax = right - left, tx = baseX;
+            xmax >= 0;
+            x++, xmax--, tx += tw)
+        {
+
+            if (x >= width) { x -= width; }
+
+            var tile = row[x];
+            if (!tile || tile.index < 0 || !tile.collides)
+            {
+                continue;
+            }
+
+            if (this.debugSettings.collidingTileOverfill)
+            {
+                context.fillStyle = this.debugSettings.collidingTileOverfill;
+                context.fillRect(tx, ty, this._mc.cw, this._mc.ch);
+            }
+
+            if (this.debugSettings.facingEdgeStroke)
+            {
+                context.beginPath();
+
+                if (tile.faceTop)
+                {
+                    context.moveTo(tx, ty);
+                    context.lineTo(tx + this._mc.cw, ty);
+                }
+
+                if (tile.faceBottom)
+                {
+                    context.moveTo(tx, ty + this._mc.ch);
+                    context.lineTo(tx + this._mc.cw, ty + this._mc.ch);
+                }
+
+                if (tile.faceLeft)
+                {
+                    context.moveTo(tx, ty);
+                    context.lineTo(tx, ty + this._mc.ch);
+                }
+
+                if (tile.faceRight)
+                {
+                    context.moveTo(tx + this._mc.cw, ty);
+                    context.lineTo(tx + this._mc.cw, ty + this._mc.ch);
+                }
+
+                context.stroke();
+            }
+           
+        }
+
+    }
+
+};
+
+/**
+* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size.
+*
+* @property {boolean} wrap
+* @memberof Phaser.TilemapLayer
+* @public
+* @default false
+*/
+Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", {
+
+    get: function () {
+        return this._wrap;
+    },
+
+    set: function (value) {
+        this._wrap = value;
+        this.dirty = true;
+    }
+
+});
+
+/**
+* Scrolls the map horizontally or returns the current x position.
+*
+* @property {number} scrollX
+* @memberof Phaser.TilemapLayer
+* @public
+*/
+Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", {
+
+    get: function () {
+        return this._scrollX;
+    },
+
+    set: function (value) {
+        this._scrollX = value;
+    }
+
+});
+
+/**
+* Scrolls the map vertically or returns the current y position.
+*
+* @property {number} scrollY
+* @memberof Phaser.TilemapLayer
+* @public
+*/
+Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", {
+
+    get: function () {
+        return this._scrollY;
+    },
+
+    set: function (value) {
+        this._scrollY = value;
+    }
+
+});
+
+/**
+* The width of the collision tiles (in pixels).
+*
+* @property {integer} collisionWidth
+* @memberof Phaser.TilemapLayer
+* @public
+*/
+Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", {
+
+    get: function () {
+        return this._mc.cw;
+    },
+
+    set: function (value) {
+        this._mc.cw = value | 0;
+        this.dirty = true;
+    }
+
+});
+
+/**
+* The height of the collision tiles (in pixels).
+*
+* @property {integer} collisionHeight
+* @memberof Phaser.TilemapLayer
+* @public
+*/
+Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", {
+
+    get: function () {
+        return this._mc.ch;
+    },
+
+    set: function (value) {
+        this._mc.ch = value | 0;
+        this.dirty = true;
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
+*
+* @class Phaser.TilemapParser
+*/
+Phaser.TilemapParser = {
+
+    /**
+    * Parse tilemap data from the cache and creates a Tilemap object.
+    *
+    * @method Phaser.TilemapParser.parse
+    * @param {Phaser.Game} game - Game reference to the currently running game.
+    * @param {string} key - The key of the tilemap in the Cache.
+    * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+    * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
+    * @return {object} The parsed map object.
+    */
+    parse: function (game, key, tileWidth, tileHeight, width, height) {
+
+        if (tileWidth === undefined) { tileWidth = 32; }
+        if (tileHeight === undefined) { tileHeight = 32; }
+        if (width === undefined) { width = 10; }
+        if (height === undefined) { height = 10; }
+
+        if (key === undefined)
+        {
+            return this.getEmptyData();
+        }
+
+        if (key === null)
+        {
+            return this.getEmptyData(tileWidth, tileHeight, width, height);
+        }
+
+        var map = game.cache.getTilemapData(key);
+
+        if (map)
+        {
+            if (map.format === Phaser.Tilemap.CSV)
+            {
+                return this.parseCSV(key, map.data, tileWidth, tileHeight);
+            }
+            else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
+            {
+                return this.parseTiledJSON(map.data);
+            }
+        }
+        else
+        {
+            console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
+        }
+
+    },
+
+    /**
+    * Parses a CSV file into valid map data.
+    *
+    * @method Phaser.TilemapParser.parseCSV
+    * @param {string} data - The CSV file data.
+    * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
+    * @return {object} Generated map data.
+    */
+    parseCSV: function (key, data, tileWidth, tileHeight) {
+
+        var map = this.getEmptyData();
+
+        //  Trim any rogue whitespace from the data
+        data = data.trim();
+
+        var output = [];
+        var rows = data.split("\n");
+        var height = rows.length;
+        var width = 0;
+
+        for (var y = 0; y < rows.length; y++)
+        {
+            output[y] = [];
+
+            var column = rows[y].split(",");
+
+            for (var x = 0; x < column.length; x++)
+            {
+                output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight);
+            }
+
+            if (width === 0)
+            {
+                width = column.length;
+            }
+        }
+
+        map.format = Phaser.Tilemap.CSV;
+        map.name = key;
+        map.width = width;
+        map.height = height;
+        map.tileWidth = tileWidth;
+        map.tileHeight = tileHeight;
+        map.widthInPixels = width * tileWidth;
+        map.heightInPixels = height * tileHeight;
+
+        map.layers[0].width = width;
+        map.layers[0].height = height;
+        map.layers[0].widthInPixels = map.widthInPixels;
+        map.layers[0].heightInPixels = map.heightInPixels;
+        map.layers[0].data = output;
+
+        return map;
+
+    },
+
+    /**
+    * Returns an empty map data object.
+    *
+    * @method Phaser.TilemapParser.getEmptyData
+    * @return {object} Generated map data.
+    */
+    getEmptyData: function (tileWidth, tileHeight, width, height) {
+
+        var map = {};
+
+        map.width = 0;
+        map.height = 0;
+        map.tileWidth = 0;
+        map.tileHeight = 0;
+
+        if (typeof tileWidth !== 'undefined' && tileWidth !== null) { map.tileWidth = tileWidth; }
+        if (typeof tileHeight !== 'undefined' && tileHeight !== null) { map.tileHeight = tileHeight; }
+        if (typeof width !== 'undefined' && width !== null) { map.width = width; }
+        if (typeof height !== 'undefined' && height !== null) { map.height = height; }
+
+        map.orientation = 'orthogonal';
+        map.version = '1';
+        map.properties = {};
+        map.widthInPixels = 0;
+        map.heightInPixels = 0;
+
+        var layers = [];
+
+        var layer = {
+
+            name: 'layer',
+            x: 0,
+            y: 0,
+            width: 0,
+            height: 0,
+            widthInPixels: 0,
+            heightInPixels: 0,
+            alpha: 1,
+            visible: true,
+            properties: {},
+            indexes: [],
+            callbacks: [],
+            bodies: [],
+            data: []
+
+        };
+
+        //  fill with nulls?
+
+        layers.push(layer);
+
+        map.layers = layers;
+        map.images = [];
+        map.objects = {};
+        map.collision = {};
+        map.tilesets = [];
+        map.tiles = [];
+
+        return map;
+
+    },
+
+    /**
+    * Parses a Tiled JSON file into valid map data.
+    * @method Phaser.TilemapParser.parseJSON
+    * @param {object} json - The JSON map data.
+    * @return {object} Generated and parsed map data.
+    */
+    parseTiledJSON: function (json) {
+
+        if (json.orientation !== 'orthogonal')
+        {
+            console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser');
+            return null;
+        }
+
+        //  Map data will consist of: layers, objects, images, tilesets, sizes
+        var map = {};
+
+        map.width = json.width;
+        map.height = json.height;
+        map.tileWidth = json.tilewidth;
+        map.tileHeight = json.tileheight;
+        map.orientation = json.orientation;
+        map.format = Phaser.Tilemap.TILED_JSON;
+        map.version = json.version;
+        map.properties = json.properties;
+        map.widthInPixels = map.width * map.tileWidth;
+        map.heightInPixels = map.height * map.tileHeight;
+
+        //  Tile Layers
+        var layers = [];
+
+        for (var i = 0; i < json.layers.length; i++)
+        {
+            if (json.layers[i].type !== 'tilelayer')
+            {
+                continue;
+            }
+
+            var layer = {
+
+                name: json.layers[i].name,
+                x: json.layers[i].x,
+                y: json.layers[i].y,
+                width: json.layers[i].width,
+                height: json.layers[i].height,
+                widthInPixels: json.layers[i].width * json.tilewidth,
+                heightInPixels: json.layers[i].height * json.tileheight,
+                alpha: json.layers[i].opacity,
+                visible: json.layers[i].visible,
+                properties: {},
+                indexes: [],
+                callbacks: [],
+                bodies: []
+
+            };
+
+            if (json.layers[i].properties)
+            {
+                layer.properties = json.layers[i].properties;
+            }
+
+            var x = 0;
+            var row = [];
+            var output = [];
+            var rotation, flipped, flippedVal, gid;
+
+            //  Loop through the data field in the JSON.
+
+            //  This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV)
+            //  If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
+            //  Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset.
+
+            for (var t = 0, len = json.layers[i].data.length; t < len; t++)
+            {
+                rotation = 0;
+                flipped = false;
+                gid = json.layers[i].data[t];
+
+                //  If true the current tile is flipped or rotated (Tiled TMX format) 
+                if (gid > 0x20000000)
+                {
+                    flippedVal = 0;
+
+                    // FlippedX
+                    if (gid > 0x80000000)
+                    {
+                        gid -= 0x80000000;
+                        flippedVal += 4;
+                    }
+
+                    // FlippedY
+                    if (gid > 0x40000000)
+                    {
+                        gid -= 0x40000000;
+                        flippedVal += 2;
+                    }
+
+                    // FlippedAD
+                    if (gid > 0x20000000)
+                    {
+                        gid -= 0x20000000;
+                        flippedVal += 1;
+                    }
+                   
+                    switch (flippedVal)
+                    {
+                        case 5:
+                            rotation = Math.PI/2;
+                            break;
+                        case 6:
+                            rotation = Math.PI;
+                            break;
+                        case 3:
+                            rotation = 3*Math.PI/2;
+                            break;
+                        case 4:
+                            rotation = 0;
+                            flipped = true;
+                            break;
+                        case 7:
+                            rotation = Math.PI/2;
+                            flipped = true;
+                            break;
+                        case 2:
+                            rotation = Math.PI;
+                            flipped = true;
+                            break;
+                        case 1:
+                            rotation = 3*Math.PI/2;
+                            flipped = true;
+                            break;
+                    }
+                }
+
+                //  index, x, y, width, height
+                if (gid > 0)
+                {
+                    row.push(new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight));
+                    row[row.length - 1].rotation = rotation;
+                    row[row.length - 1].flipped = flipped;
+                }
+                else
+                {
+                    row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight));
+                }
+
+                x++;
+
+                if (x === json.layers[i].width)
+                {
+                    output.push(row);
+                    x = 0;
+                    row = [];
+                }
+            }
+
+            layer.data = output;
+
+            layers.push(layer);
+
+        }
+
+        map.layers = layers;
+
+        //  Images
+        var images = [];
+
+        for (var i = 0; i < json.layers.length; i++)
+        {
+            if (json.layers[i].type !== 'imagelayer')
+            {
+                continue;
+            }
+
+            var image = {
+
+                name: json.layers[i].name,
+                image: json.layers[i].image,
+                x: json.layers[i].x,
+                y: json.layers[i].y,
+                alpha: json.layers[i].opacity,
+                visible: json.layers[i].visible,
+                properties: {}
+
+            };
+
+            if (json.layers[i].properties)
+            {
+                image.properties = json.layers[i].properties;
+            }
+
+            images.push(image);
+
+        }
+
+        map.images = images;
+
+        //  Tilesets & Image Collections
+        var tilesets = [];
+        var imagecollections = [];
+
+        for (var i = 0; i < json.tilesets.length; i++)
+        {
+            //  name, firstgid, width, height, margin, spacing, properties
+            var set = json.tilesets[i];
+
+            if (set.image)
+            {
+                var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
+
+                if (set.tileproperties)
+                {
+                    newSet.tileProperties = set.tileproperties;
+                }
+
+                // For a normal sliced tileset the row/count/size information is computed when updated.
+                // This is done (again) after the image is set.
+                newSet.updateTileData(set.imagewidth, set.imageheight);
+                tilesets.push(newSet);
+            }
+            else
+            {
+                var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
+                
+                for (var i in set.tiles)
+                {
+                    var image = set.tiles[i].image;
+                    var gid = set.firstgid + parseInt(i, 10);
+                    newCollection.addImage(gid, image);
+                }
+
+                imagecollections.push(newCollection);
+            }
+
+        }
+
+        map.tilesets = tilesets;
+        map.imagecollections = imagecollections;
+
+        //  Objects & Collision Data (polylines, etc)
+        var objects = {};
+        var collision = {};
+
+        function slice (obj, fields) {
+
+            var sliced = {};
+
+            for (var k in fields)
+            {
+                var key = fields[k];
+
+                if (typeof obj[key] !== 'undefined')
+                {
+                    sliced[key] = obj[key];
+                }
+            }
+
+            return sliced;
+        }
+
+        for (var i = 0; i < json.layers.length; i++)
+        {
+            if (json.layers[i].type !== 'objectgroup')
+            {
+                continue;
+            }
+
+            objects[json.layers[i].name] = [];
+            collision[json.layers[i].name] = [];
+
+            for (var v = 0, len = json.layers[i].objects.length; v < len; v++)
+            {
+                //  Object Tiles
+                if (json.layers[i].objects[v].gid)
+                {
+                    var object = {
+
+                        gid: json.layers[i].objects[v].gid,
+                        name: json.layers[i].objects[v].name,
+                        type: json.layers[i].objects[v].hasOwnProperty("type") ? json.layers[i].objects[v].type : "",
+                        x: json.layers[i].objects[v].x,
+                        y: json.layers[i].objects[v].y,
+                        visible: json.layers[i].objects[v].visible,
+                        properties: json.layers[i].objects[v].properties
+
+                    };
+
+                    if (json.layers[i].objects[v].rotation)
+                    {
+                        object.rotation = json.layers[i].objects[v].rotation;
+                    }
+
+                    objects[json.layers[i].name].push(object);
+                }
+                else if (json.layers[i].objects[v].polyline)
+                {
+                    var object = {
+
+                        name: json.layers[i].objects[v].name,
+                        type: json.layers[i].objects[v].type,
+                        x: json.layers[i].objects[v].x,
+                        y: json.layers[i].objects[v].y,
+                        width: json.layers[i].objects[v].width,
+                        height: json.layers[i].objects[v].height,
+                        visible: json.layers[i].objects[v].visible,
+                        properties: json.layers[i].objects[v].properties
+
+                    };
+
+                    if (json.layers[i].objects[v].rotation)
+                    {
+                        object.rotation = json.layers[i].objects[v].rotation;
+                    }
+
+                    object.polyline = [];
+
+                    //  Parse the polyline into an array
+                    for (var p = 0; p < json.layers[i].objects[v].polyline.length; p++)
+                    {
+                        object.polyline.push([ json.layers[i].objects[v].polyline[p].x, json.layers[i].objects[v].polyline[p].y ]);
+                    }
+
+                    collision[json.layers[i].name].push(object);
+                    objects[json.layers[i].name].push(object);
+                }
+                // polygon
+                else if (json.layers[i].objects[v].polygon)
+                {
+                    var object = slice(json.layers[i].objects[v],
+                                       ["name", "type", "x", "y", "visible", "rotation", "properties" ]);
+
+                    //  Parse the polygon into an array
+                    object.polygon = [];
+
+                    for (var p = 0; p < json.layers[i].objects[v].polygon.length; p++)
+                    {
+                        object.polygon.push([ json.layers[i].objects[v].polygon[p].x, json.layers[i].objects[v].polygon[p].y ]);
+                    }
+
+                    objects[json.layers[i].name].push(object);
+
+                }
+                // ellipse
+                else if (json.layers[i].objects[v].ellipse)
+                {
+                    var object = slice(json.layers[i].objects[v],
+                                       ["name", "type", "ellipse", "x", "y", "width", "height", "visible", "rotation", "properties" ]);
+                    objects[json.layers[i].name].push(object);
+                }
+                // otherwise it's a rectangle
+                else
+                {
+                    var object = slice(json.layers[i].objects[v],
+                                       ["name", "type", "x", "y", "width", "height", "visible", "rotation", "properties" ]);
+                    object.rectangle = true;
+                    objects[json.layers[i].name].push(object);
+                }
+            }
+        }
+
+        map.objects = objects;
+        map.collision = collision;
+
+        map.tiles = [];
+
+        //  Finally lets build our super tileset index
+        for (var i = 0; i < map.tilesets.length; i++)
+        {
+            var set = map.tilesets[i];
+
+            var x = set.tileMargin;
+            var y = set.tileMargin;
+
+            var count = 0;
+            var countX = 0;
+            var countY = 0;
+
+            for (var t = set.firstgid; t < set.firstgid + set.total; t++)
+            {
+                //  Can add extra properties here as needed
+                map.tiles[t] = [x, y, i];
+
+                x += set.tileWidth + set.tileSpacing;
+
+                count++;
+
+                if (count === set.total)
+                {
+                    break;
+                }
+
+                countX++;
+
+                if (countX === set.columns)
+                {
+                    x = set.tileMargin;
+                    y += set.tileHeight + set.tileSpacing;
+
+                    countX = 0;
+                    countY++;
+
+                    if (countY === set.rows)
+                    {
+                        break;
+                    }
+                }
+            }
+
+        }
+
+        // assign tile properties
+
+        var layer;
+        var tile;
+        var sid;
+        var set;
+
+        // go through each of the map layers
+        for (var i = 0; i < map.layers.length; i++)
+        {
+            layer = map.layers[i];
+
+            // rows of tiles
+            for (var j = 0; j < layer.data.length; j++)
+            {
+                row = layer.data[j];
+
+                // individual tiles
+                for (var k = 0; k < row.length; k++)
+                {
+                    tile = row[k];
+
+                    if (tile.index < 0)
+                    {
+                        continue;
+                    }
+
+                    // find the relevant tileset
+
+                    sid = map.tiles[tile.index][2];
+                    set = map.tilesets[sid];
+
+                    // if that tile type has any properties, add them to the tile object
+
+                    if (set.tileProperties && set.tileProperties[tile.index - set.firstgid])
+                    {
+                        tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties);
+                    }
+                }
+            }
+        }
+
+        return map;
+
+    }
+
+};
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Tile set is a combination of an image containing the tiles and collision data per tile.
+*
+* Tilesets are normally created automatically when Tiled data is loaded.
+*
+* @class Phaser.Tileset
+* @constructor
+* @param {string} name - The name of the tileset in the map data.
+* @param {integer} firstgid - The first tile index this tileset contains.
+* @param {integer} [width=32] - Width of each tile (in pixels).
+* @param {integer} [height=32] - Height of each tile (in pixels).
+* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels).
+* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels).
+* @param {object} [properties={}] - Custom Tileset properties.
+*/
+Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) {
+
+    if (width === undefined || width <= 0) { width = 32; }
+    if (height === undefined || height <= 0) { height = 32; }
+    if (margin === undefined) { margin = 0; }
+    if (spacing === undefined) { spacing = 0; }
+
+    /**
+    * The name of the Tileset.
+    * @property {string} name
+    */
+    this.name = name;
+
+    /**
+    * The Tiled firstgid value.
+    * This is the starting index of the first tile index this Tileset contains.
+    * @property {integer} firstgid
+    */
+    this.firstgid = firstgid | 0;
+
+    /**
+    * The width of each tile (in pixels).
+    * @property {integer} tileWidth
+    * @readonly
+    */
+    this.tileWidth = width | 0;
+
+    /**
+    * The height of each tile (in pixels).
+    * @property {integer} tileHeight
+    * @readonly
+    */
+    this.tileHeight = height | 0;
+
+    /**
+    * The margin around the tiles in the sheet (in pixels).
+    * Use `setSpacing` to change.
+    * @property {integer} tileMarge
+    * @readonly
+    */
+    // Modified internally
+    this.tileMargin = margin | 0;
+
+    /**
+    * The spacing between each tile in the sheet (in pixels).
+    * Use `setSpacing` to change.
+    * @property {integer} tileSpacing
+    * @readonly
+    */
+    this.tileSpacing = spacing | 0;
+
+    /**
+    * Tileset-specific properties that are typically defined in the Tiled editor.
+    * @property {object} properties
+    */
+    this.properties = properties || {};
+
+    /**
+    * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set.
+    * @property {?object} image
+    * @readonly
+    */
+    // Modified internally
+    this.image = null;
+
+    /**
+    * The number of tile rows in the the tileset.
+    * @property {integer}
+    * @readonly
+    */
+    // Modified internally
+    this.rows = 0;
+
+    /**
+    * The number of tile columns in the tileset.
+    * @property {integer} columns
+    * @readonly
+    */
+    // Modified internally
+    this.columns = 0;
+
+    /**
+    * The total number of tiles in the tileset.
+    * @property {integer} total
+    * @readonly
+    */
+    // Modified internally
+    this.total = 0;
+
+    /**
+    * The look-up table to specific tile image offsets.
+    * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1.
+    * @property {integer[]} drawCoords
+    * @private
+    */
+    this.drawCoords = [];
+
+};
+
+Phaser.Tileset.prototype = {
+
+    /**
+    * Draws a tile from this Tileset at the given coordinates on the context.
+    *
+    * @method Phaser.Tileset#draw
+    * @public
+    * @param {CanvasRenderingContext2D} context - The context to draw the tile onto.
+    * @param {number} x - The x coordinate to draw to.
+    * @param {number} y - The y coordinate to draw to.
+    * @param {integer} index - The index of the tile within the set to draw.
+    */
+    draw: function (context, x, y, index) {
+
+        //  Correct the tile index for the set and bias for interlacing
+        var coordIndex = (index - this.firstgid) << 1;
+
+        if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length)
+        {
+            context.drawImage(
+                this.image,
+                this.drawCoords[coordIndex],
+                this.drawCoords[coordIndex + 1],
+                this.tileWidth,
+                this.tileHeight,
+                x,
+                y,
+                this.tileWidth,
+                this.tileHeight
+            );
+        }
+
+    },
+
+    /**
+    * Returns true if and only if this tileset contains the given tile index.
+    *
+    * @method Phaser.Tileset#containsTileIndex
+    * @public
+    * @return {boolean} True if this tileset contains the given index.
+    */
+    containsTileIndex: function (tileIndex) {
+
+        return (
+            tileIndex >= this.firstgid &&
+            tileIndex < (this.firstgid + this.total)
+        );
+
+    },
+
+    /**
+    * Set the image associated with this Tileset and update the tile data.
+    *
+    * @method Phaser.Tileset#setImage
+    * @public
+    * @param {Image} image - The image that contains the tiles.
+    */
+    setImage: function (image) {
+
+        this.image = image;
+        this.updateTileData(image.width, image.height);
+       
+    },
+
+    /**
+    * Sets tile spacing and margins.
+    *
+    * @method Phaser.Tileset#setSpacing
+    * @public
+    * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels).
+    * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels).
+    */
+    setSpacing: function (margin, spacing) {
+
+        this.tileMargin = margin | 0;
+        this.tileSpacing = spacing | 0;
+
+        if (this.image)
+        {
+            this.updateTileData(this.image.width, this.image.height);
+        }
+
+    },
+
+    /**
+    * Updates tile coordinates and tileset data.
+    *
+    * @method Phaser.Tileset#updateTileData
+    * @private
+    * @param {integer} imageWidth - The (expected) width of the image to slice.
+    * @param {integer} imageHeight - The (expected) height of the image to slice.
+    */
+    updateTileData: function (imageWidth, imageHeight) {
+
+        // May be fractional values
+        var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
+        var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing);
+
+        if (rowCount % 1 !== 0 || colCount % 1 !== 0)
+        {
+            console.warn("Phaser.Tileset - image tile area is not an even multiple of tile size");
+        }
+
+        // In Tiled a tileset image that is not an even multiple of the tile dimensions
+        // is truncated - hence the floor when calculating the rows/columns.
+        rowCount = Math.floor(rowCount);
+        colCount = Math.floor(colCount);
+
+        if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount))
+        {
+            console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ");
+        }
+
+        this.rows = rowCount;
+        this.columns = colCount;
+        this.total = rowCount * colCount;
+
+        this.drawCoords.length = 0;
+
+        var tx = this.tileMargin;
+        var ty = this.tileMargin;
+
+        for (var y = 0; y < this.rows; y++)
+        {
+            for (var x = 0; x < this.columns; x++)
+            {
+                this.drawCoords.push(tx);
+                this.drawCoords.push(ty);
+                tx += this.tileWidth + this.tileSpacing;
+            }
+
+            tx = this.tileMargin;
+            ty += this.tileHeight + this.tileSpacing;
+        }
+
+    }
+
+};
+
+Phaser.Tileset.prototype.constructor = Phaser.Tileset;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
+*
+* @class Phaser.Particles
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+*/
+Phaser.Particles = function (game) {
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running Game.
+    */
+    this.game = game;
+
+    /**
+    * @property {object} emitters - Internal emitters store.
+    */
+    this.emitters = {};
+
+    /**
+    * @property {number} ID -
+    * @default
+    */
+    this.ID = 0;
+
+};
+
+Phaser.Particles.prototype = {
+
+    /**
+    * Adds a new Particle Emitter to the Particle Manager.
+    * @method Phaser.Particles#add
+    * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
+    * @return {Phaser.Emitter} The emitter that was added.
+    */
+    add: function (emitter) {
+
+        this.emitters[emitter.name] = emitter;
+
+        return emitter;
+
+    },
+
+    /**
+    * Removes an existing Particle Emitter from the Particle Manager.
+    * @method Phaser.Particles#remove
+    * @param {Phaser.Emitter} emitter - The emitter to remove.
+    */
+    remove: function (emitter) {
+
+        delete this.emitters[emitter.name];
+
+    },
+
+    /**
+    * Called by the core game loop. Updates all Emitters who have their exists value set to true.
+    * @method Phaser.Particles#update
+    * @protected
+    */
+    update: function () {
+
+        for (var key in this.emitters)
+        {
+            if (this.emitters[key].exists)
+            {
+                this.emitters[key].update();
+            }
+        }
+
+    }
+
+};
+
+Phaser.Particles.prototype.constructor = Phaser.Particles;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Arcade Particles is a Particle System integrated with Arcade Physics.
+*
+* @class Phaser.Particles.Arcade
+*/
+Phaser.Particles.Arcade = {};
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* Emitter is a lightweight particle emitter that uses Arcade Physics.
+* It can be used for one-time explosions or for continuous effects like rain and fire.
+* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly.
+* 
+* @class Phaser.Particles.Arcade.Emitter
+* @constructor
+* @extends Phaser.Group
+* @param {Phaser.Game} game - Current game instance.
+* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
+* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
+* @param {number} [maxParticles=50] - The total number of particles in this emitter.
+*/
+Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
+
+    /**
+    * @property {number} maxParticles - The total number of particles in this emitter.
+    * @default
+    */
+    this.maxParticles = maxParticles || 50;
+
+    Phaser.Group.call(this, game);
+
+    /**
+    * @property {string} name - A handy string name for this emitter. Can be set to anything.
+    */
+    this.name = 'emitter' + this.game.particles.ID++;
+
+    /**
+    * @property {number} type - Internal Phaser Type value.
+    * @protected
+    */
+    this.type = Phaser.EMITTER;
+
+    /**
+    * @property {number} physicsType - The const physics body type of this object.
+    * @readonly
+    */
+    this.physicsType = Phaser.GROUP;
+
+    /**
+    * @property {Phaser.Rectangle} area - The area of the emitter. Particles can be randomly generated from anywhere within this rectangle.
+    * @default
+    */
+    this.area = new Phaser.Rectangle(x, y, 1, 1);
+
+    /**
+    * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle.
+    * @default
+    */
+    this.minParticleSpeed = new Phaser.Point(-100, -100);
+
+    /**
+    * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle.
+    * @default
+    */
+    this.maxParticleSpeed = new Phaser.Point(100, 100);
+
+    /**
+    * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX.
+    * @default
+    */
+    this.minParticleScale = 1;
+
+    /**
+    * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX.
+    * @default
+    */
+    this.maxParticleScale = 1;
+
+    /**
+    * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0.
+    */
+    this.scaleData = null;
+
+    /**
+    * @property {number} minRotation - The minimum possible angular velocity of a particle.
+    * @default
+    */
+    this.minRotation = -360;
+
+    /**
+    * @property {number} maxRotation - The maximum possible angular velocity of a particle.
+    * @default
+    */
+    this.maxRotation = 360;
+
+    /**
+    * @property {number} minParticleAlpha - The minimum possible alpha value of a particle.
+    * @default
+    */
+    this.minParticleAlpha = 1;
+
+    /**
+    * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle.
+    * @default
+    */
+    this.maxParticleAlpha = 1;
+
+    /**
+    * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0.
+    */
+    this.alphaData = null;
+
+    /**
+    * @property {number} gravity - Sets the `body.gravity.y` of each particle sprite to this value on launch.
+    * @default
+    */
+    this.gravity = 100;
+
+    /**
+    * @property {any} particleClass - For emitting your own particle class types. They must extend Phaser.Particle.
+    * @default
+    */
+    this.particleClass = Phaser.Particle;
+
+    /**
+    * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter.
+    */
+    this.particleDrag = new Phaser.Point();
+
+    /**
+    * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating.
+    * @default
+    */
+    this.angularDrag = 0;
+
+    /**
+    * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false).
+    * @default
+    */
+    this.frequency = 100;
+
+    /**
+    * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever.
+    * @default
+    */
+    this.lifespan = 2000;
+
+    /**
+    * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
+    */
+    this.bounce = new Phaser.Point();
+
+    /**
+    * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this.
+    * @default
+    */
+    this.on = false;
+
+    /**
+    * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation)
+    * @default
+    */
+    this.particleAnchor = new Phaser.Point(0.5, 0.5);
+
+    /**
+    * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL)
+    * @default
+    */
+    this.blendMode = Phaser.blendModes.NORMAL;
+
+    /**
+    * The point the particles are emitted from.
+    * Emitter.x and Emitter.y control the containers location, which updates all current particles
+    * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
+    * @property {number} emitX
+    */
+    this.emitX = x;
+
+    /**
+    * The point the particles are emitted from.
+    * Emitter.x and Emitter.y control the containers location, which updates all current particles
+    * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
+    * @property {number} emitY
+    */
+    this.emitY = y;
+
+    /**
+    * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure.
+    */
+    this.autoScale = false;
+
+    /**
+    * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure.
+    */
+    this.autoAlpha = false;
+
+    /**
+    * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list.
+    * @default
+    */
+    this.particleBringToTop = false;
+
+    /**
+    * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list.
+    * @default
+    */
+    this.particleSendToBack = false;
+
+    /**
+    * @property {Phaser.Point} _minParticleScale - Internal particle scale var.
+    * @private
+    */
+    this._minParticleScale = new Phaser.Point(1, 1);
+
+    /**
+    * @property {Phaser.Point} _maxParticleScale - Internal particle scale var.
+    * @private
+    */
+    this._maxParticleScale = new Phaser.Point(1, 1);
+
+    /**
+    * @property {number} _quantity - Internal helper for deciding how many particles to launch.
+    * @private
+    */
+    this._quantity = 0;
+
+    /**
+    * @property {number} _timer - Internal helper for deciding when to launch particles or kill them.
+    * @private
+    */
+    this._timer = 0;
+
+    /**
+    * @property {number} _counter - Internal counter for figuring out how many particles to launch.
+    * @private
+    */
+    this._counter = 0;
+
+    /**
+    * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update.
+    * @private
+    */
+    this._flowQuantity = 0;
+
+    /**
+    * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total.
+    * @private
+    */
+    this._flowTotal = 0;
+
+    /**
+    * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time).
+    * @private
+    */
+    this._explode = true;
+
+    /**
+    * @property {any} _frames - Internal helper for the particle frame.
+    * @private
+    */
+    this._frames = null;
+
+};
+
+Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
+Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
+
+/**
+* Called automatically by the game loop, decides when to launch particles and when to "die".
+* 
+* @method Phaser.Particles.Arcade.Emitter#update
+*/
+Phaser.Particles.Arcade.Emitter.prototype.update = function () {
+
+    if (this.on && this.game.time.time >= this._timer)
+    {
+        this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion;
+
+        if (this._flowTotal !== 0)
+        {
+            if (this._flowQuantity > 0)
+            {
+                for (var i = 0; i < this._flowQuantity; i++)
+                {
+                    if (this.emitParticle())
+                    {
+                        this._counter++;
+
+                        if (this._flowTotal !== -1 && this._counter >= this._flowTotal)
+                        {
+                            this.on = false;
+                            break;
+                        }
+                    }
+                }
+            }
+            else
+            {
+                if (this.emitParticle())
+                {
+                    this._counter++;
+
+                    if (this._flowTotal !== -1 && this._counter >= this._flowTotal)
+                    {
+                        this.on = false;
+                    }
+                }
+            }
+        }
+        else
+        {
+            if (this.emitParticle())
+            {
+                this._counter++;
+
+                if (this._quantity > 0 && this._counter >= this._quantity)
+                {
+                    this.on = false;
+                }
+            }
+        }
+
+    }
+
+    var i = this.children.length;
+
+    while (i--)
+    {
+        if (this.children[i].exists)
+        {
+            this.children[i].update();
+        }
+    }
+
+};
+
+/**
+* This function generates a new set of particles for use by this emitter.
+* The particles are stored internally waiting to be emitted via Emitter.start.
+*
+* @method Phaser.Particles.Arcade.Emitter#makeParticles
+* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random.
+* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random.
+* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity.
+* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true.
+* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
+* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
+
+    if (frames === undefined) { frames = 0; }
+    if (quantity === undefined) { quantity = this.maxParticles; }
+    if (collide === undefined) { collide = false; }
+    if (collideWorldBounds === undefined) { collideWorldBounds = false; }
+
+    var particle;
+    var i = 0;
+    var rndKey = keys;
+    var rndFrame = frames;
+    this._frames = frames;
+
+    if (quantity > this.maxParticles)
+    {
+        this.maxParticles = quantity;
+    }
+
+    while (i < quantity)
+    {
+        if (Array.isArray(keys))
+        {
+            rndKey = this.game.rnd.pick(keys);
+        }
+
+        if (Array.isArray(frames))
+        {
+            rndFrame = this.game.rnd.pick(frames);
+        }
+
+        particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame);
+
+        this.game.physics.arcade.enable(particle, false);
+
+        if (collide)
+        {
+            particle.body.checkCollision.any = true;
+            particle.body.checkCollision.none = false;
+        }
+        else
+        {
+            particle.body.checkCollision.none = true;
+        }
+
+        particle.body.collideWorldBounds = collideWorldBounds;
+        particle.body.skipQuadTree = true;
+
+        particle.exists = false;
+        particle.visible = false;
+        particle.anchor.copyFrom(this.particleAnchor);
+
+        this.add(particle);
+
+        i++;
+    }
+
+    return this;
+
+};
+
+/**
+* Call this function to turn off all the particles and the emitter.
+*
+* @method Phaser.Particles.Arcade.Emitter#kill
+*/
+Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
+
+    this.on = false;
+    this.alive = false;
+    this.exists = false;
+
+};
+
+/**
+* Handy for bringing game objects "back to life". Just sets alive and exists back to true.
+*
+* @method Phaser.Particles.Arcade.Emitter#revive
+*/
+Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
+
+    this.alive = true;
+    this.exists = true;
+
+};
+
+/**
+* Call this function to emit the given quantity of particles at all once (an explosion)
+* 
+* @method Phaser.Particles.Arcade.Emitter#explode
+* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
+* @param {number} [quantity=0] - How many particles to launch.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) {
+
+    this._flowTotal = 0;
+
+    this.start(true, lifespan, 0, quantity, false);
+
+};
+
+/**
+* Call this function to start emitting a flow of particles at the given frequency.
+* It will carry on going until the total given is reached.
+* Each time the flow is run the quantity number of particles will be emitted together.
+* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 x 5 = 20 total)
+* If you set the total to be -1 then no quantity cap is used and it will keep emitting.
+* 
+* @method Phaser.Particles.Arcade.Emitter#flow
+* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
+* @param {number} [frequency=250] - Frequency is how often to emit the particles, given in ms.
+* @param {number} [quantity=1] - How many particles to launch each time the frequency is met. Can never be > Emitter.maxParticles.
+* @param {number} [total=-1] - How many particles to launch in total. If -1 it will carry on indefinitely.
+* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false)
+*/
+Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) {
+
+    if (quantity === undefined || quantity === 0) { quantity = 1; }
+    if (total === undefined) { total = -1; }
+    if (immediate === undefined) { immediate = true; }
+
+    if (quantity > this.maxParticles)
+    {
+        quantity = this.maxParticles;
+    }
+
+    this._counter = 0;
+    this._flowQuantity = quantity;
+    this._flowTotal = total;
+
+    if (immediate)
+    {
+        this.start(true, lifespan, frequency, quantity);
+
+        this._counter += quantity;
+        this.on = true;
+        this._timer = this.game.time.time + frequency * this.game.time.slowMotion;
+    }
+    else
+    {
+        this.start(false, lifespan, frequency, quantity);
+    }
+
+};
+
+/**
+* Call this function to start emitting particles.
+* 
+* @method Phaser.Particles.Arcade.Emitter#start
+* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false).
+* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
+* @param {number} [frequency=250] - Ignored if Explode is set to true. Frequency is how often to emit 1 particle. Value given in ms.
+* @param {number} [quantity=0] - How many particles to launch. 0 = "all of the particles" which will keep emitting until Emitter.maxParticles is reached.
+* @param {number} [forceQuantity=false] - If `true` and creating a particle flow, the quantity emitted will be forced to the be quantity given in this call. This can never exceed Emitter.maxParticles.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity, forceQuantity) {
+
+    if (explode === undefined) { explode = true; }
+    if (lifespan === undefined) { lifespan = 0; }
+    if (frequency === undefined || frequency === null) { frequency = 250; }
+    if (quantity === undefined) { quantity = 0; }
+    if (forceQuantity === undefined) { forceQuantity = false; }
+
+    if (quantity > this.maxParticles)
+    {
+        quantity = this.maxParticles;
+    }
+
+    this.revive();
+
+    this.visible = true;
+
+    this.lifespan = lifespan;
+    this.frequency = frequency;
+
+    if (explode || forceQuantity)
+    {
+        for (var i = 0; i < quantity; i++)
+        {
+            this.emitParticle();
+        }
+    }
+    else
+    {
+        this.on = true;
+        this._quantity += quantity;
+        this._counter = 0;
+        this._timer = this.game.time.time + frequency * this.game.time.slowMotion;
+    }
+
+};
+
+/**
+* This function can be used both internally and externally to emit the next particle in the queue.
+*
+* @method Phaser.Particles.Arcade.Emitter#emitParticle
+* @return {boolean} True if a particle was emitted, otherwise false.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () {
+
+    var particle = this.getFirstExists(false);
+
+    if (particle === null)
+    {
+        return false;
+    }
+
+    if (this.width > 1 || this.height > 1)
+    {
+        particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom));
+    }
+    else
+    {
+        particle.reset(this.emitX, this.emitY);
+    }
+
+    particle.angle = 0;
+    particle.lifespan = this.lifespan;
+
+    if (this.particleBringToTop)
+    {
+        this.bringToTop(particle);
+    }
+    else if (this.particleSendToBack)
+    {
+        this.sendToBack(particle);
+    }
+
+    if (this.autoScale)
+    {
+        particle.setScaleData(this.scaleData);
+    }
+    else if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
+    {
+        particle.scale.set(this.game.rnd.realInRange(this.minParticleScale, this.maxParticleScale));
+    }
+    else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y))
+    {
+        particle.scale.set(this.game.rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), this.game.rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y));
+    }
+
+    if (Array.isArray(this._frames === 'object'))
+    {
+        particle.frame = this.game.rnd.pick(this._frames);
+    }
+    else
+    {
+        particle.frame = this._frames;
+    }
+
+    if (this.autoAlpha)
+    {
+        particle.setAlphaData(this.alphaData);
+    }
+    else
+    {
+        particle.alpha = this.game.rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha);
+    }
+
+    particle.blendMode = this.blendMode;
+
+    particle.body.updateBounds();
+
+    particle.body.bounce.setTo(this.bounce.x, this.bounce.y);
+
+    particle.body.velocity.x = this.game.rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x);
+    particle.body.velocity.y = this.game.rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y);
+    particle.body.angularVelocity = this.game.rnd.between(this.minRotation, this.maxRotation);
+
+    particle.body.gravity.y = this.gravity;
+
+    particle.body.drag.x = this.particleDrag.x;
+    particle.body.drag.y = this.particleDrag.y;
+
+    particle.body.angularDrag = this.angularDrag;
+
+    particle.onEmit();
+
+    return true;
+
+};
+
+/**
+* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager.
+* 
+* @method Phaser.Particles.Arcade.Emitter#destroy
+*/
+Phaser.Particles.Arcade.Emitter.prototype.destroy = function () {
+
+    this.game.particles.remove(this);
+
+    Phaser.Group.prototype.destroy.call(this, true, false);
+
+};
+
+/**
+* A more compact way of setting the width and height of the emitter.
+* 
+* @method Phaser.Particles.Arcade.Emitter#setSize
+* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
+* @param {number} height - The desired height of the emitter.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
+
+    this.area.width = width;
+    this.area.height = height;
+
+};
+
+/**
+* A more compact way of setting the X velocity range of the emitter.
+* @method Phaser.Particles.Arcade.Emitter#setXSpeed
+* @param {number} [min=0] - The minimum value for this range.
+* @param {number} [max=0] - The maximum value for this range.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
+
+    min = min || 0;
+    max = max || 0;
+
+    this.minParticleSpeed.x = min;
+    this.maxParticleSpeed.x = max;
+
+};
+
+/**
+* A more compact way of setting the Y velocity range of the emitter.
+* @method Phaser.Particles.Arcade.Emitter#setYSpeed
+* @param {number} [min=0] - The minimum value for this range.
+* @param {number} [max=0] - The maximum value for this range.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
+
+    min = min || 0;
+    max = max || 0;
+
+    this.minParticleSpeed.y = min;
+    this.maxParticleSpeed.y = max;
+
+};
+
+/**
+* A more compact way of setting the angular velocity constraints of the particles.
+*
+* @method Phaser.Particles.Arcade.Emitter#setRotation
+* @param {number} [min=0] - The minimum value for this range.
+* @param {number} [max=0] - The maximum value for this range.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
+
+    min = min || 0;
+    max = max || 0;
+
+    this.minRotation = min;
+    this.maxRotation = max;
+
+};
+
+/**
+* A more compact way of setting the alpha constraints of the particles.
+* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max.
+* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit.
+*
+* @method Phaser.Particles.Arcade.Emitter#setAlpha
+* @param {number} [min=1] - The minimum value for this range.
+* @param {number} [max=1] - The maximum value for this range.
+* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two.
+* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
+* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
+*/
+Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) {
+
+    if (min === undefined) { min = 1; }
+    if (max === undefined) { max = 1; }
+    if (rate === undefined) { rate = 0; }
+    if (ease === undefined) { ease = Phaser.Easing.Linear.None; }
+    if (yoyo === undefined) { yoyo = false; }
+
+    this.minParticleAlpha = min;
+    this.maxParticleAlpha = max;
+    this.autoAlpha = false;
+
+    if (rate > 0 && min !== max)
+    {
+        var tweenData = { v: min };
+        var tween = this.game.make.tween(tweenData).to( { v: max }, rate, ease);
+        tween.yoyo(yoyo);
+
+        this.alphaData = tween.generateData(60);
+
+        //  Inverse it so we don't have to do array length look-ups in Particle update loops
+        this.alphaData.reverse();
+        this.autoAlpha = true;
+    }
+
+};
+
+/**
+* A more compact way of setting the scale constraints of the particles.
+* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis.
+* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit.
+*
+* @method Phaser.Particles.Arcade.Emitter#setScale
+* @param {number} [minX=1] - The minimum value of Particle.scale.x.
+* @param {number} [maxX=1] - The maximum value of Particle.scale.x.
+* @param {number} [minY=1] - The minimum value of Particle.scale.y.
+* @param {number} [maxY=1] - The maximum value of Particle.scale.y.
+* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two.
+* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
+* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
+*/
+Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) {
+
+    if (minX === undefined) { minX = 1; }
+    if (maxX === undefined) { maxX = 1; }
+    if (minY === undefined) { minY = 1; }
+    if (maxY === undefined) { maxY = 1; }
+    if (rate === undefined) { rate = 0; }
+    if (ease === undefined) { ease = Phaser.Easing.Linear.None; }
+    if (yoyo === undefined) { yoyo = false; }
+
+    //  Reset these
+    this.minParticleScale = 1;
+    this.maxParticleScale = 1;
+
+    this._minParticleScale.set(minX, minY);
+    this._maxParticleScale.set(maxX, maxY);
+
+    this.autoScale = false;
+
+    if (rate > 0 && ((minX !== maxX) || (minY !== maxY)))
+    {
+        var tweenData = { x: minX, y: minY };
+        var tween = this.game.make.tween(tweenData).to( { x: maxX, y: maxY }, rate, ease);
+        tween.yoyo(yoyo);
+
+        this.scaleData = tween.generateData(60);
+
+        //  Inverse it so we don't have to do array length look-ups in Particle update loops
+        this.scaleData.reverse();
+        this.autoScale = true;
+    }
+
+};
+
+/**
+* Change the emitters center to match the center of any object with a `center` property, such as a Sprite.
+* If the object doesn't have a center property it will be set to object.x + object.width / 2
+*
+* @method Phaser.Particles.Arcade.Emitter#at
+* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with.
+*/
+Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
+
+    if (object.center)
+    {
+        this.emitX = object.center.x;
+        this.emitY = object.center.y;
+    }
+    else
+    {
+        this.emitX = object.world.x + (object.anchor.x * object.width);
+        this.emitY = object.world.y + (object.anchor.y * object.height);
+    }
+
+};
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#width
+* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted.
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", {
+
+    get: function () {
+        return this.area.width;
+    },
+
+    set: function (value) {
+        this.area.width = value;
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#height
+* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted.
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", {
+
+    get: function () {
+        return this.area.height;
+    },
+
+    set: function (value) {
+        this.area.height = value;
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#x
+* @property {number} x - Gets or sets the x position of the Emitter.
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
+
+    get: function () {
+        return this.emitX;
+    },
+
+    set: function (value) {
+        this.emitX = value;
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#y
+* @property {number} y - Gets or sets the y position of the Emitter.
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
+
+    get: function () {
+        return this.emitY;
+    },
+
+    set: function (value) {
+        this.emitY = value;
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#left
+* @property {number} left - Gets the left position of the Emitter.
+* @readonly
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
+
+    get: function () {
+        return Math.floor(this.x - (this.area.width / 2));
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#right
+* @property {number} right - Gets the right position of the Emitter.
+* @readonly
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
+
+    get: function () {
+        return Math.floor(this.x + (this.area.width / 2));
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#top
+* @property {number} top - Gets the top position of the Emitter.
+* @readonly
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
+
+    get: function () {
+        return Math.floor(this.y - (this.area.height / 2));
+    }
+
+});
+
+/**
+* @name Phaser.Particles.Arcade.Emitter#bottom
+* @property {number} bottom - Gets the bottom position of the Emitter.
+* @readonly
+*/
+Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
+
+    get: function () {
+        return Math.floor(this.y + (this.area.height / 2));
+    }
+
+});
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+/**
+* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it.
+* 
+* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to
+* the Video instead (see `startMediaStream` method)
+* 
+* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback
+* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously.
+*
+* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode.
+* 
+* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite.
+* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM.
+*
+* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen.
+* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio
+* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource`
+* method to try and work around this limitation, but see the method help for details.
+*
+* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, 
+* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation.
+*
+* @class Phaser.Video
+* @constructor
+* @param {Phaser.Game} game - A reference to the currently running game.
+* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture.
+* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null)
+*/
+Phaser.Video = function (game, key, url) {
+
+    if (key === undefined) { key = null; }
+    if (url === undefined) { url = null; }
+
+    /**
+    * @property {Phaser.Game} game - A reference to the currently running game.
+    */
+    this.game = game;
+
+    /**
+    * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead.
+    * @default null
+    */
+    this.key = key;
+
+    /**
+    * @property {number} width - The width of the video in pixels.
+    * @default
+    */
+    this.width = 0;
+
+    /**
+    * @property {number} height - The height of the video in pixels.
+    * @default
+    */
+    this.height = 0;
+
+    /**
+    * @property {number} type - The const type of this object.
+    * @default
+    */
+    this.type = Phaser.VIDEO;
+
+    /**
+    * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL.
+    */
+    this.disableTextureUpload = false;
+
+    /**
+    * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS.
+    * @default
+    */
+    this.touchLocked = false;
+
+    /**
+    * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate.
+    */
+    this.onPlay = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source.
+    */
+    this.onChangeSource = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. Videos set to loop will never dispatch this signal.
+    */
+    this.onComplete = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam.
+    */
+    this.onAccess = new Phaser.Signal();
+
+    /**
+    * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file.
+    */
+    this.onError = new Phaser.Signal();
+
+    /**
+    * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit.
+    * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream.
+    * @property {Phaser.Signal} onTimeout
+    */
+    this.onTimeout = new Phaser.Signal();
+
+    /**
+    * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access.
+    * @default
+    */
+    this.timeout = 15000;
+
+    /**
+    * @property {integer} _timeOutID - setTimeout ID.
+    * @private
+    */
+    this._timeOutID = null;
+
+    /**
+    * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document.
+    */
+    this.video = null;
+
+    /**
+    * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`.
+    */
+    this.videoStream = null;
+
+    /**
+    * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam.
+    */
+    this.isStreaming = false;
+
+    /**
+    * When starting playback of a video Phaser will monitor its readyState using a setTimeout call.
+    * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video
+    * state in this manner until the `retryLimit` is reached and then abort.
+    * @property {integer} retryLimit
+    * @default
+    */
+    this.retryLimit = 20;
+
+    /**
+    * @property {integer} retry - The current retry attempt.
+    * @default
+    */
+    this.retry = 0;
+
+    /**
+    * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video.
+    * @default
+    */
+    this.retryInterval = 500;
+
+    /**
+    * @property {integer} _retryID - The callback ID of the retry setTimeout.
+    * @private
+    */
+    this._retryID = null;
+
+    /**
+    * @property {boolean} _codeMuted - Internal mute tracking var.
+    * @private
+    * @default
+    */
+    this._codeMuted = false;
+
+    /**
+    * @property {boolean} _muted - Internal mute tracking var.
+    * @private
+    * @default
+    */
+    this._muted = false;
+
+    /**
+    * @property {boolean} _codePaused - Internal paused tracking var.
+    * @private
+    * @default
+    */
+    this._codePaused = false;
+
+    /**
+    * @property {boolean} _paused - Internal paused tracking var.
+    * @private
+    * @default
+    */
+    this._paused = false;
+
+    /**
+    * @property {boolean} _pending - Internal var tracking play pending.
+    * @private
+    * @default
+    */
+    this._pending = false;
+
+    /**
+    * @property {boolean} _autoplay - Internal var tracking autoplay when changing source.
+    * @private
+    * @default
+    */
+    this._autoplay = false;
+
+    if (key && this.game.cache.checkVideoKey(key))
+    {
+        var _video = this.game.cache.getVideo(key);
+
+        if (_video.isBlob)
+        {
+            this.createVideoFromBlob(_video.data);
+        }
+        else
+        {
+            this.video = _video.data;
+        }
+
+        this.width = this.video.videoWidth;
+        this.height = this.video.videoHeight;
+    }
+    else if (url)
+    {
+        this.createVideoFromURL(url, false);
+    }
+
+    /**
+    * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
+    * @default
+    */
+    if (this.video && !url)
+    {
+        this.baseTexture = new PIXI.BaseTexture(this.video);
+        this.baseTexture.forceLoaded(this.width, this.height);
+    }
+    else
+    {
+        this.baseTexture = new PIXI.BaseTexture(PIXI.TextureCache['__default'].baseTexture.source);
+        this.baseTexture.forceLoaded(this.width, this.height);
+    }
+
+    /**
+    * @property {PIXI.Texture} texture - The PIXI.Texture.
+    * @default
+    */
+    this.texture = new PIXI.Texture(this.baseTexture);
+
+    /**
+    * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering.
+    * @default
+    */
+    this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video');
+
+    this.texture.setFrame(this.textureFrame);
+
+    this.texture.valid = false;
+
+    if (key !== null && this.video)
+    {
+        this.texture.valid = this.video.canplay;
+    }
+
+    /**
+    * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab().
+    * When called the BitmapData is updated with a grab taken from the current video playing or active video stream.
+    * If Phaser has been compiled without BitmapData support this property will always be `null`.
+    * 
+    * @property {Phaser.BitmapData} snapshot
+    * @readOnly
+    */
+    this.snapshot = null;
+
+    if (Phaser.BitmapData)
+    {
+        this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height);
+    }
+
+    if (!this.game.device.cocoonJS && (this.game.device.iOS || this.game.device.android) || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
+    {
+        this.setTouchLock();
+    }
+    else
+    {
+        if (_video)
+        {
+            _video.locked = false;
+        }
+    }
+
+};
+
+Phaser.Video.prototype = {
+
+    /**
+     * Connects to an external media stream for the webcam, rather than using a local one.
+     *
+     * @method Phaser.Video#connectToMediaStream
+     * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses.
+     * @param {MediaStream} stream - The Video Stream data.
+     * @return {Phaser.Video} This Video object for method chaining.
+     */
+    connectToMediaStream: function (video, stream) {
+
+        if (video && stream)
+        {
+            this.video = video;
+            this.videoStream = stream;
+
+            this.isStreaming = true;
+            this.baseTexture.source = this.video;
+            this.updateTexture(null, this.video.videoWidth, this.video.videoHeight);
+
+            this.onAccess.dispatch(this);
+        }
+
+        return this;
+
+    },
+
+    /**
+     * Instead of playing a video file this method allows you to stream video data from an attached webcam.
+     *
+     * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam.
+     * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream.
+     *
+     * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError
+     * or MediaStreamError event.
+     *
+     * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions.
+     * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device.
+     * You can listen for this with the onChangeSource signal.
+     *
+     * @method Phaser.Video#startMediaStream
+     * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream.
+     * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source.
+     * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source.
+     * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia.
+     */
+    startMediaStream: function (captureAudio, width, height) {
+
+        if (captureAudio === undefined) { captureAudio = false; }
+        if (width === undefined) { width = null; }
+        if (height === undefined) { height = null; }
+
+        if (!this.game.device.getUserMedia)
+        {
+            this.onError.dispatch(this, 'No getUserMedia');
+            return false;
+        }
+
+        if (this.videoStream !== null)
+        {
+            this.videoStream.stop();
+        }
+
+        this.removeVideoElement();
+
+        this.video = document.createElement("video");
+        this.video.setAttribute('autoplay', 'autoplay');
+
+        if (width !== null)
+        {
+            this.video.width = width;
+        }
+
+        if (height !== null)
+        {
+            this.video.height = height;
+        }
+
+        //  Request access to the webcam
+
+        this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout);
+
+        try {
+            navigator.getUserMedia(
+                { "audio": captureAudio, "video": true },
+                this.getUserMediaSuccess.bind(this),
+                this.getUserMediaError.bind(this)
+            );
+        }
+        catch (error)
+        {
+            this.getUserMediaError(error);
+        }
+
+        return this;
+
+    },
+
+    /**
+     * @method Phaser.Video#getUserMediaTimeout
+     * @private
+     */
+    getUserMediaTimeout: function () {
+
+        clearTimeout(this._timeOutID);
+
+        this.onTimeout.dispatch(this);
+
+    },
+
+    /**
+     * @method Phaser.Video#getUserMediaError
+     * @private
+     */
+    getUserMediaError: function (event) {
+
+        clearTimeout(this._timeOutID);
+
+        this.onError.dispatch(this, event);
+
+    },
+
+    /**
+     * @method Phaser.Video#getUserMediaSuccess
+     * @private
+     */
+    getUserMediaSuccess: function (stream) {
+
+        clearTimeout(this._timeOutID);
+
+        // Attach the stream to the video
+        this.videoStream = stream;
+
+        // Set the source of the video element with the stream from the camera
+        if (this.video.mozSrcObject !== undefined)
+        {
+            this.video.mozSrcObject = stream;
+        }
+        else
+        {
+            this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
+        }
+
+        var self = this;
+
+        this.video.onloadeddata = function () {
+
+            var retry = 10;
+
+            function checkStream () {
+
+                if (retry > 0)
+                {
+                    if (self.video.videoWidth > 0)
+                    {
+                        // Patch for Firefox bug where the height can't be read from the video
+                        var width = self.video.videoWidth;
+                        var height = self.video.videoHeight;
+
+                        if (isNaN(self.video.videoHeight))
+                        {
+                            height = width / (4/3);
+                        }
+
+                        self.video.play();
+
+                        self.isStreaming = true;
+                        self.baseTexture.source = self.video;
+                        self.updateTexture(null, width, height);
+                        self.onAccess.dispatch(self);
+                    }
+                    else
+                    {
+                        window.setTimeout(checkStream, 500);
+                    }
+                }
+                else
+                {
+                    console.warn('Unable to connect to video stream. Webcam error?');
+                }
+
+                retry--;
+            }
+
+            checkStream();
+
+        };
+
+    },
+
+    /**
+     * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format.
+     * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience.
+     *
+     * @method Phaser.Video#createVideoFromBlob
+     * @param {Blob} blob - The Blob containing the video data: `Blob([new Uint8Array(data)])`
+     * @return {Phaser.Video} This Video object for method chaining.
+     */
+    createVideoFromBlob: function (blob) {
+
+        var _this = this;
+
+        this.video = document.createElement("video");
+        this.video.controls = false;
+        this.video.setAttribute('autoplay', 'autoplay');
+        this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true);
+        this.video.src = window.URL.createObjectURL(blob);
+        this.video.canplay = true;
+
+        return this;
+
+    },
+
+    /**
+     * Creates a new Video element from the given URL.
+     *
+     * @method Phaser.Video#createVideoFromURL
+     * @param {string} url - The URL of the video.
+     * @param {boolean} [autoplay=false] - Automatically start the video?
+     * @return {Phaser.Video} This Video object for method chaining.
+     */
+    createVideoFromURL: function (url, autoplay) {
+
+        if (autoplay === undefined) { autoplay = false; }
+
+        //  Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise)
+        if (this.texture)
+        {
+            this.texture.valid = false;
+        }
+
+        this.video = document.createElement("video");
+        this.video.controls = false;
+
+        if (autoplay)
+        {
+            this.video.setAttribute('autoplay', 'autoplay');
+        }
+
+        this.video.src = url;
+
+        this.video.canplay = true;
+
+        this.video.load();
+
+        this.retry = this.retryLimit;
+
+        this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
+
+        this.key = url;
+
+        return this;
+
+    },
+
+    /**
+     * Called automatically if the video source changes and updates the internal texture dimensions.
+     * Then dispatches the onChangeSource signal.
+     *
+     * @method Phaser.Video#updateTexture
+     * @param {object} [event] - The event which triggered the texture update.
+     * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used.
+     * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used.
+     */
+    updateTexture: function (event, width, height) {
+
+        var change = false;
+
+        if (width === undefined || width === null) { width = this.video.videoWidth; change = true; }
+        if (height === undefined || height === null) { height = this.video.videoHeight; }
+
+        this.width = width;
+        this.height = height;
+
+        if (this.baseTexture.source !== this.video)
+        {
+            this.baseTexture.source = this.video;
+        }
+
+        this.baseTexture.forceLoaded(width, height);
+
+        this.texture.frame.resize(width, height);
+
+        this.texture.width = width;
+        this.texture.height = height;
+
+        this.texture.valid = true;
+
+        if (this.snapshot)
+        {
+            this.snapshot.resize(width, height);
+        }
+
+        if (change && this.key !== null)
+        {
+            this.onChangeSource.dispatch(this, width, height);
+
+            if (this._autoplay)
+            {
+                this.video.play();
+                this.onPlay.dispatch(this, this.loop, this.playbackRate);
+            }
+        }
+
+    },
+
+    /**
+     * Called when the video completes playback (reaches and ended state).
+     * Dispatches the Video.onComplete signal.
+     *
+     * @method Phaser.Video#complete
+     */
+    complete: function () {
+
+        this.onComplete.dispatch(this);
+
+    },
+
+    /**
+     * Starts this video playing if it's not already doing so.
+     *
+     * @method Phaser.Video#play
+     * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping.
+     * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate.
+     * @return {Phaser.Video} This Video object for method chaining.
+     */
+    play: function (loop, playbackRate) {
+
+        if (loop === undefined) { loop = false; }
+        if (playbackRate === undefined) { playbackRate = 1; }
+
+        if (this.game.sound.onMute)
+        {
+            this.game.sound.onMute.add(this.setMute, this);
+            this.game.sound.onUnMute.add(this.unsetMute, this);
+
+            if (this.game.sound.mute)
+            {
+                this.setMute();
+            }
+        }
+
+        this.game.onPause.add(this.setPause, this);
+        this.game.onResume.add(this.setResume, this);
+
+        this.video.addEventListener('ended', this.complete.bind(this), true);
+
+        if (loop)
+        {
+            this.video.loop = 'loop';
+        }
+        else
+        {
+            this.video.loop = '';
+        }
+
+        this.video.playbackRate = playbackRate;
+
+        if (this.touchLocked)
+        {
+            this._pending = true;
+        }
+        else
+        {
+            this._pending = false;
+
+            if (this.key !== null)
+            {
+                if (this.video.readyState !== 4)
+                {
+                    this.retry = this.retryLimit;
+                    this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
+                }
+                else
+                {
+                    this.video.addEventListener('playing', this.playHandler.bind(this), true);
+                }
+            }
+
+            this.video.play();
+
+            this.onPlay.dispatch(this, loop, playbackRate);
+        }
+
+        return this;
+
+    },
+
+    /**
+     * Called when the video starts to play. Updates the texture.
+     *
+     * @method Phaser.Video#playHandler
+     * @private
+     */
+    playHandler: function () {
+
+        this.video.removeEventListener('playing', this.playHandler.bind(this));
+
+        this.updateTexture();
+
+    },
+
+    /**
+     * Stops the video playing.
+     * 
+     * This removes all locally set signals.
+     * 
+     * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead.
+     * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to 
+     * call `Video.destroy` instead.
+     *
+     * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam.
+     *
+     * @method Phaser.Video#stop
+     * @return {Phaser.Video} This Video object for method chaining.
+     */
+    stop: function () {
+
+        if (this.game.sound.onMute)
+        {
+            this.game.sound.onMute.remove(this.setMute, this);
+            this.game.sound.onUnMute.remove(this.unsetMute, this);
+        }
+
+        this.game.onPause.remove(this.setPause, this);
+        this.game.onResume.remove(this.setResume, this);
+
+        //  Stream or file?
+
+        if (this.isStreaming)
+        {
+            if (this.video.mozSrcObject)
+            {
+                this.video.mozSrcObject.stop();
+                this.video.src = null;
+            }
+            else
+            {
+                this.video.src = "";
+                this.videoStream.stop();
+            }
+
+            this.videoStream = null;
+            this.isStreaming = false;
+        }
+        else
+        {
+            this.video.removeEventListener('ended', this.complete.bind(this));
+
+            if (this.touchLocked)
+            {
+                this._pending = false;
+            }
+            else
+            {
+                this.video.pause();
+            }
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Updates the given Display Objects so they use this Video as their texture.
+    * This will replace any texture they will currently have set.
+    *
+    * @method Phaser.Video#add
+    * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
+    * @return {Phaser.Video} This Video object for method chaining.
+    */
+    add: function (object) {
+
+        if (Array.isArray(object))
+        {
+            for (var i = 0; i < object.length; i++)
+            {
+                if (object[i]['loadTexture'])
+                {
+                    object[i].loadTexture(this);
+                }
+            }
+        }
+        else
+        {
+            object.loadTexture(this);
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it.
+    *
+    * @method Phaser.Video#addToWorld
+    * @param {number} [x=0] - The x coordinate to place the Image at.
+    * @param {number} [y=0] - The y coordinate to place the Image at.
+    * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
+    * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
+    * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
+    * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
+    * @return {Phaser.Image} The newly added Image object.
+    */
+    addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) {
+
+        scaleX = scaleX || 1;
+        scaleY = scaleY || 1;
+
+        var image = this.game.add.image(x, y, this);
+
+        image.anchor.set(anchorX, anchorY);
+        image.scale.set(scaleX, scaleY);
+
+        return image;
+
+    },
+
+    /**
+    * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
+    * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function.
+    * If you wish to suppress this functionality set Video.disableTextureUpload to `true`.
+    *
+    * @method Phaser.Video#render
+    */
+    render: function () {
+
+        if (!this.disableTextureUpload && this.playing)
+        {
+            this.baseTexture.dirty();
+        }
+
+    },
+
+    /**
+    * Internal handler called automatically by the Video.mute setter.
+    *
+    * @method Phaser.Video#setMute
+    * @private
+    */
+    setMute: function () {
+
+        if (this._muted)
+        {
+            return;
+        }
+
+        this._muted = true;
+
+        this.video.muted = true;
+
+    },
+
+    /**
+    * Internal handler called automatically by the Video.mute setter.
+    *
+    * @method Phaser.Video#unsetMute
+    * @private
+    */
+    unsetMute: function () {
+
+        if (!this._muted || this._codeMuted)
+        {
+            return;
+        }
+
+        this._muted = false;
+
+        this.video.muted = false;
+
+    },
+
+    /**
+    * Internal handler called automatically by the Video.paused setter.
+    *
+    * @method Phaser.Video#setPause
+    * @private
+    */
+    setPause: function () {
+
+        if (this._paused || this.touchLocked)
+        {
+            return;
+        }
+
+        this._paused = true;
+
+        this.video.pause();
+
+    },
+
+    /**
+    * Internal handler called automatically by the Video.paused setter.
+    *
+    * @method Phaser.Video#setResume
+    * @private
+    */
+    setResume: function () {
+
+        if (!this._paused || this._codePaused || this.touchLocked)
+        {
+            return;
+        }
+
+        this._paused = false;
+
+        if (!this.video.ended)
+        {
+            this.video.play();
+        }
+
+    },
+
+    /**
+     * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it.
+     * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over"
+     * split into three different Video objects, then you will need the user to touch-unlock every single one of them.
+     * 
+     * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains
+     * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again.
+     *
+     * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate.
+     * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it
+     * cannot render the new video on iOS (desktop browsers cope better).
+     *
+     * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know
+     * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state
+     * are adopted automatically by the new video.
+     *
+     * @method Phaser.Video#changeSource
+     * @param {string} src - The new URL to change the video.src to.
+     * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated?
+     * @return {Phaser.Video} This Video object for method chaining.
+     */
+    changeSource: function (src, autoplay) {
+
+        if (autoplay === undefined) { autoplay = true; }
+
+        //  Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise)
+        this.texture.valid = false;
+
+        this.video.pause();
+
+        this.retry = this.retryLimit;
+
+        this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
+
+        this.video.src = src;
+
+        this.video.load();
+
+        this._autoplay = autoplay;
+
+        if (!autoplay)
+        {
+            this.paused = true;
+        }
+
+        return this;
+
+    },
+
+    /**
+    * Internal callback that monitors the download progress of a video after changing its source.
+    * 
+    * @method Phaser.Video#checkVideoProgress
+    * @private
+    */
+    checkVideoProgress: function () {
+
+        // if (this.video.readyState === 2 || this.video.readyState === 4)
+        if (this.video.readyState === 4)
+        {
+            //  We've got enough data to update the texture for playback
+            this.updateTexture();
+        }
+        else
+        {
+            this.retry--;
+
+            if (this.retry > 0)
+            {
+                this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
+            }
+            else
+            {
+                console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming);
+            }
+        }
+
+    },
+
+    /**
+    * Sets the Input Manager touch callback to be Video.unlock.
+    * Required for mobile video unlocking. Mostly just used internally.
+    * 
+    * @method Phaser.Video#setTouchLock
+    */
+    setTouchLock: function () {
+
+        this.game.input.touch.addTouchLockCallback(this.unlock, this);
+        this.touchLocked = true;
+
+    },
+
+    /**
+    * Enables the video on mobile devices, usually after the first touch.
+    * If the SoundManager hasn't been unlocked then this will automatically unlock that as well.
+    * Only one video can be pending unlock at any one time.
+    * 
+    * @method Phaser.Video#unlock
+    */
+    unlock: function () {
+
+        this.touchLocked = false;
+
+        this.video.play();
+
+        this.onPlay.dispatch(this, this.loop, this.playbackRate);
+
+        if (this.key)
+        {
+            var _video = this.game.cache.getVideo(this.key);
+
+            if (_video && !_video.isBlob)
+            {
+                _video.locked = false;
+            }
+        }
+
+        return true;
+
+    },
+
+    /**
+     * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData.
+     *
+     * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw.
+     *
+     * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy.
+     *
+     * @method Phaser.Video#grab
+     * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false.
+     * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque.
+     * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
+     * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining.
+     */
+    grab: function (clear, alpha, blendMode) {
+
+        if (clear === undefined) { clear = false; }
+        if (alpha === undefined) { alpha = 1; }
+        if (blendMode === undefined) { blendMode = null; }
+
+        if (this.snapshot === null)
+        {
+            console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable');
+            return;
+        }
+
+        if (clear)
+        {
+            this.snapshot.cls();
+        }
+
+        this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode);
+
+        return this.snapshot;
+
+    },
+
+    /**
+     * Removes the Video element from the DOM by calling parentNode.removeChild on itself.
+     * Also removes the autoplay and src attributes and nulls the reference.
+     * 
+     * @method Phaser.Video#removeVideoElement
+     */
+    removeVideoElement: function () {
+
+        if (!this.video)
+        {
+            return;
+        }
+
+        if (this.video.parentNode)
+        {
+            this.video.parentNode.removeChild(this.video);
+        }
+
+        while (this.video.hasChildNodes())
+        {
+            this.video.removeChild(this.video.firstChild);
+        }
+
+        this.video.removeAttribute('autoplay');
+        this.video.removeAttribute('src');
+
+        this.video = null;
+
+    },
+
+    /**
+     * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`.
+     * If any Sprites are using this Video as their texture it is up to you to manage those.
+     *
+     * @method Phaser.Video#destroy
+     */
+    destroy: function () {
+
+        this.stop();
+
+        this.removeVideoElement();
+
+        if (this.touchLocked)
+        {
+            this.game.input.touch.removeTouchLockCallback(this.unlock, this);
+        }
+
+        if (this._retryID)
+        {
+            window.clearTimeout(this._retryID);
+        }
+
+    }
+
+};
+
+/**
+* @memberof Phaser.Video
+* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time.
+*/
+Object.defineProperty(Phaser.Video.prototype, "currentTime", {
+
+    get: function () {
+
+        return (this.video) ? this.video.currentTime : 0;
+
+    },
+
+    set: function (value) {
+
+        this.video.currentTime = value;
+
+    }
+
+});
+
+/**
+* @memberof Phaser.Video
+* @property {number} duration - The duration of the video in seconds.
+* @readOnly
+*/
+Object.defineProperty(Phaser.Video.prototype, "duration", {
+
+    get: function () {
+
+        return (this.video) ? this.video.duration : 0;
+
+    }
+
+});
+
+/**
+* @memberof Phaser.Video
+* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video.
+* @readOnly
+*/
+Object.defineProperty(Phaser.Video.prototype, "progress", {
+
+    get: function () {
+
+        return (this.video) ? (this.video.currentTime / this.video.duration) : 0;
+
+    }
+
+});
+
+/**
+* @name Phaser.Video#mute
+* @property {boolean} mute - Gets or sets the muted state of the Video.
+*/
+Object.defineProperty(Phaser.Video.prototype, "mute", {
+
+    get: function () {
+
+        return this._muted;
+
+    },
+
+    set: function (value) {
+
+        value = value || null;
+
+        if (value)
+        {
+            if (this._muted)
+            {
+                return;
+            }
+
+            this._codeMuted = true;
+            this.setMute();
+        }
+        else
+        {
+            if (!this._muted)
+            {
+                return;
+            }
+
+            this._codeMuted = false;
+            this.unsetMute();
+        }
+    }
+
+});
+
+/**
+* Gets or sets the paused state of the Video.
+* If the video is still touch locked (such as on iOS devices) this call has no effect.
+* 
+* @name Phaser.Video#paused
+* @property {boolean} paused
+*/
+Object.defineProperty(Phaser.Video.prototype, "paused", {
+
+    get: function () {
+
+        return this._paused;
+
+    },
+
+    set: function (value) {
+
+        value = value || null;
+
+        if (this.touchLocked)
+        {
+            return;
+        }
+
+        if (value)
+        {
+            if (this._paused)
+            {
+                return;
+            }
+
+            this._codePaused = true;
+            this.setPause();
+        }
+        else
+        {
+            if (!this._paused)
+            {
+                return;
+            }
+
+            this._codePaused = false;
+            this.setResume();
+        }
+    }
+
+});
+
+/**
+* @name Phaser.Video#volume
+* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1.
+*/
+Object.defineProperty(Phaser.Video.prototype, "volume", {
+
+    get: function () {
+
+        return (this.video) ? this.video.volume : 1;
+
+    },
+
+    set: function (value) {
+
+        if (value < 0)
+        {
+            value = 0;
+        }
+        else if (value > 1)
+        {
+            value = 1;
+        }
+
+        if (this.video)
+        {
+            this.video.volume = value;
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Video#playbackRate
+* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing.
+*/
+Object.defineProperty(Phaser.Video.prototype, "playbackRate", {
+
+    get: function () {
+
+        return (this.video) ? this.video.playbackRate : 1;
+
+    },
+
+    set: function (value) {
+
+        if (this.video)
+        {
+            this.video.playbackRate = value;
+        }
+
+    }
+
+});
+
+/**
+* Gets or sets if the Video is set to loop.
+* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping.
+* If the video isn't yet set this will always return false.
+* 
+* @name Phaser.Video#loop
+* @property {boolean} loop
+*/
+Object.defineProperty(Phaser.Video.prototype, "loop", {
+
+    get: function () {
+
+        return (this.video) ? this.video.loop : false;
+
+    },
+
+    set: function (value) {
+
+        if (value && this.video)
+        {
+            this.video.loop = 'loop';
+        }
+        else if (this.video)
+        {
+            this.video.loop = '';
+        }
+
+    }
+
+});
+
+/**
+* @name Phaser.Video#playing
+* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false.
+* @readOnly
+*/
+Object.defineProperty(Phaser.Video.prototype, "playing", {
+
+    get: function () {
+
+        return !(this.video.paused && this.video.ended);
+
+    }
+
+});
+
+Phaser.Video.prototype.constructor = Phaser.Video;
+
+/* global Phaser:true */
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+//  Pixi expects these globals to exist
+
+if (PIXI.blendModes === undefined)
+{
+    PIXI.blendModes = Phaser.blendModes;
+}
+
+if (PIXI.scaleModes === undefined)
+{
+    PIXI.scaleModes = Phaser.scaleModes;
+}
+
+if (PIXI.Texture.emptyTexture === undefined)
+{
+    PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture());
+}
+
+if (PIXI.DisplayObject._tempMatrix === undefined)
+{
+    PIXI.DisplayObject._tempMatrix = new PIXI.Matrix();
+}
+
+if (PIXI.RenderTexture.tempMatrix === undefined)
+{
+    PIXI.RenderTexture.tempMatrix = new PIXI.Matrix();
+}
+
+if (PIXI.Graphics.POLY === undefined)
+{
+    PIXI.Graphics.POLY = Phaser.POLYGON;
+    PIXI.Graphics.RECT = Phaser.RECTANGLE;
+    PIXI.Graphics.CIRC = Phaser.CIRCLE;
+    PIXI.Graphics.ELIP = Phaser.ELLIPSE;
+    PIXI.Graphics.RREC = Phaser.ROUNDEDRECTANGLE;
+}
+
+PIXI.TextureSilentFail = true;
+
+/**
+* @author       Richard Davey <rich@photonstorm.com>
+* @copyright    2015 Photon Storm Ltd.
+* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+*/
+
+    if (typeof exports !== 'undefined') {
+        if (typeof module !== 'undefined' && module.exports) {
+            exports = module.exports = Phaser;
+        }
+        exports.Phaser = Phaser;
+    } else if (typeof define !== 'undefined' && define.amd) {
+        define('Phaser', (function() { return root.Phaser = Phaser; })() );
+    } else {
+        root.Phaser = Phaser;
+    }
+
+    return Phaser;
+}).call(this);
+
+/*
+* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer
+*/
diff --git a/js/phaser/phaser.min.js b/js/phaser/phaser.min.js
new file mode 100644
index 0000000..3524cc9
--- /dev/null
+++ b/js/phaser/phaser.min.js
@@ -0,0 +1,26 @@
+/* Phaser v2.4.2 - http://phaser.io - @photonstorm - (c) 2015 Photon Storm Ltd. */
+
+!function(a){if("object"==typeof exports)module.exports=a();else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.p2=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b){function c(){}var d=a("./Scalar");b.exports=c,c.lineInt=function(a,b,c){c=c||0;var e,f,g,h,i,j,k,l=[0,0];return e=a[1][1]-a[0][1],f=a[0][0]-a[1][0],g=e*a[0][0]+f*a[0][1],h=b[1][1]-b[0][1],i=b[0][0]-b[1][0],j=h*b[0][0]+i*b[0][1],k=e*i-h*f,d.eq(k,0,c)||(l[0]=(i*g-f*j)/k,l[1]=(e*j-h*g)/k),l},c.segmentsIntersect=function(a,b,c,d){var e=b[0]-a[0],f=b[1]-a[1],g=d[0]-c[0],h=d[1]-c[1];if(g*f-h*e==0)return!1;var i=(e*(c[1]-a[1])+f*(a[0]-c[0]))/(g*f-h*e),j=(g*(a[1]-c[1])+h*(c[0]-a[0]))/(h*e-g*f);return i>=0&&1>=i&&j>=0&&1>=j}},{"./Scalar":4}],2:[function(a,b){function c(){}b.exports=c,c.area=function(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1])},c.left=function(a,b,d){return c.area(a,b,d)>0},c.leftOn=function(a,b,d){return c.area(a,b,d)>=0},c.right=function(a,b,d){return c.area(a,b,d)<0},c.rightOn=function(a,b,d){return c.area(a,b,d)<=0};var d=[],e=[];c.collinear=function(a,b,f,g){if(g){var h=d,i=e;h[0]=b[0]-a[0],h[1]=b[1]-a[1],i[0]=f[0]-b[0],i[1]=f[1]-b[1];var j=h[0]*i[0]+h[1]*i[1],k=Math.sqrt(h[0]*h[0]+h[1]*h[1]),l=Math.sqrt(i[0]*i[0]+i[1]*i[1]),m=Math.acos(j/(k*l));return g>m}return 0==c.area(a,b,f)},c.sqdist=function(a,b){var c=b[0]-a[0],d=b[1]-a[1];return c*c+d*d}},{}],3:[function(a,b){function c(){this.vertices=[]}function d(a,b,c,d,e){e=e||0;var f=b[1]-a[1],h=a[0]-b[0],i=f*a[0]+h*a[1],j=d[1]-c[1],k=c[0]-d[0],l=j*c[0]+k*c[1],m=f*k-j*h;return g.eq(m,0,e)?[0,0]:[(k*i-h*l)/m,(f*l-j*i)/m]}var e=a("./Line"),f=a("./Point"),g=a("./Scalar");b.exports=c,c.prototype.at=function(a){var b=this.vertices,c=b.length;return b[0>a?a%c+c:a%c]},c.prototype.first=function(){return this.vertices[0]},c.prototype.last=function(){return this.vertices[this.vertices.length-1]},c.prototype.clear=function(){this.vertices.length=0},c.prototype.append=function(a,b,c){if("undefined"==typeof b)throw new Error("From is not given!");if("undefined"==typeof c)throw new Error("To is not given!");if(b>c-1)throw new Error("lol1");if(c>a.vertices.length)throw new Error("lol2");if(0>b)throw new Error("lol3");for(var d=b;c>d;d++)this.vertices.push(a.vertices[d])},c.prototype.makeCCW=function(){for(var a=0,b=this.vertices,c=1;c<this.vertices.length;++c)(b[c][1]<b[a][1]||b[c][1]==b[a][1]&&b[c][0]>b[a][0])&&(a=c);f.left(this.at(a-1),this.at(a),this.at(a+1))||this.reverse()},c.prototype.reverse=function(){for(var a=[],b=0,c=this.vertices.length;b!==c;b++)a.push(this.vertices.pop());this.vertices=a},c.prototype.isReflex=function(a){return f.right(this.at(a-1),this.at(a),this.at(a+1))};var h=[],i=[];c.prototype.canSee=function(a,b){var c,d,g=h,j=i;if(f.leftOn(this.at(a+1),this.at(a),this.at(b))&&f.rightOn(this.at(a-1),this.at(a),this.at(b)))return!1;d=f.sqdist(this.at(a),this.at(b));for(var k=0;k!==this.vertices.length;++k)if((k+1)%this.vertices.length!==a&&k!==a&&f.leftOn(this.at(a),this.at(b),this.at(k+1))&&f.rightOn(this.at(a),this.at(b),this.at(k))&&(g[0]=this.at(a),g[1]=this.at(b),j[0]=this.at(k),j[1]=this.at(k+1),c=e.lineInt(g,j),f.sqdist(this.at(a),c)<d))return!1;return!0},c.prototype.copy=function(a,b,d){var e=d||new c;if(e.clear(),b>a)for(var f=a;b>=f;f++)e.vertices.push(this.vertices[f]);else{for(var f=0;b>=f;f++)e.vertices.push(this.vertices[f]);for(var f=a;f<this.vertices.length;f++)e.vertices.push(this.vertices[f])}return e},c.prototype.getCutEdges=function(){for(var a=[],b=[],d=[],e=new c,f=Number.MAX_VALUE,g=0;g<this.vertices.length;++g)if(this.isReflex(g))for(var h=0;h<this.vertices.length;++h)if(this.canSee(g,h)){b=this.copy(g,h,e).getCutEdges(),d=this.copy(h,g,e).getCutEdges();for(var i=0;i<d.length;i++)b.push(d[i]);b.length<f&&(a=b,f=b.length,a.push([this.at(g),this.at(h)]))}return a},c.prototype.decomp=function(){var a=this.getCutEdges();return a.length>0?this.slice(a):[this]},c.prototype.slice=function(a){if(0==a.length)return[this];if(a instanceof Array&&a.length&&a[0]instanceof Array&&2==a[0].length&&a[0][0]instanceof Array){for(var b=[this],c=0;c<a.length;c++)for(var d=a[c],e=0;e<b.length;e++){var f=b[e],g=f.slice(d);if(g){b.splice(e,1),b.push(g[0],g[1]);break}}return b}var d=a,c=this.vertices.indexOf(d[0]),e=this.vertices.indexOf(d[1]);return-1!=c&&-1!=e?[this.copy(c,e),this.copy(e,c)]:!1},c.prototype.isSimple=function(){for(var a=this.vertices,b=0;b<a.length-1;b++)for(var c=0;b-1>c;c++)if(e.segmentsIntersect(a[b],a[b+1],a[c],a[c+1]))return!1;for(var b=1;b<a.length-2;b++)if(e.segmentsIntersect(a[0],a[a.length-1],a[b],a[b+1]))return!1;return!0},c.prototype.quickDecomp=function(a,b,e,g,h,i){h=h||100,i=i||0,g=g||25,a="undefined"!=typeof a?a:[],b=b||[],e=e||[];var j=[0,0],k=[0,0],l=[0,0],m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=new c,u=new c,v=this,w=this.vertices;if(w.length<3)return a;if(i++,i>h)return console.warn("quickDecomp: max level ("+h+") reached."),a;for(var x=0;x<this.vertices.length;++x)if(v.isReflex(x)){b.push(v.vertices[x]),m=n=Number.MAX_VALUE;for(var y=0;y<this.vertices.length;++y)f.left(v.at(x-1),v.at(x),v.at(y))&&f.rightOn(v.at(x-1),v.at(x),v.at(y-1))&&(l=d(v.at(x-1),v.at(x),v.at(y),v.at(y-1)),f.right(v.at(x+1),v.at(x),l)&&(o=f.sqdist(v.vertices[x],l),n>o&&(n=o,k=l,r=y))),f.left(v.at(x+1),v.at(x),v.at(y+1))&&f.rightOn(v.at(x+1),v.at(x),v.at(y))&&(l=d(v.at(x+1),v.at(x),v.at(y),v.at(y+1)),f.left(v.at(x-1),v.at(x),l)&&(o=f.sqdist(v.vertices[x],l),m>o&&(m=o,j=l,q=y)));if(r==(q+1)%this.vertices.length)l[0]=(k[0]+j[0])/2,l[1]=(k[1]+j[1])/2,e.push(l),q>x?(t.append(v,x,q+1),t.vertices.push(l),u.vertices.push(l),0!=r&&u.append(v,r,v.vertices.length),u.append(v,0,x+1)):(0!=x&&t.append(v,x,v.vertices.length),t.append(v,0,q+1),t.vertices.push(l),u.vertices.push(l),u.append(v,r,x+1));else{if(r>q&&(q+=this.vertices.length),p=Number.MAX_VALUE,r>q)return a;for(var y=r;q>=y;++y)f.leftOn(v.at(x-1),v.at(x),v.at(y))&&f.rightOn(v.at(x+1),v.at(x),v.at(y))&&(o=f.sqdist(v.at(x),v.at(y)),p>o&&(p=o,s=y%this.vertices.length));s>x?(t.append(v,x,s+1),0!=s&&u.append(v,s,w.length),u.append(v,0,x+1)):(0!=x&&t.append(v,x,w.length),t.append(v,0,s+1),u.append(v,s,x+1))}return t.vertices.length<u.vertices.length?(t.quickDecomp(a,b,e,g,h,i),u.quickDecomp(a,b,e,g,h,i)):(u.quickDecomp(a,b,e,g,h,i),t.quickDecomp(a,b,e,g,h,i)),a}return a.push(this),a},c.prototype.removeCollinearPoints=function(a){for(var b=0,c=this.vertices.length-1;this.vertices.length>3&&c>=0;--c)f.collinear(this.at(c-1),this.at(c),this.at(c+1),a)&&(this.vertices.splice(c%this.vertices.length,1),c--,b++);return b}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(a,b){function c(){}b.exports=c,c.eq=function(a,b,c){return c=c||0,Math.abs(a-b)<c}},{}],5:[function(a,b){b.exports={Polygon:a("./Polygon"),Point:a("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(a,b){b.exports={name:"p2",version:"0.7.0",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <schteppe@gmail.com> (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.0"}}},{}],7:[function(a,b){function c(a){this.lowerBound=d.create(),a&&a.lowerBound&&d.copy(this.lowerBound,a.lowerBound),this.upperBound=d.create(),a&&a.upperBound&&d.copy(this.upperBound,a.upperBound)}{var d=a("../math/vec2");a("../utils/Utils")}b.exports=c;var e=d.create();c.prototype.setFromPoints=function(a,b,c,f){var g=this.lowerBound,h=this.upperBound;"number"!=typeof c&&(c=0),0!==c?d.rotate(g,a[0],c):d.copy(g,a[0]),d.copy(h,g);for(var i=Math.cos(c),j=Math.sin(c),k=1;k<a.length;k++){var l=a[k];if(0!==c){var m=l[0],n=l[1];e[0]=i*m-j*n,e[1]=j*m+i*n,l=e}for(var o=0;2>o;o++)l[o]>h[o]&&(h[o]=l[o]),l[o]<g[o]&&(g[o]=l[o])}b&&(d.add(this.lowerBound,this.lowerBound,b),d.add(this.upperBound,this.upperBound,b)),f&&(this.lowerBound[0]-=f,this.lowerBound[1]-=f,this.upperBound[0]+=f,this.upperBound[1]+=f)},c.prototype.copy=function(a){d.copy(this.lowerBound,a.lowerBound),d.copy(this.upperBound,a.upperBound)},c.prototype.extend=function(a){for(var b=2;b--;){var c=a.lowerBound[b];this.lowerBound[b]>c&&(this.lowerBound[b]=c);var d=a.upperBound[b];this.upperBound[b]<d&&(this.upperBound[b]=d)}},c.prototype.overlaps=function(a){var b=this.lowerBound,c=this.upperBound,d=a.lowerBound,e=a.upperBound;return(d[0]<=c[0]&&c[0]<=e[0]||b[0]<=e[0]&&e[0]<=c[0])&&(d[1]<=c[1]&&c[1]<=e[1]||b[1]<=e[1]&&e[1]<=c[1])},c.prototype.containsPoint=function(a){var b=this.lowerBound,c=this.upperBound;return b[0]<=a[0]&&a[0]<=c[0]&&b[1]<=a[1]&&a[1]<=c[1]},c.prototype.overlapsRay=function(a){var b=1/a.direction[0],c=1/a.direction[1],d=(this.lowerBound[0]-a.from[0])*b,e=(this.upperBound[0]-a.from[0])*b,f=(this.lowerBound[1]-a.from[1])*c,g=(this.upperBound[1]-a.from[1])*c,h=Math.max(Math.max(Math.min(d,e),Math.min(f,g))),i=Math.min(Math.min(Math.max(d,e),Math.max(f,g)));return 0>i?-1:h>i?-1:h}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(a,b){function c(a){this.type=a,this.result=[],this.world=null,this.boundingVolumeType=c.AABB}var d=a("../math/vec2"),e=a("../objects/Body");b.exports=c,c.AABB=1,c.BOUNDING_CIRCLE=2,c.prototype.setWorld=function(a){this.world=a},c.prototype.getCollisionPairs=function(){};var f=d.create();c.boundingRadiusCheck=function(a,b){d.sub(f,a.position,b.position);var c=d.squaredLength(f),e=a.boundingRadius+b.boundingRadius;return e*e>=c},c.aabbCheck=function(a,b){return a.getAABB().overlaps(b.getAABB())},c.prototype.boundingVolumeCheck=function(a,b){var d;switch(this.boundingVolumeType){case c.BOUNDING_CIRCLE:d=c.boundingRadiusCheck(a,b);break;case c.AABB:d=c.aabbCheck(a,b);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return d},c.canCollide=function(a,b){var c=e.KINEMATIC,d=e.STATIC;return a.type===d&&b.type===d?!1:a.type===c&&b.type===d||a.type===d&&b.type===c?!1:a.type===c&&b.type===c?!1:a.sleepState===e.SLEEPING&&b.sleepState===e.SLEEPING?!1:a.sleepState===e.SLEEPING&&b.type===d||b.sleepState===e.SLEEPING&&a.type===d?!1:!0},c.NAIVE=1,c.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(a,b){function c(){d.call(this,d.NAIVE)}{var d=(a("../shapes/Circle"),a("../shapes/Plane"),a("../shapes/Shape"),a("../shapes/Particle"),a("../collision/Broadphase"));a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.getCollisionPairs=function(a){var b=a.bodies,c=this.result;c.length=0;for(var e=0,f=b.length;e!==f;e++)for(var g=b[e],h=0;e>h;h++){var i=b[h];d.canCollide(g,i)&&this.boundingVolumeCheck(g,i)&&c.push(g,i)}return c},c.prototype.aabbQuery=function(a,b,c){c=c||[];for(var d=a.bodies,e=0;e<d.length;e++){var f=d[e];f.aabbNeedsUpdate&&f.updateAABB(),f.aabb.overlaps(b)&&c.push(f)}return c}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(a,b){function c(){this.contactEquations=[],this.frictionEquations=[],this.enableFriction=!0,this.enabledEquations=!0,this.slipForce=10,this.frictionCoefficient=.3,this.surfaceVelocity=0,this.contactEquationPool=new j({size:32}),this.frictionEquationPool=new k({size:64}),this.restitution=0,this.stiffness=m.DEFAULT_STIFFNESS,this.relaxation=m.DEFAULT_RELAXATION,this.frictionStiffness=m.DEFAULT_STIFFNESS,this.frictionRelaxation=m.DEFAULT_RELAXATION,this.enableFrictionReduction=!0,this.collidingBodiesLastStep=new l,this.contactSkinSize=.01}function d(a,b){f.set(a.vertices[0],.5*-b.length,-b.radius),f.set(a.vertices[1],.5*b.length,-b.radius),f.set(a.vertices[2],.5*b.length,b.radius),f.set(a.vertices[3],.5*-b.length,b.radius)}function e(a,b,c,d){for(var e=S,i=T,j=U,k=V,l=a,m=b.vertices,n=null,o=0;o!==m.length+1;o++){var p=m[o%m.length],q=m[(o+1)%m.length];f.rotate(e,p,d),f.rotate(i,q,d),h(e,e,c),h(i,i,c),g(j,e,l),g(k,i,l);var r=f.crossLength(j,k);if(null===n&&(n=r),0>=r*n)return!1;n=r}return!0}var f=a("../math/vec2"),g=f.sub,h=f.add,i=f.dot,j=(a("../utils/Utils"),a("../utils/ContactEquationPool")),k=a("../utils/FrictionEquationPool"),l=a("../utils/TupleDictionary"),m=a("../equations/Equation"),n=(a("../equations/ContactEquation"),a("../equations/FrictionEquation"),a("../shapes/Circle")),o=a("../shapes/Convex"),p=a("../shapes/Shape"),q=(a("../objects/Body"),a("../shapes/Box"));b.exports=c;var r=f.fromValues(0,1),s=f.fromValues(0,0),t=f.fromValues(0,0),u=f.fromValues(0,0),v=f.fromValues(0,0),w=f.fromValues(0,0),x=f.fromValues(0,0),y=f.fromValues(0,0),z=f.fromValues(0,0),A=f.fromValues(0,0),B=f.fromValues(0,0),C=f.fromValues(0,0),D=f.fromValues(0,0),E=f.fromValues(0,0),F=f.fromValues(0,0),G=f.fromValues(0,0),H=f.fromValues(0,0),I=f.fromValues(0,0),J=f.fromValues(0,0),K=[],L=f.create(),M=f.create();c.prototype.bodiesOverlap=function(a,b){for(var c=L,d=M,e=0,f=a.shapes.length;e!==f;e++){var g=a.shapes[e];a.toWorldFrame(c,g.position);for(var h=0,i=b.shapes.length;h!==i;h++){var j=b.shapes[h];if(b.toWorldFrame(d,j.position),this[g.type|j.type](a,g,c,g.angle+a.angle,b,j,d,j.angle+b.angle,!0))return!0}}return!1},c.prototype.collidedLastStep=function(a,b){var c=0|a.id,d=0|b.id;return!!this.collidingBodiesLastStep.get(c,d)},c.prototype.reset=function(){this.collidingBodiesLastStep.reset();for(var a=this.contactEquations,b=a.length;b--;){var c=a[b],d=c.bodyA.id,e=c.bodyB.id;this.collidingBodiesLastStep.set(d,e,!0)}for(var f=this.contactEquations,g=this.frictionEquations,h=0;h<f.length;h++)this.contactEquationPool.release(f[h]);for(var h=0;h<g.length;h++)this.frictionEquationPool.release(g[h]);this.contactEquations.length=this.frictionEquations.length=0},c.prototype.createContactEquation=function(a,b,c,d){var e=this.contactEquationPool.get();return e.bodyA=a,e.bodyB=b,e.shapeA=c,e.shapeB=d,e.restitution=this.restitution,e.firstImpact=!this.collidedLastStep(a,b),e.stiffness=this.stiffness,e.relaxation=this.relaxation,e.needsUpdate=!0,e.enabled=this.enabledEquations,e.offset=this.contactSkinSize,e},c.prototype.createFrictionEquation=function(a,b,c,d){var e=this.frictionEquationPool.get();return e.bodyA=a,e.bodyB=b,e.shapeA=c,e.shapeB=d,e.setSlipForce(this.slipForce),e.frictionCoefficient=this.frictionCoefficient,e.relativeVelocity=this.surfaceVelocity,e.enabled=this.enabledEquations,e.needsUpdate=!0,e.stiffness=this.frictionStiffness,e.relaxation=this.frictionRelaxation,e.contactEquations.length=0,e},c.prototype.createFrictionFromContact=function(a){var b=this.createFrictionEquation(a.bodyA,a.bodyB,a.shapeA,a.shapeB);return f.copy(b.contactPointA,a.contactPointA),f.copy(b.contactPointB,a.contactPointB),f.rotate90cw(b.t,a.normalA),b.contactEquations.push(a),b},c.prototype.createFrictionFromAverage=function(a){{var b=this.contactEquations[this.contactEquations.length-1],c=this.createFrictionEquation(b.bodyA,b.bodyB,b.shapeA,b.shapeB),d=b.bodyA;b.bodyB}f.set(c.contactPointA,0,0),f.set(c.contactPointB,0,0),f.set(c.t,0,0);for(var e=0;e!==a;e++)b=this.contactEquations[this.contactEquations.length-1-e],b.bodyA===d?(f.add(c.t,c.t,b.normalA),f.add(c.contactPointA,c.contactPointA,b.contactPointA),f.add(c.contactPointB,c.contactPointB,b.contactPointB)):(f.sub(c.t,c.t,b.normalA),f.add(c.contactPointA,c.contactPointA,b.contactPointB),f.add(c.contactPointB,c.contactPointB,b.contactPointA)),c.contactEquations.push(b);var g=1/a;return f.scale(c.contactPointA,c.contactPointA,g),f.scale(c.contactPointB,c.contactPointB,g),f.normalize(c.t,c.t),f.rotate90cw(c.t,c.t),c},c.prototype[p.LINE|p.CONVEX]=c.prototype.convexLine=function(a,b,c,d,e,f,g,h,i){return i?!1:0},c.prototype[p.LINE|p.BOX]=c.prototype.lineBox=function(a,b,c,d,e,f,g,h,i){return i?!1:0};var N=new q({width:1,height:1}),O=f.create();c.prototype[p.CAPSULE|p.CONVEX]=c.prototype[p.CAPSULE|p.BOX]=c.prototype.convexCapsule=function(a,b,c,e,g,h,i,j,k){var l=O;f.set(l,h.length/2,0),f.rotate(l,l,j),f.add(l,l,i);var m=this.circleConvex(g,h,l,j,a,b,c,e,k,h.radius);f.set(l,-h.length/2,0),f.rotate(l,l,j),f.add(l,l,i);var n=this.circleConvex(g,h,l,j,a,b,c,e,k,h.radius);if(k&&(m||n))return!0;var o=N;d(o,h);var p=this.convexConvex(a,b,c,e,g,o,i,j,k);return p+m+n},c.prototype[p.CAPSULE|p.LINE]=c.prototype.lineCapsule=function(a,b,c,d,e,f,g,h,i){return i?!1:0};var P=f.create(),Q=f.create(),R=new q({width:1,height:1});c.prototype[p.CAPSULE|p.CAPSULE]=c.prototype.capsuleCapsule=function(a,b,c,e,g,h,i,j,k){for(var l,m=P,n=Q,o=0,p=0;2>p;p++){f.set(m,(0===p?-1:1)*b.length/2,0),f.rotate(m,m,e),f.add(m,m,c);for(var q=0;2>q;q++){f.set(n,(0===q?-1:1)*h.length/2,0),f.rotate(n,n,j),f.add(n,n,i),this.enableFrictionReduction&&(l=this.enableFriction,this.enableFriction=!1);var r=this.circleCircle(a,b,m,e,g,h,n,j,k,b.radius,h.radius);if(this.enableFrictionReduction&&(this.enableFriction=l),k&&r)return!0;o+=r}}this.enableFrictionReduction&&(l=this.enableFriction,this.enableFriction=!1);var s=R;d(s,b);var t=this.convexCapsule(a,s,c,e,g,h,i,j,k);if(this.enableFrictionReduction&&(this.enableFriction=l),k&&t)return!0;if(o+=t,this.enableFrictionReduction){var l=this.enableFriction;this.enableFriction=!1}d(s,h);var u=this.convexCapsule(g,s,i,j,a,b,c,e,k);return this.enableFrictionReduction&&(this.enableFriction=l),k&&u?!0:(o+=u,this.enableFrictionReduction&&o&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(o)),o)},c.prototype[p.LINE|p.LINE]=c.prototype.lineLine=function(a,b,c,d,e,f,g,h,i){return i?!1:0},c.prototype[p.PLANE|p.LINE]=c.prototype.planeLine=function(a,b,c,d,e,j,k,l,m){var n=s,o=t,p=u,q=v,B=w,C=x,D=y,E=z,F=A,G=K,H=0;f.set(n,-j.length/2,0),f.set(o,j.length/2,0),f.rotate(p,n,l),f.rotate(q,o,l),h(p,p,k),h(q,q,k),f.copy(n,p),f.copy(o,q),g(B,o,n),f.normalize(C,B),f.rotate90cw(F,C),f.rotate(E,r,d),G[0]=n,G[1]=o;for(var I=0;I<G.length;I++){var J=G[I];g(D,J,c);var L=i(D,E);if(0>L){if(m)return!0;var M=this.createContactEquation(a,e,b,j);H++,f.copy(M.normalA,E),f.normalize(M.normalA,M.normalA),f.scale(D,E,L),g(M.contactPointA,J,D),g(M.contactPointA,M.contactPointA,a.position),g(M.contactPointB,J,k),h(M.contactPointB,M.contactPointB,k),g(M.contactPointB,M.contactPointB,e.position),this.contactEquations.push(M),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}return m?!1:(this.enableFrictionReduction||H&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(H)),H)},c.prototype[p.PARTICLE|p.CAPSULE]=c.prototype.particleCapsule=function(a,b,c,d,e,f,g,h,i){return this.circleLine(a,b,c,d,e,f,g,h,i,f.radius,0)},c.prototype[p.CIRCLE|p.LINE]=c.prototype.circleLine=function(a,b,c,d,e,j,k,l,m,n,o){var n=n||0,o="undefined"!=typeof o?o:b.radius,p=s,q=t,r=u,G=v,H=w,I=x,J=y,L=z,M=A,N=B,O=C,P=D,Q=E,R=F,S=K;f.set(L,-j.length/2,0),f.set(M,j.length/2,0),f.rotate(N,L,l),f.rotate(O,M,l),h(N,N,k),h(O,O,k),f.copy(L,N),f.copy(M,O),g(I,M,L),f.normalize(J,I),f.rotate90cw(H,J),g(P,c,L);var T=i(P,H);g(G,L,k),g(Q,c,k);var U=o+n;if(Math.abs(T)<U){f.scale(p,H,T),g(r,c,p),f.scale(q,H,i(H,Q)),f.normalize(q,q),f.scale(q,q,n),h(r,r,q);var V=i(J,r),W=i(J,L),X=i(J,M);if(V>W&&X>V){if(m)return!0;var Y=this.createContactEquation(a,e,b,j);return f.scale(Y.normalA,p,-1),f.normalize(Y.normalA,Y.normalA),f.scale(Y.contactPointA,Y.normalA,o),h(Y.contactPointA,Y.contactPointA,c),g(Y.contactPointA,Y.contactPointA,a.position),g(Y.contactPointB,r,k),h(Y.contactPointB,Y.contactPointB,k),g(Y.contactPointB,Y.contactPointB,e.position),this.contactEquations.push(Y),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Y)),1}}S[0]=L,S[1]=M;for(var Z=0;Z<S.length;Z++){var $=S[Z];if(g(P,$,c),f.squaredLength(P)<Math.pow(U,2)){if(m)return!0;var Y=this.createContactEquation(a,e,b,j);return f.copy(Y.normalA,P),f.normalize(Y.normalA,Y.normalA),f.scale(Y.contactPointA,Y.normalA,o),h(Y.contactPointA,Y.contactPointA,c),g(Y.contactPointA,Y.contactPointA,a.position),g(Y.contactPointB,$,k),f.scale(R,Y.normalA,-n),h(Y.contactPointB,Y.contactPointB,R),h(Y.contactPointB,Y.contactPointB,k),g(Y.contactPointB,Y.contactPointB,e.position),this.contactEquations.push(Y),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Y)),1}}return 0},c.prototype[p.CIRCLE|p.CAPSULE]=c.prototype.circleCapsule=function(a,b,c,d,e,f,g,h,i){return this.circleLine(a,b,c,d,e,f,g,h,i,f.radius)},c.prototype[p.CIRCLE|p.CONVEX]=c.prototype[p.CIRCLE|p.BOX]=c.prototype.circleConvex=function(a,b,c,d,i,j,k,l,m,n){for(var n="number"==typeof n?n:b.radius,o=s,p=t,q=u,r=v,x=w,y=B,z=C,A=E,D=F,I=G,J=H,K=!1,L=Number.MAX_VALUE,M=j.vertices,N=0;N!==M.length+1;N++){var O=M[N%M.length],P=M[(N+1)%M.length];if(f.rotate(o,O,l),f.rotate(p,P,l),h(o,o,k),h(p,p,k),g(q,p,o),f.normalize(r,q),f.rotate90cw(x,r),f.scale(D,x,-b.radius),h(D,D,c),e(D,j,k,l)){f.sub(I,o,D);var Q=Math.abs(f.dot(I,x));L>Q&&(f.copy(J,D),L=Q,f.scale(A,x,Q),f.add(A,A,D),K=!0)}}if(K){if(m)return!0;var R=this.createContactEquation(a,i,b,j);return f.sub(R.normalA,J,c),f.normalize(R.normalA,R.normalA),f.scale(R.contactPointA,R.normalA,n),h(R.contactPointA,R.contactPointA,c),g(R.contactPointA,R.contactPointA,a.position),g(R.contactPointB,A,k),h(R.contactPointB,R.contactPointB,k),g(R.contactPointB,R.contactPointB,i.position),this.contactEquations.push(R),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(R)),1}if(n>0)for(var N=0;N<M.length;N++){var S=M[N];if(f.rotate(z,S,l),h(z,z,k),g(y,z,c),f.squaredLength(y)<Math.pow(n,2)){if(m)return!0;var R=this.createContactEquation(a,i,b,j);return f.copy(R.normalA,y),f.normalize(R.normalA,R.normalA),f.scale(R.contactPointA,R.normalA,n),h(R.contactPointA,R.contactPointA,c),g(R.contactPointA,R.contactPointA,a.position),g(R.contactPointB,z,k),h(R.contactPointB,R.contactPointB,k),g(R.contactPointB,R.contactPointB,i.position),this.contactEquations.push(R),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(R)),1}}return 0};var S=f.create(),T=f.create(),U=f.create(),V=f.create();c.prototype[p.PARTICLE|p.CONVEX]=c.prototype[p.PARTICLE|p.BOX]=c.prototype.particleConvex=function(a,b,c,d,j,k,l,m,n){var o=s,p=t,q=u,r=v,z=w,A=x,C=y,D=B,F=E,G=I,H=J,K=Number.MAX_VALUE,L=!1,M=k.vertices;if(!e(c,k,l,m))return 0;if(n)return!0;for(var N=0;N!==M.length+1;N++){var O=M[N%M.length],P=M[(N+1)%M.length];f.rotate(o,O,m),f.rotate(p,P,m),h(o,o,l),h(p,p,l),g(q,p,o),f.normalize(r,q),f.rotate90cw(z,r),g(D,c,o);{i(D,z)}g(A,o,l),g(C,c,l),f.sub(G,o,c);var Q=Math.abs(f.dot(G,z));K>Q&&(K=Q,f.scale(F,z,Q),f.add(F,F,c),f.copy(H,z),L=!0)}if(L){var R=this.createContactEquation(a,j,b,k);return f.scale(R.normalA,H,-1),f.normalize(R.normalA,R.normalA),f.set(R.contactPointA,0,0),h(R.contactPointA,R.contactPointA,c),g(R.contactPointA,R.contactPointA,a.position),g(R.contactPointB,F,l),h(R.contactPointB,R.contactPointB,l),g(R.contactPointB,R.contactPointB,j.position),this.contactEquations.push(R),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(R)),1}return 0},c.prototype[p.CIRCLE]=c.prototype.circleCircle=function(a,b,c,d,e,i,j,k,l,m,n){var o=s,m=m||b.radius,n=n||i.radius;g(o,c,j);var p=m+n;if(f.squaredLength(o)>Math.pow(p,2))return 0;if(l)return!0;var q=this.createContactEquation(a,e,b,i);return g(q.normalA,j,c),f.normalize(q.normalA,q.normalA),f.scale(q.contactPointA,q.normalA,m),f.scale(q.contactPointB,q.normalA,-n),h(q.contactPointA,q.contactPointA,c),g(q.contactPointA,q.contactPointA,a.position),h(q.contactPointB,q.contactPointB,j),g(q.contactPointB,q.contactPointB,e.position),this.contactEquations.push(q),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(q)),1},c.prototype[p.PLANE|p.CONVEX]=c.prototype[p.PLANE|p.BOX]=c.prototype.planeConvex=function(a,b,c,d,e,j,k,l,m){var n=s,o=t,p=u,q=0;f.rotate(o,r,d);for(var v=0;v!==j.vertices.length;v++){var w=j.vertices[v];if(f.rotate(n,w,l),h(n,n,k),g(p,n,c),i(p,o)<=0){if(m)return!0;q++;var x=this.createContactEquation(a,e,b,j);g(p,n,c),f.copy(x.normalA,o);var y=i(p,x.normalA);f.scale(p,x.normalA,y),g(x.contactPointB,n,e.position),g(x.contactPointA,n,p),g(x.contactPointA,x.contactPointA,a.position),this.contactEquations.push(x),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(x))}}return this.enableFrictionReduction&&this.enableFriction&&q&&this.frictionEquations.push(this.createFrictionFromAverage(q)),q},c.prototype[p.PARTICLE|p.PLANE]=c.prototype.particlePlane=function(a,b,c,d,e,h,j,k,l){var m=s,n=t;k=k||0,g(m,c,j),f.rotate(n,r,k);var o=i(m,n);if(o>0)return 0;if(l)return!0;var p=this.createContactEquation(e,a,h,b);return f.copy(p.normalA,n),f.scale(m,p.normalA,o),g(p.contactPointA,c,m),g(p.contactPointA,p.contactPointA,e.position),g(p.contactPointB,c,a.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1},c.prototype[p.CIRCLE|p.PARTICLE]=c.prototype.circleParticle=function(a,b,c,d,e,i,j,k,l){var m=s;if(g(m,j,c),f.squaredLength(m)>Math.pow(b.radius,2))return 0;if(l)return!0;var n=this.createContactEquation(a,e,b,i);return f.copy(n.normalA,m),f.normalize(n.normalA,n.normalA),f.scale(n.contactPointA,n.normalA,b.radius),h(n.contactPointA,n.contactPointA,c),g(n.contactPointA,n.contactPointA,a.position),g(n.contactPointB,j,e.position),this.contactEquations.push(n),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(n)),1};{var W=new n({radius:1}),X=f.create(),Y=f.create();f.create()}c.prototype[p.PLANE|p.CAPSULE]=c.prototype.planeCapsule=function(a,b,c,d,e,g,i,j,k){var l=X,m=Y,n=W;f.set(l,-g.length/2,0),f.rotate(l,l,j),h(l,l,i),f.set(m,g.length/2,0),f.rotate(m,m,j),h(m,m,i),n.radius=g.radius;var o;this.enableFrictionReduction&&(o=this.enableFriction,this.enableFriction=!1);var p=this.circlePlane(e,n,l,0,a,b,c,d,k),q=this.circlePlane(e,n,m,0,a,b,c,d,k);if(this.enableFrictionReduction&&(this.enableFriction=o),k)return p||q;var r=p+q;return this.enableFrictionReduction&&r&&this.frictionEquations.push(this.createFrictionFromAverage(r)),r},c.prototype[p.CIRCLE|p.PLANE]=c.prototype.circlePlane=function(a,b,c,d,e,j,k,l,m){var n=a,o=b,p=c,q=e,v=k,w=l;w=w||0;var x=s,y=t,z=u;g(x,p,v),f.rotate(y,r,w);var A=i(y,x);if(A>o.radius)return 0;if(m)return!0;var B=this.createContactEquation(q,n,j,b);return f.copy(B.normalA,y),f.scale(B.contactPointB,B.normalA,-o.radius),h(B.contactPointB,B.contactPointB,p),g(B.contactPointB,B.contactPointB,n.position),f.scale(z,B.normalA,A),g(B.contactPointA,x,z),h(B.contactPointA,B.contactPointA,v),g(B.contactPointA,B.contactPointA,q.position),this.contactEquations.push(B),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(B)),1},c.prototype[p.CONVEX]=c.prototype[p.CONVEX|p.BOX]=c.prototype[p.BOX]=c.prototype.convexConvex=function(a,b,d,e,j,k,l,m,n,o){var p=s,q=t,r=u,x=v,B=w,C=y,D=z,E=A,F=0,o="number"==typeof o?o:0,G=c.findSeparatingAxis(b,d,e,k,l,m,p);if(!G)return 0;g(D,l,d),i(p,D)>0&&f.scale(p,p,-1);var H=c.getClosestEdge(b,e,p,!0),I=c.getClosestEdge(k,m,p);if(-1===H||-1===I)return 0;for(var J=0;2>J;J++){var K=H,L=I,M=b,N=k,O=d,P=l,Q=e,R=m,S=a,T=j;if(0===J){var U;U=K,K=L,L=U,U=M,M=N,N=U,U=O,O=P,P=U,U=Q,Q=R,R=U,U=S,S=T,T=U}for(var V=L;L+2>V;V++){var W=N.vertices[(V+N.vertices.length)%N.vertices.length];f.rotate(q,W,R),h(q,q,P);for(var X=0,Y=K-1;K+2>Y;Y++){var Z=M.vertices[(Y+M.vertices.length)%M.vertices.length],$=M.vertices[(Y+1+M.vertices.length)%M.vertices.length];f.rotate(r,Z,Q),f.rotate(x,$,Q),h(r,r,O),h(x,x,O),g(B,x,r),f.rotate90cw(E,B),f.normalize(E,E),g(D,q,r);var _=i(E,D);(Y===K&&o>=_||Y!==K&&0>=_)&&X++}if(X>=3){if(n)return!0;var ab=this.createContactEquation(S,T,M,N);F++;var Z=M.vertices[K%M.vertices.length],$=M.vertices[(K+1)%M.vertices.length];f.rotate(r,Z,Q),f.rotate(x,$,Q),h(r,r,O),h(x,x,O),g(B,x,r),f.rotate90cw(ab.normalA,B),f.normalize(ab.normalA,ab.normalA),g(D,q,r);var _=i(ab.normalA,D);f.scale(C,ab.normalA,_),g(ab.contactPointA,q,O),g(ab.contactPointA,ab.contactPointA,C),h(ab.contactPointA,ab.contactPointA,O),g(ab.contactPointA,ab.contactPointA,S.position),g(ab.contactPointB,q,P),h(ab.contactPointB,ab.contactPointB,P),g(ab.contactPointB,ab.contactPointB,T.position),this.contactEquations.push(ab),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(ab))}}}return this.enableFrictionReduction&&this.enableFriction&&F&&this.frictionEquations.push(this.createFrictionFromAverage(F)),F};var Z=f.fromValues(0,0);c.projectConvexOntoAxis=function(a,b,c,d,e){var g,h,j=null,k=null,l=Z;f.rotate(l,d,-c);for(var m=0;m<a.vertices.length;m++)g=a.vertices[m],h=i(g,l),(null===j||h>j)&&(j=h),(null===k||k>h)&&(k=h);if(k>j){var n=k;k=j,j=n}var o=i(b,d);f.set(e,k+o,j+o)};var $=f.fromValues(0,0),_=f.fromValues(0,0),ab=f.fromValues(0,0),bb=f.fromValues(0,0),cb=f.fromValues(0,0),db=f.fromValues(0,0);c.findSeparatingAxis=function(a,b,d,e,h,i,j){var k=null,l=!1,m=!1,n=$,o=_,p=ab,r=bb,s=cb,t=db;if(a instanceof q&&e instanceof q)for(var u=0;2!==u;u++){var v=a,w=d;1===u&&(v=e,w=i);for(var x=0;2!==x;x++){0===x?f.set(r,0,1):1===x&&f.set(r,1,0),0!==w&&f.rotate(r,r,w),c.projectConvexOntoAxis(a,b,d,r,s),c.projectConvexOntoAxis(e,h,i,r,t);var y=s,z=t,A=!1;s[0]>t[0]&&(z=s,y=t,A=!0);var B=z[0]-y[1];l=0>=B,(null===k||B>k)&&(f.copy(j,r),k=B,m=l)}}else for(var u=0;2!==u;u++){var v=a,w=d;1===u&&(v=e,w=i);for(var x=0;x!==v.vertices.length;x++){f.rotate(o,v.vertices[x],w),f.rotate(p,v.vertices[(x+1)%v.vertices.length],w),g(n,p,o),f.rotate90cw(r,n),f.normalize(r,r),c.projectConvexOntoAxis(a,b,d,r,s),c.projectConvexOntoAxis(e,h,i,r,t);var y=s,z=t,A=!1;s[0]>t[0]&&(z=s,y=t,A=!0);var B=z[0]-y[1];l=0>=B,(null===k||B>k)&&(f.copy(j,r),k=B,m=l)}}return m};var eb=f.fromValues(0,0),fb=f.fromValues(0,0),gb=f.fromValues(0,0);c.getClosestEdge=function(a,b,c,d){var e=eb,h=fb,j=gb;f.rotate(e,c,-b),d&&f.scale(e,e,-1);for(var k=-1,l=a.vertices.length,m=-1,n=0;n!==l;n++){g(h,a.vertices[(n+1)%l],a.vertices[n%l]),f.rotate90cw(j,h),f.normalize(j,j);var o=i(j,e);(-1===k||o>m)&&(k=n%l,m=o)}return k};var hb=f.create(),ib=f.create(),jb=f.create(),kb=f.create(),lb=f.create(),mb=f.create(),nb=f.create();c.prototype[p.CIRCLE|p.HEIGHTFIELD]=c.prototype.circleHeightfield=function(a,b,c,d,e,i,j,k,l,m){var n=i.heights,m=m||b.radius,o=i.elementWidth,p=ib,q=hb,r=lb,s=nb,t=mb,u=jb,v=kb,w=Math.floor((c[0]-m-j[0])/o),x=Math.ceil((c[0]+m-j[0])/o);0>w&&(w=0),x>=n.length&&(x=n.length-1);for(var y=n[w],z=n[x],A=w;x>A;A++)n[A]<z&&(z=n[A]),n[A]>y&&(y=n[A]);if(c[1]-m>y)return l?!1:0;for(var B=!1,A=w;x>A;A++){f.set(u,A*o,n[A]),f.set(v,(A+1)*o,n[A+1]),f.add(u,u,j),f.add(v,v,j),f.sub(t,v,u),f.rotate(t,t,Math.PI/2),f.normalize(t,t),f.scale(q,t,-m),f.add(q,q,c),f.sub(p,q,u);var C=f.dot(p,t);if(q[0]>=u[0]&&q[0]<v[0]&&0>=C){if(l)return!0;B=!0,f.scale(p,t,-C),f.add(r,q,p),f.copy(s,t);var D=this.createContactEquation(e,a,i,b);f.copy(D.normalA,s),f.scale(D.contactPointB,D.normalA,-m),h(D.contactPointB,D.contactPointB,c),g(D.contactPointB,D.contactPointB,a.position),f.copy(D.contactPointA,r),f.sub(D.contactPointA,D.contactPointA,e.position),this.contactEquations.push(D),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(D))}}if(B=!1,m>0)for(var A=w;x>=A;A++)if(f.set(u,A*o,n[A]),f.add(u,u,j),f.sub(p,c,u),f.squaredLength(p)<Math.pow(m,2)){if(l)return!0;B=!0;var D=this.createContactEquation(e,a,i,b);
+f.copy(D.normalA,p),f.normalize(D.normalA,D.normalA),f.scale(D.contactPointB,D.normalA,-m),h(D.contactPointB,D.contactPointB,c),g(D.contactPointB,D.contactPointB,a.position),g(D.contactPointA,u,j),h(D.contactPointA,D.contactPointA,j),g(D.contactPointA,D.contactPointA,e.position),this.contactEquations.push(D),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(D))}return B?1:0};var ob=f.create(),pb=f.create(),qb=f.create(),rb=new o({vertices:[f.create(),f.create(),f.create(),f.create()]});c.prototype[p.BOX|p.HEIGHTFIELD]=c.prototype[p.CONVEX|p.HEIGHTFIELD]=c.prototype.convexHeightfield=function(a,b,c,d,e,g,h,i,j){var k=g.heights,l=g.elementWidth,m=ob,n=pb,o=qb,p=rb,q=Math.floor((a.aabb.lowerBound[0]-h[0])/l),r=Math.ceil((a.aabb.upperBound[0]-h[0])/l);0>q&&(q=0),r>=k.length&&(r=k.length-1);for(var s=k[q],t=k[r],u=q;r>u;u++)k[u]<t&&(t=k[u]),k[u]>s&&(s=k[u]);if(a.aabb.lowerBound[1]>s)return j?!1:0;for(var v=0,u=q;r>u;u++){f.set(m,u*l,k[u]),f.set(n,(u+1)*l,k[u+1]),f.add(m,m,h),f.add(n,n,h);var w=100;f.set(o,.5*(n[0]+m[0]),.5*(n[1]+m[1]-w)),f.sub(p.vertices[0],n,o),f.sub(p.vertices[1],m,o),f.copy(p.vertices[2],p.vertices[1]),f.copy(p.vertices[3],p.vertices[0]),p.vertices[2][1]-=w,p.vertices[3][1]-=w,v+=this.convexConvex(a,b,c,d,e,p,o,0,j)}return v}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(a,b){function c(a){a=a||{},this.from=a.from?e.fromValues(a.from[0],a.from[1]):e.create(),this.to=a.to?e.fromValues(a.to[0],a.to[1]):e.create(),this.checkCollisionResponse=void 0!==a.checkCollisionResponse?a.checkCollisionResponse:!0,this.skipBackfaces=!!a.skipBackfaces,this.collisionMask=void 0!==a.collisionMask?a.collisionMask:-1,this.collisionGroup=void 0!==a.collisionGroup?a.collisionGroup:-1,this.mode=void 0!==a.mode?a.mode:c.ANY,this.callback=a.callback||function(){},this.direction=e.create(),this.length=1,this.update()}function d(a,b,c){e.sub(g,c,a);var d=e.dot(g,b);return e.scale(h,b,d),e.add(h,h,a),e.squaredDistance(c,h)}b.exports=c;{var e=a("../math/vec2");a("../collision/RaycastResult"),a("../shapes/Shape"),a("../collision/AABB")}c.prototype.constructor=c,c.CLOSEST=1,c.ANY=2,c.ALL=4,c.prototype.update=function(){var a=this.direction;e.sub(a,this.to,this.from),this.length=e.length(a),e.normalize(a,a)},c.prototype.intersectBodies=function(a,b){for(var c=0,d=b.length;!a.shouldStop(this)&&d>c;c++){var e=b[c],f=e.getAABB();(f.overlapsRay(this)>=0||f.containsPoint(this.from))&&this.intersectBody(a,e)}};var f=e.create();c.prototype.intersectBody=function(a,b){var c=this.checkCollisionResponse;if(!c||b.collisionResponse)for(var d=f,g=0,h=b.shapes.length;h>g;g++){var i=b.shapes[g];if((!c||i.collisionResponse)&&0!==(this.collisionGroup&i.collisionMask)&&0!==(i.collisionGroup&this.collisionMask)){e.rotate(d,i.position,b.angle),e.add(d,d,b.position);var j=i.angle+b.angle;if(this.intersectShape(a,i,j,d,b),a.shouldStop(this))break}}},c.prototype.intersectShape=function(a,b,c,e,f){var g=this.from,h=d(g,this.direction,e);h>b.boundingRadius*b.boundingRadius||(this._currentBody=f,this._currentShape=b,b.raycast(a,this,e,c),this._currentBody=this._currentShape=null)},c.prototype.getAABB=function(a){var b=this.to,c=this.from;e.set(a.lowerBound,Math.min(b[0],c[0]),Math.min(b[1],c[1])),e.set(a.upperBound,Math.max(b[0],c[0]),Math.max(b[1],c[1]))};e.create();c.prototype.reportIntersection=function(a,b,d,f){var g=(this.from,this.to,this._currentShape),h=this._currentBody;if(!(this.skipBackfaces&&e.dot(d,this.direction)>0))switch(this.mode){case c.ALL:a.set(d,g,h,b,f),this.callback(a);break;case c.CLOSEST:(b<a.fraction||!a.hasHit())&&a.set(d,g,h,b,f);break;case c.ANY:a.set(d,g,h,b,f)}};var g=e.create(),h=e.create()},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(a,b){function c(){this.normal=d.create(),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1}var d=a("../math/vec2"),e=a("../collision/Ray");b.exports=c,c.prototype.reset=function(){d.set(this.normal,0,0),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1},c.prototype.getHitDistance=function(a){return d.distance(a.from,a.to)*this.fraction},c.prototype.hasHit=function(){return-1!==this.fraction},c.prototype.getHitPoint=function(a,b){d.lerp(a,b.from,b.to,this.fraction)},c.prototype.stop=function(){this.isStopped=!0},c.prototype.shouldStop=function(a){return this.isStopped||-1!==this.fraction&&a.mode===e.ANY},c.prototype.set=function(a,b,c,e,f){d.copy(this.normal,a),this.shape=b,this.body=c,this.fraction=e,this.faceIndex=f}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(a,b){function c(){e.call(this,e.SAP),this.axisList=[],this.axisIndex=0;var a=this;this._addBodyHandler=function(b){a.axisList.push(b.body)},this._removeBodyHandler=function(b){var c=a.axisList.indexOf(b.body);-1!==c&&a.axisList.splice(c,1)}}var d=a("../utils/Utils"),e=a("../collision/Broadphase");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.setWorld=function(a){this.axisList.length=0,d.appendArray(this.axisList,a.bodies),a.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler),a.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler),this.world=a},c.sortAxisList=function(a,b){b=0|b;for(var c=1,d=a.length;d>c;c++){for(var e=a[c],f=c-1;f>=0&&!(a[f].aabb.lowerBound[b]<=e.aabb.lowerBound[b]);f--)a[f+1]=a[f];a[f+1]=e}return a},c.prototype.sortList=function(){var a=this.axisList,b=this.axisIndex;c.sortAxisList(a,b)},c.prototype.getCollisionPairs=function(){var a=this.axisList,b=this.result,c=this.axisIndex;b.length=0;for(var d=a.length;d--;){var f=a[d];f.aabbNeedsUpdate&&f.updateAABB()}this.sortList();for(var g=0,h=0|a.length;g!==h;g++)for(var i=a[g],j=g+1;h>j;j++){var k=a[j],l=k.aabb.lowerBound[c]<=i.aabb.upperBound[c];if(!l)break;e.canCollide(i,k)&&this.boundingVolumeCheck(i,k)&&b.push(i,k)}return b},c.prototype.aabbQuery=function(a,b,c){c=c||[],this.sortList();var d=this.axisIndex,e="x";1===d&&(e="y"),2===d&&(e="z");for(var f=this.axisList,g=(b.lowerBound[e],b.upperBound[e],0);g<f.length;g++){var h=f[g];h.aabbNeedsUpdate&&h.updateAABB(),h.aabb.overlaps(b)&&c.push(h)}return c}},{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(a,b){function c(a,b,c,e){this.type=c,e=d.defaults(e,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=a,this.bodyB=b,this.collideConnected=e.collideConnected,e.wakeUpBodies&&(a&&a.wakeUp(),b&&b.wakeUp())}b.exports=c;var d=a("../utils/Utils");c.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},c.DISTANCE=1,c.GEAR=2,c.LOCK=3,c.PRISMATIC=4,c.REVOLUTE=5,c.prototype.setStiffness=function(a){for(var b=this.equations,c=0;c!==b.length;c++){var d=b[c];d.stiffness=a,d.needsUpdate=!0}},c.prototype.setRelaxation=function(a){for(var b=this.equations,c=0;c!==b.length;c++){var d=b[c];d.relaxation=a,d.needsUpdate=!0}}},{"../utils/Utils":57}],15:[function(a,b){function c(a,b,c){c=g.defaults(c,{localAnchorA:[0,0],localAnchorB:[0,0]}),d.call(this,a,b,d.DISTANCE,c),this.localAnchorA=f.fromValues(c.localAnchorA[0],c.localAnchorA[1]),this.localAnchorB=f.fromValues(c.localAnchorB[0],c.localAnchorB[1]);var h=this.localAnchorA,i=this.localAnchorB;if(this.distance=0,"number"==typeof c.distance)this.distance=c.distance;else{var j=f.create(),k=f.create(),l=f.create();f.rotate(j,h,a.angle),f.rotate(k,i,b.angle),f.add(l,b.position,k),f.sub(l,l,j),f.sub(l,l,a.position),this.distance=f.length(l)}var m;m="undefined"==typeof c.maxForce?Number.MAX_VALUE:c.maxForce;var n=new e(a,b,-m,m);this.equations=[n],this.maxForce=m;var l=f.create(),o=f.create(),p=f.create(),q=this;n.computeGq=function(){var a=this.bodyA,b=this.bodyB,c=a.position,d=b.position;return f.rotate(o,h,a.angle),f.rotate(p,i,b.angle),f.add(l,d,p),f.sub(l,l,o),f.sub(l,l,c),f.length(l)-q.distance},this.setMaxForce(m),this.upperLimitEnabled=!1,this.upperLimit=1,this.lowerLimitEnabled=!1,this.lowerLimit=0,this.position=0}var d=a("./Constraint"),e=a("../equations/Equation"),f=a("../math/vec2"),g=a("../utils/Utils");b.exports=c,c.prototype=new d,c.prototype.constructor=c;var h=f.create(),i=f.create(),j=f.create();c.prototype.update=function(){var a=this.equations[0],b=this.bodyA,c=this.bodyB,d=(this.distance,b.position),e=c.position,g=this.equations[0],k=a.G;f.rotate(i,this.localAnchorA,b.angle),f.rotate(j,this.localAnchorB,c.angle),f.add(h,e,j),f.sub(h,h,i),f.sub(h,h,d),this.position=f.length(h);var l=!1;if(this.upperLimitEnabled&&this.position>this.upperLimit&&(g.maxForce=0,g.minForce=-this.maxForce,this.distance=this.upperLimit,l=!0),this.lowerLimitEnabled&&this.position<this.lowerLimit&&(g.maxForce=this.maxForce,g.minForce=0,this.distance=this.lowerLimit,l=!0),(this.lowerLimitEnabled||this.upperLimitEnabled)&&!l)return void(g.enabled=!1);g.enabled=!0,f.normalize(h,h);var m=f.crossLength(i,h),n=f.crossLength(j,h);k[0]=-h[0],k[1]=-h[1],k[2]=-m,k[3]=h[0],k[4]=h[1],k[5]=n},c.prototype.setMaxForce=function(a){var b=this.equations[0];b.minForce=-a,b.maxForce=a},c.prototype.getMaxForce=function(){var a=this.equations[0];return a.maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.GEAR,c),this.ratio=void 0!==c.ratio?c.ratio:1,this.angle=void 0!==c.angle?c.angle:b.angle-this.ratio*a.angle,c.angle=this.angle,c.ratio=this.ratio,this.equations=[new e(a,b,c)],void 0!==c.maxTorque&&this.setMaxTorque(c.maxTorque)}{var d=a("./Constraint"),e=(a("../equations/Equation"),a("../equations/AngleLockEquation"));a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.update=function(){var a=this.equations[0];a.ratio!==this.ratio&&a.setRatio(this.ratio),a.angle=this.angle},c.prototype.setMaxTorque=function(a){this.equations[0].setMaxTorque(a)},c.prototype.getMaxTorque=function(){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.LOCK,c);var g="undefined"==typeof c.maxForce?Number.MAX_VALUE:c.maxForce,h=(c.localAngleB||0,new f(a,b,-g,g)),i=new f(a,b,-g,g),j=new f(a,b,-g,g),k=e.create(),l=e.create(),m=this;h.computeGq=function(){return e.rotate(k,m.localOffsetB,a.angle),e.sub(l,b.position,a.position),e.sub(l,l,k),l[0]},i.computeGq=function(){return e.rotate(k,m.localOffsetB,a.angle),e.sub(l,b.position,a.position),e.sub(l,l,k),l[1]};var n=e.create(),o=e.create();j.computeGq=function(){return e.rotate(n,m.localOffsetB,b.angle-m.localAngleB),e.scale(n,n,-1),e.sub(l,a.position,b.position),e.add(l,l,n),e.rotate(o,n,-Math.PI/2),e.normalize(o,o),e.dot(l,o)},this.localOffsetB=e.create(),c.localOffsetB?e.copy(this.localOffsetB,c.localOffsetB):(e.sub(this.localOffsetB,b.position,a.position),e.rotate(this.localOffsetB,this.localOffsetB,-a.angle)),this.localAngleB=0,this.localAngleB="number"==typeof c.localAngleB?c.localAngleB:b.angle-a.angle,this.equations.push(h,i,j),this.setMaxForce(g)}var d=a("./Constraint"),e=a("../math/vec2"),f=a("../equations/Equation");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.setMaxForce=function(a){for(var b=this.equations,c=0;c<this.equations.length;c++)b[c].maxForce=a,b[c].minForce=-a},c.prototype.getMaxForce=function(){return this.equations[0].maxForce};var g=e.create(),h=e.create(),i=e.create(),j=e.fromValues(1,0),k=e.fromValues(0,1);c.prototype.update=function(){var a=this.equations[0],b=this.equations[1],c=this.equations[2],d=this.bodyA,f=this.bodyB;e.rotate(g,this.localOffsetB,d.angle),e.rotate(h,this.localOffsetB,f.angle-this.localAngleB),e.scale(h,h,-1),e.rotate(i,h,Math.PI/2),e.normalize(i,i),a.G[0]=-1,a.G[1]=0,a.G[2]=-e.crossLength(g,j),a.G[3]=1,b.G[0]=0,b.G[1]=-1,b.G[2]=-e.crossLength(g,k),b.G[4]=1,c.G[0]=-i[0],c.G[1]=-i[1],c.G[3]=i[0],c.G[4]=i[1],c.G[5]=e.crossLength(h,i)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.PRISMATIC,c);var i=g.fromValues(0,0),j=g.fromValues(1,0),k=g.fromValues(0,0);c.localAnchorA&&g.copy(i,c.localAnchorA),c.localAxisA&&g.copy(j,c.localAxisA),c.localAnchorB&&g.copy(k,c.localAnchorB),this.localAnchorA=i,this.localAnchorB=k,this.localAxisA=j;var l=this.maxForce="undefined"!=typeof c.maxForce?c.maxForce:Number.MAX_VALUE,m=new f(a,b,-l,l),n=new g.create,o=new g.create,p=new g.create,q=new g.create;if(m.computeGq=function(){return g.dot(p,q)},m.updateJacobian=function(){var c=this.G,d=a.position,e=b.position;g.rotate(n,i,a.angle),g.rotate(o,k,b.angle),g.add(p,e,o),g.sub(p,p,d),g.sub(p,p,n),g.rotate(q,j,a.angle+Math.PI/2),c[0]=-q[0],c[1]=-q[1],c[2]=-g.crossLength(n,q)+g.crossLength(q,p),c[3]=q[0],c[4]=q[1],c[5]=g.crossLength(o,q)},this.equations.push(m),!c.disableRotationalLock){var r=new h(a,b,-l,l);this.equations.push(r)}this.position=0,this.velocity=0,this.lowerLimitEnabled="undefined"!=typeof c.lowerLimit?!0:!1,this.upperLimitEnabled="undefined"!=typeof c.upperLimit?!0:!1,this.lowerLimit="undefined"!=typeof c.lowerLimit?c.lowerLimit:0,this.upperLimit="undefined"!=typeof c.upperLimit?c.upperLimit:1,this.upperLimitEquation=new e(a,b),this.lowerLimitEquation=new e(a,b),this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0,this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=l,this.motorEquation=new f(a,b),this.motorEnabled=!1,this.motorSpeed=0;{var s=this,t=this.motorEquation;t.computeGW}t.computeGq=function(){return 0},t.computeGW=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=b.velocity,e=c.velocity,f=b.angularVelocity,g=c.angularVelocity;return this.gmult(a,d,f,e,g)+s.motorSpeed}}var d=a("./Constraint"),e=a("../equations/ContactEquation"),f=a("../equations/Equation"),g=a("../math/vec2"),h=a("../equations/RotationalLockEquation");b.exports=c,c.prototype=new d,c.prototype.constructor=c;var i=g.create(),j=g.create(),k=g.create(),l=g.create(),m=g.create(),n=g.create();c.prototype.update=function(){var a=this.equations,b=a[0],c=this.upperLimit,d=this.lowerLimit,e=this.upperLimitEquation,f=this.lowerLimitEquation,h=this.bodyA,o=this.bodyB,p=this.localAxisA,q=this.localAnchorA,r=this.localAnchorB;b.updateJacobian(),g.rotate(i,p,h.angle),g.rotate(l,q,h.angle),g.add(j,l,h.position),g.rotate(m,r,o.angle),g.add(k,m,o.position);var s=this.position=g.dot(k,i)-g.dot(j,i);if(this.motorEnabled){var t=this.motorEquation.G;t[0]=i[0],t[1]=i[1],t[2]=g.crossLength(i,m),t[3]=-i[0],t[4]=-i[1],t[5]=-g.crossLength(i,l)}if(this.upperLimitEnabled&&s>c)g.scale(e.normalA,i,-1),g.sub(e.contactPointA,j,h.position),g.sub(e.contactPointB,k,o.position),g.scale(n,i,c),g.add(e.contactPointA,e.contactPointA,n),-1===a.indexOf(e)&&a.push(e);else{var u=a.indexOf(e);-1!==u&&a.splice(u,1)}if(this.lowerLimitEnabled&&d>s)g.scale(f.normalA,i,1),g.sub(f.contactPointA,j,h.position),g.sub(f.contactPointB,k,o.position),g.scale(n,i,d),g.sub(f.contactPointB,f.contactPointB,n),-1===a.indexOf(f)&&a.push(f);else{var u=a.indexOf(f);-1!==u&&a.splice(u,1)}},c.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},c.prototype.disableMotor=function(){if(this.motorEnabled){var a=this.equations.indexOf(this.motorEquation);this.equations.splice(a,1),this.motorEnabled=!1}},c.prototype.setLimits=function(a,b){"number"==typeof a?(this.lowerLimit=a,this.lowerLimitEnabled=!0):(this.lowerLimit=a,this.lowerLimitEnabled=!1),"number"==typeof b?(this.upperLimit=b,this.upperLimitEnabled=!0):(this.upperLimit=b,this.upperLimitEnabled=!1)}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,d.REVOLUTE,c);var n=this.maxForce="undefined"!=typeof c.maxForce?c.maxForce:Number.MAX_VALUE;this.pivotA=h.create(),this.pivotB=h.create(),c.worldPivot?(h.sub(this.pivotA,c.worldPivot,a.position),h.sub(this.pivotB,c.worldPivot,b.position),h.rotate(this.pivotA,this.pivotA,-a.angle),h.rotate(this.pivotB,this.pivotB,-b.angle)):(h.copy(this.pivotA,c.localPivotA),h.copy(this.pivotB,c.localPivotB));var o=this.equations=[new e(a,b,-n,n),new e(a,b,-n,n)],p=o[0],q=o[1],r=this;p.computeGq=function(){return h.rotate(i,r.pivotA,a.angle),h.rotate(j,r.pivotB,b.angle),h.add(m,b.position,j),h.sub(m,m,a.position),h.sub(m,m,i),h.dot(m,k)},q.computeGq=function(){return h.rotate(i,r.pivotA,a.angle),h.rotate(j,r.pivotB,b.angle),h.add(m,b.position,j),h.sub(m,m,a.position),h.sub(m,m,i),h.dot(m,l)},q.minForce=p.minForce=-n,q.maxForce=p.maxForce=n,this.motorEquation=new f(a,b),this.motorEnabled=!1,this.angle=0,this.lowerLimitEnabled=!1,this.upperLimitEnabled=!1,this.lowerLimit=0,this.upperLimit=0,this.upperLimitEquation=new g(a,b),this.lowerLimitEquation=new g(a,b),this.upperLimitEquation.minForce=0,this.lowerLimitEquation.maxForce=0}var d=a("./Constraint"),e=a("../equations/Equation"),f=a("../equations/RotationalVelocityEquation"),g=a("../equations/RotationalLockEquation"),h=a("../math/vec2");b.exports=c;var i=h.create(),j=h.create(),k=h.fromValues(1,0),l=h.fromValues(0,1),m=h.create();c.prototype=new d,c.prototype.constructor=c,c.prototype.setLimits=function(a,b){"number"==typeof a?(this.lowerLimit=a,this.lowerLimitEnabled=!0):(this.lowerLimit=a,this.lowerLimitEnabled=!1),"number"==typeof b?(this.upperLimit=b,this.upperLimitEnabled=!0):(this.upperLimit=b,this.upperLimitEnabled=!1)},c.prototype.update=function(){var a=this.bodyA,b=this.bodyB,c=this.pivotA,d=this.pivotB,e=this.equations,f=(e[0],e[1],e[0]),g=e[1],m=this.upperLimit,n=this.lowerLimit,o=this.upperLimitEquation,p=this.lowerLimitEquation,q=this.angle=b.angle-a.angle;if(this.upperLimitEnabled&&q>m)o.angle=m,-1===e.indexOf(o)&&e.push(o);else{var r=e.indexOf(o);-1!==r&&e.splice(r,1)}if(this.lowerLimitEnabled&&n>q)p.angle=n,-1===e.indexOf(p)&&e.push(p);else{var r=e.indexOf(p);-1!==r&&e.splice(r,1)}h.rotate(i,c,a.angle),h.rotate(j,d,b.angle),f.G[0]=-1,f.G[1]=0,f.G[2]=-h.crossLength(i,k),f.G[3]=1,f.G[4]=0,f.G[5]=h.crossLength(j,k),g.G[0]=0,g.G[1]=-1,g.G[2]=-h.crossLength(i,l),g.G[3]=0,g.G[4]=1,g.G[5]=h.crossLength(j,l)},c.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},c.prototype.disableMotor=function(){if(this.motorEnabled){var a=this.equations.indexOf(this.motorEquation);this.equations.splice(a,1),this.motorEnabled=!1}},c.prototype.motorIsEnabled=function(){return!!this.motorEnabled},c.prototype.setMotorSpeed=function(a){if(this.motorEnabled){var b=this.equations.indexOf(this.motorEquation);this.equations[b].relativeVelocity=a}},c.prototype.getMotorSpeed=function(){return this.motorEnabled?this.motorEquation.relativeVelocity:!1}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=c.angle||0,this.ratio="number"==typeof c.ratio?c.ratio:1,this.setRatio(this.ratio)}{var d=a("./Equation");a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle},c.prototype.setRatio=function(a){var b=this.G;b[2]=a,b[5]=-1,this.ratio=a},c.prototype.setMaxTorque=function(a){this.maxForce=a,this.minForce=-a}},{"../math/vec2":30,"./Equation":22}],21:[function(a,b){function c(a,b){d.call(this,a,b,0,Number.MAX_VALUE),this.contactPointA=e.create(),this.penetrationVec=e.create(),this.contactPointB=e.create(),this.normalA=e.create(),this.restitution=0,this.firstImpact=!1,this.shapeA=null,this.shapeB=null}var d=a("./Equation"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeB=function(a,b,c){var d=this.bodyA,f=this.bodyB,g=this.contactPointA,h=this.contactPointB,i=d.position,j=f.position,k=this.penetrationVec,l=this.normalA,m=this.G,n=e.crossLength(g,l),o=e.crossLength(h,l);m[0]=-l[0],m[1]=-l[1],m[2]=-n,m[3]=l[0],m[4]=l[1],m[5]=o,e.add(k,j,h),e.sub(k,k,i),e.sub(k,k,g);var p,q;this.firstImpact&&0!==this.restitution?(q=0,p=1/b*(1+this.restitution)*this.computeGW()):(q=e.dot(l,k)+this.offset,p=this.computeGW());var r=this.computeGiMf(),s=-q*a-p*b-c*r;return s}},{"../math/vec2":30,"./Equation":22}],22:[function(a,b){function c(a,b,d,f){this.minForce="undefined"==typeof d?-Number.MAX_VALUE:d,this.maxForce="undefined"==typeof f?Number.MAX_VALUE:f,this.bodyA=a,this.bodyB=b,this.stiffness=c.DEFAULT_STIFFNESS,this.relaxation=c.DEFAULT_RELAXATION,this.G=new e.ARRAY_TYPE(6);for(var g=0;6>g;g++)this.G[g]=0;this.offset=0,this.a=0,this.b=0,this.epsilon=0,this.timeStep=1/60,this.needsUpdate=!0,this.multiplier=0,this.relativeVelocity=0,this.enabled=!0}b.exports=c;{var d=a("../math/vec2"),e=a("../utils/Utils");a("../objects/Body")}c.prototype.constructor=c,c.DEFAULT_STIFFNESS=1e6,c.DEFAULT_RELAXATION=4,c.prototype.update=function(){var a=this.stiffness,b=this.relaxation,c=this.timeStep;this.a=4/(c*(1+4*b)),this.b=4*b/(1+4*b),this.epsilon=4/(c*c*a*(1+4*b)),this.needsUpdate=!1},c.prototype.gmult=function(a,b,c,d,e){return a[0]*b[0]+a[1]*b[1]+a[2]*c+a[3]*d[0]+a[4]*d[1]+a[5]*e},c.prototype.computeB=function(a,b,c){var d=this.computeGW(),e=this.computeGq(),f=this.computeGiMf();return-e*a-d*b-f*c};var f=d.create(),g=d.create();c.prototype.computeGq=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=(b.position,c.position,b.angle),e=c.angle;return this.gmult(a,f,d,g,e)+this.offset},c.prototype.computeGW=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=b.velocity,e=c.velocity,f=b.angularVelocity,g=c.angularVelocity;return this.gmult(a,d,f,e,g)+this.relativeVelocity},c.prototype.computeGWlambda=function(){var a=this.G,b=this.bodyA,c=this.bodyB,d=b.vlambda,e=c.vlambda,f=b.wlambda,g=c.wlambda;return this.gmult(a,d,f,e,g)};var h=d.create(),i=d.create();c.prototype.computeGiMf=function(){var a=this.bodyA,b=this.bodyB,c=a.force,e=a.angularForce,f=b.force,g=b.angularForce,j=a.invMassSolve,k=b.invMassSolve,l=a.invInertiaSolve,m=b.invInertiaSolve,n=this.G;return d.scale(h,c,j),d.multiply(h,a.massMultiplier,h),d.scale(i,f,k),d.multiply(i,b.massMultiplier,i),this.gmult(n,h,e*l,i,g*m)},c.prototype.computeGiMGt=function(){var a=this.bodyA,b=this.bodyB,c=a.invMassSolve,d=b.invMassSolve,e=a.invInertiaSolve,f=b.invInertiaSolve,g=this.G;return g[0]*g[0]*c*a.massMultiplier[0]+g[1]*g[1]*c*a.massMultiplier[1]+g[2]*g[2]*e+g[3]*g[3]*d*b.massMultiplier[0]+g[4]*g[4]*d*b.massMultiplier[1]+g[5]*g[5]*f};{var j=d.create(),k=d.create(),l=d.create();d.create(),d.create(),d.create()}c.prototype.addToWlambda=function(a){var b=this.bodyA,c=this.bodyB,e=j,f=k,g=l,h=b.invMassSolve,i=c.invMassSolve,m=b.invInertiaSolve,n=c.invInertiaSolve,o=this.G;f[0]=o[0],f[1]=o[1],g[0]=o[3],g[1]=o[4],d.scale(e,f,h*a),d.multiply(e,e,b.massMultiplier),d.add(b.vlambda,b.vlambda,e),b.wlambda+=m*o[2]*a,d.scale(e,g,i*a),d.multiply(e,e,c.massMultiplier),d.add(c.vlambda,c.vlambda,e),c.wlambda+=n*o[5]*a},c.prototype.computeInvC=function(a){return 1/(this.computeGiMGt()+a)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(a,b){function c(a,b,c){e.call(this,a,b,-c,c),this.contactPointA=d.create(),this.contactPointB=d.create(),this.t=d.create(),this.contactEquations=[],this.shapeA=null,this.shapeB=null,this.frictionCoefficient=.3}{var d=a("../math/vec2"),e=a("./Equation");a("../utils/Utils")}b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.setSlipForce=function(a){this.maxForce=a,this.minForce=-a},c.prototype.getSlipForce=function(){return this.maxForce},c.prototype.computeB=function(a,b,c){var e=(this.bodyA,this.bodyB,this.contactPointA),f=this.contactPointB,g=this.t,h=this.G;h[0]=-g[0],h[1]=-g[1],h[2]=-d.crossLength(e,g),h[3]=g[0],h[4]=g[1],h[5]=d.crossLength(f,g);var i=this.computeGW(),j=this.computeGiMf(),k=-i*b-c*j;return k}},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=c.angle||0;var e=this.G;e[2]=1,e[5]=-1}var d=a("./Equation"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c;var f=e.create(),g=e.create(),h=e.fromValues(1,0),i=e.fromValues(0,1);c.prototype.computeGq=function(){return e.rotate(f,h,this.bodyA.angle+this.angle),e.rotate(g,i,this.bodyB.angle),e.dot(f,g)}},{"../math/vec2":30,"./Equation":22}],25:[function(a,b){function c(a,b){d.call(this,a,b,-Number.MAX_VALUE,Number.MAX_VALUE),this.relativeVelocity=1,this.ratio=1}{var d=a("./Equation");a("../math/vec2")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeB=function(a,b,c){var d=this.G;d[2]=-1,d[5]=this.ratio;var e=this.computeGiMf(),f=this.computeGW(),g=-f*b-c*e;return g}},{"../math/vec2":30,"./Equation":22}],26:[function(a,b){var c=function(){};b.exports=c,c.prototype={constructor:c,on:function(a,b,c){b.context=c||this,void 0===this._listeners&&(this._listeners={});var d=this._listeners;return void 0===d[a]&&(d[a]=[]),-1===d[a].indexOf(b)&&d[a].push(b),this},has:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;if(b){if(void 0!==c[a]&&-1!==c[a].indexOf(b))return!0}else if(void 0!==c[a])return!0;return!1},off:function(a,b){if(void 0===this._listeners)return this;var c=this._listeners,d=c[a].indexOf(b);return-1!==d&&c[a].splice(d,1),this},emit:function(a){if(void 0===this._listeners)return this;var b=this._listeners,c=b[a.type];if(void 0!==c){a.target=this;for(var d=0,e=c.length;e>d;d++){var f=c[d];f.call(f.context,a)}}return this}}},{}],27:[function(a,b){function c(a,b,f){if(f=f||{},!(a instanceof d&&b instanceof d))throw new Error("First two arguments must be Material instances.");this.id=c.idCounter++,this.materialA=a,this.materialB=b,this.friction="undefined"!=typeof f.friction?Number(f.friction):.3,this.restitution="undefined"!=typeof f.restitution?Number(f.restitution):0,this.stiffness="undefined"!=typeof f.stiffness?Number(f.stiffness):e.DEFAULT_STIFFNESS,this.relaxation="undefined"!=typeof f.relaxation?Number(f.relaxation):e.DEFAULT_RELAXATION,this.frictionStiffness="undefined"!=typeof f.frictionStiffness?Number(f.frictionStiffness):e.DEFAULT_STIFFNESS,this.frictionRelaxation="undefined"!=typeof f.frictionRelaxation?Number(f.frictionRelaxation):e.DEFAULT_RELAXATION,this.surfaceVelocity="undefined"!=typeof f.surfaceVelocity?Number(f.surfaceVelocity):0,this.contactSkinSize=.005}var d=a("./Material"),e=a("../equations/Equation");b.exports=c,c.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(a,b){function c(a){this.id=a||c.idCounter++}b.exports=c,c.idCounter=0},{}],29:[function(a,b){var c={};c.GetArea=function(a){if(a.length<6)return 0;for(var b=a.length-2,c=0,d=0;b>d;d+=2)c+=(a[d+2]-a[d])*(a[d+1]+a[d+3]);return c+=(a[0]-a[b])*(a[b+1]+a[1]),.5*-c},c.Triangulate=function(a){var b=a.length>>1;if(3>b)return[];for(var d=[],e=[],f=0;b>f;f++)e.push(f);for(var f=0,g=b;g>3;){var h=e[(f+0)%g],i=e[(f+1)%g],j=e[(f+2)%g],k=a[2*h],l=a[2*h+1],m=a[2*i],n=a[2*i+1],o=a[2*j],p=a[2*j+1],q=!1;if(c._convex(k,l,m,n,o,p)){q=!0;for(var r=0;g>r;r++){var s=e[r];if(s!=h&&s!=i&&s!=j&&c._PointInTriangle(a[2*s],a[2*s+1],k,l,m,n,o,p)){q=!1;break}}}if(q)d.push(h,i,j),e.splice((f+1)%g,1),g--,f=0;else if(f++>3*g)break}return d.push(e[0],e[1],e[2]),d},c._PointInTriangle=function(a,b,c,d,e,f,g,h){var i=g-c,j=h-d,k=e-c,l=f-d,m=a-c,n=b-d,o=i*i+j*j,p=i*k+j*l,q=i*m+j*n,r=k*k+l*l,s=k*m+l*n,t=1/(o*r-p*p),u=(r*q-p*s)*t,v=(o*s-p*q)*t;return u>=0&&v>=0&&1>u+v},c._convex=function(a,b,c,d,e,f){return(b-d)*(e-c)+(c-a)*(f-d)>=0},b.exports=c},{}],30:[function(a,b){var c=b.exports={},d=a("../utils/Utils");c.crossLength=function(a,b){return a[0]*b[1]-a[1]*b[0]},c.crossVZ=function(a,b,d){return c.rotate(a,b,-Math.PI/2),c.scale(a,a,d),a},c.crossZV=function(a,b,d){return c.rotate(a,d,Math.PI/2),c.scale(a,a,b),a},c.rotate=function(a,b,c){if(0!==c){var d=Math.cos(c),e=Math.sin(c),f=b[0],g=b[1];a[0]=d*f-e*g,a[1]=e*f+d*g}else a[0]=b[0],a[1]=b[1]},c.rotate90cw=function(a,b){var c=b[0],d=b[1];a[0]=d,a[1]=-c},c.toLocalFrame=function(a,b,d,e){c.copy(a,b),c.sub(a,a,d),c.rotate(a,a,-e)},c.toGlobalFrame=function(a,b,d,e){c.copy(a,b),c.rotate(a,a,e),c.add(a,a,d)},c.vectorToLocalFrame=function(a,b,d){c.rotate(a,b,-d)},c.vectorToGlobalFrame=function(a,b,d){c.rotate(a,b,d)},c.centroid=function(a,b,d,e){return c.add(a,b,d),c.add(a,a,e),c.scale(a,a,1/3),a},c.create=function(){var a=new d.ARRAY_TYPE(2);return a[0]=0,a[1]=0,a},c.clone=function(a){var b=new d.ARRAY_TYPE(2);return b[0]=a[0],b[1]=a[1],b},c.fromValues=function(a,b){var c=new d.ARRAY_TYPE(2);return c[0]=a,c[1]=b,c},c.copy=function(a,b){return a[0]=b[0],a[1]=b[1],a},c.set=function(a,b,c){return a[0]=b,a[1]=c,a},c.add=function(a,b,c){return a[0]=b[0]+c[0],a[1]=b[1]+c[1],a},c.subtract=function(a,b,c){return a[0]=b[0]-c[0],a[1]=b[1]-c[1],a},c.sub=c.subtract,c.multiply=function(a,b,c){return a[0]=b[0]*c[0],a[1]=b[1]*c[1],a},c.mul=c.multiply,c.divide=function(a,b,c){return a[0]=b[0]/c[0],a[1]=b[1]/c[1],a},c.div=c.divide,c.scale=function(a,b,c){return a[0]=b[0]*c,a[1]=b[1]*c,a},c.distance=function(a,b){var c=b[0]-a[0],d=b[1]-a[1];return Math.sqrt(c*c+d*d)},c.dist=c.distance,c.squaredDistance=function(a,b){var c=b[0]-a[0],d=b[1]-a[1];return c*c+d*d},c.sqrDist=c.squaredDistance,c.length=function(a){var b=a[0],c=a[1];return Math.sqrt(b*b+c*c)},c.len=c.length,c.squaredLength=function(a){var b=a[0],c=a[1];return b*b+c*c},c.sqrLen=c.squaredLength,c.negate=function(a,b){return a[0]=-b[0],a[1]=-b[1],a},c.normalize=function(a,b){var c=b[0],d=b[1],e=c*c+d*d;return e>0&&(e=1/Math.sqrt(e),a[0]=b[0]*e,a[1]=b[1]*e),a},c.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]},c.str=function(a){return"vec2("+a[0]+", "+a[1]+")"},c.lerp=function(a,b,c,d){var e=b[0],f=b[1];return a[0]=e+d*(c[0]-e),a[1]=f+d*(c[1]-f),a},c.reflect=function(a,b,c){var d=b[0]*c[0]+b[1]*c[1];a[0]=b[0]-2*c[0]*d,a[1]=b[1]-2*c[1]*d},c.getLineSegmentsIntersection=function(a,b,d,e,f){var g=c.getLineSegmentsIntersectionFraction(b,d,e,f);return 0>g?!1:(a[0]=b[0]+g*(d[0]-b[0]),a[1]=b[1]+g*(d[1]-b[1]),!0)},c.getLineSegmentsIntersectionFraction=function(a,b,c,d){var e,f,g=b[0]-a[0],h=b[1]-a[1],i=d[0]-c[0],j=d[1]-c[1];return e=(-h*(a[0]-c[0])+g*(a[1]-c[1]))/(-i*h+g*j),f=(i*(a[1]-c[1])-j*(a[0]-c[0]))/(-i*h+g*j),e>=0&&1>=e&&f>=0&&1>=f?f:-1}},{"../utils/Utils":57}],31:[function(a,b){function c(a){a=a||{},j.call(this),this.id=a.id||++c._idCounter,this.world=null,this.shapes=[],this.mass=a.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!a.fixedRotation,this.fixedX=!!a.fixedX,this.fixedY=!!a.fixedY,this.massMultiplier=d.create(),this.position=d.fromValues(0,0),a.position&&d.copy(this.position,a.position),this.interpolatedPosition=d.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=d.fromValues(0,0),this.previousAngle=0,this.velocity=d.fromValues(0,0),a.velocity&&d.copy(this.velocity,a.velocity),this.vlambda=d.fromValues(0,0),this.wlambda=0,this.angle=a.angle||0,this.angularVelocity=a.angularVelocity||0,this.force=d.create(),a.force&&d.copy(this.force,a.force),this.angularForce=a.angularForce||0,this.damping="number"==typeof a.damping?a.damping:.1,this.angularDamping="number"==typeof a.angularDamping?a.angularDamping:.1,this.type=c.STATIC,this.type="undefined"!=typeof a.type?a.type:a.mass?c.DYNAMIC:c.STATIC,this.boundingRadius=0,this.aabb=new i,this.aabbNeedsUpdate=!0,this.allowSleep=void 0!==a.allowSleep?a.allowSleep:!0,this.wantsToSleep=!1,this.sleepState=c.AWAKE,this.sleepSpeedLimit=void 0!==a.sleepSpeedLimit?a.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==a.sleepTimeLimit?a.sleepTimeLimit:1,this.gravityScale=void 0!==a.gravityScale?a.gravityScale:1,this.collisionResponse=void 0!==a.collisionResponse?a.collisionResponse:!0,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==a.ccdSpeedThreshold?a.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==a.ccdIterations?a.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()
+}var d=a("../math/vec2"),e=a("poly-decomp"),f=a("../shapes/Convex"),g=a("../collision/RaycastResult"),h=a("../collision/Ray"),i=a("../collision/AABB"),j=a("../events/EventEmitter");b.exports=c,c.prototype=new j,c.prototype.constructor=c,c._idCounter=0,c.prototype.updateSolveMassProperties=function(){this.sleepState===c.SLEEPING||this.type===c.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},c.prototype.setDensity=function(a){var b=this.getArea();this.mass=b*a,this.updateMassProperties()},c.prototype.getArea=function(){for(var a=0,b=0;b<this.shapes.length;b++)a+=this.shapes[b].area;return a},c.prototype.getAABB=function(){return this.aabbNeedsUpdate&&this.updateAABB(),this.aabb};var k=new i,l=d.create();c.prototype.updateAABB=function(){for(var a=this.shapes,b=a.length,c=l,e=this.angle,f=0;f!==b;f++){var g=a[f],h=g.angle+e;d.rotate(c,g.position,e),d.add(c,c,this.position),g.computeAABB(k,c,h),0===f?this.aabb.copy(k):this.aabb.extend(k)}this.aabbNeedsUpdate=!1},c.prototype.updateBoundingRadius=function(){for(var a=this.shapes,b=a.length,c=0,e=0;e!==b;e++){var f=a[e],g=d.length(f.position),h=f.boundingRadius;g+h>c&&(c=g+h)}this.boundingRadius=c},c.prototype.addShape=function(a,b,c){if(a.body)throw new Error("A shape can only be added to one body.");a.body=this,b?d.copy(a.position,b):d.set(a.position,0,0),a.angle=c||0,this.shapes.push(a),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},c.prototype.removeShape=function(a){var b=this.shapes.indexOf(a);return-1!==b?(this.shapes.splice(b,1),this.aabbNeedsUpdate=!0,a.body=null,!0):!1},c.prototype.updateMassProperties=function(){if(this.type===c.STATIC||this.type===c.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var a=this.shapes,b=a.length,e=this.mass/b,f=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var g=0;b>g;g++){var h=a[g],i=d.squaredLength(h.position),j=h.computeMomentOfInertia(e);f+=j+e*i}this.inertia=f,this.invInertia=f>0?1/f:0}this.invMass=1/this.mass,d.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};d.create();c.prototype.applyForce=function(a,b){if(d.add(this.force,this.force,a),b){var c=d.crossLength(b,a);this.angularForce+=c}};var m=d.create(),n=d.create(),o=d.create();c.prototype.applyForceLocal=function(a,b){b=b||o;var c=m,d=n;this.vectorToWorldFrame(c,a),this.vectorToWorldFrame(d,b),this.applyForce(c,d)};var p=d.create();c.prototype.applyImpulse=function(a,b){if(this.type===c.DYNAMIC){var e=p;if(d.scale(e,a,this.invMass),d.multiply(e,this.massMultiplier,e),d.add(this.velocity,e,this.velocity),b){var f=d.crossLength(b,a);f*=this.invInertia,this.angularVelocity+=f}}};var q=d.create(),r=d.create(),s=d.create();c.prototype.applyImpulseLocal=function(a,b){b=b||s;var c=q,d=r;this.vectorToWorldFrame(c,a),this.vectorToWorldFrame(d,b),this.applyImpulse(c,d)},c.prototype.toLocalFrame=function(a,b){d.toLocalFrame(a,b,this.position,this.angle)},c.prototype.toWorldFrame=function(a,b){d.toGlobalFrame(a,b,this.position,this.angle)},c.prototype.vectorToLocalFrame=function(a,b){d.vectorToLocalFrame(a,b,this.angle)},c.prototype.vectorToWorldFrame=function(a,b){d.vectorToGlobalFrame(a,b,this.angle)},c.prototype.fromPolygon=function(a,b){b=b||{};for(var c=this.shapes.length;c>=0;--c)this.removeShape(this.shapes[c]);var g=new e.Polygon;if(g.vertices=a,g.makeCCW(),"number"==typeof b.removeCollinearPoints&&g.removeCollinearPoints(b.removeCollinearPoints),"undefined"==typeof b.skipSimpleCheck&&!g.isSimple())return!1;this.concavePath=g.vertices.slice(0);for(var c=0;c<this.concavePath.length;c++){var h=[0,0];d.copy(h,this.concavePath[c]),this.concavePath[c]=h}var i;i=b.optimalDecomp?g.decomp():g.quickDecomp();for(var j=d.create(),c=0;c!==i.length;c++){for(var k=new f({vertices:i[c].vertices}),l=0;l!==k.vertices.length;l++){var h=k.vertices[l];d.sub(h,h,k.centerOfMass)}d.scale(j,k.centerOfMass,1),k.updateTriangles(),k.updateCenterOfMass(),k.updateBoundingRadius(),this.addShape(k,j)}return this.adjustCenterOfMass(),this.aabbNeedsUpdate=!0,!0};var t=(d.fromValues(0,0),d.fromValues(0,0)),u=d.fromValues(0,0),v=d.fromValues(0,0);c.prototype.adjustCenterOfMass=function(){var a=t,b=u,c=v,e=0;d.set(b,0,0);for(var f=0;f!==this.shapes.length;f++){var g=this.shapes[f];d.scale(a,g.position,g.area),d.add(b,b,a),e+=g.area}d.scale(c,b,1/e);for(var f=0;f!==this.shapes.length;f++){var g=this.shapes[f];d.sub(g.position,g.position,c)}d.add(this.position,this.position,c);for(var f=0;this.concavePath&&f<this.concavePath.length;f++)d.sub(this.concavePath[f],this.concavePath[f],c);this.updateMassProperties(),this.updateBoundingRadius()},c.prototype.setZeroForce=function(){d.set(this.force,0,0),this.angularForce=0},c.prototype.resetConstraintVelocity=function(){var a=this,b=a.vlambda;d.set(b,0,0),a.wlambda=0},c.prototype.addConstraintVelocity=function(){var a=this,b=a.velocity;d.add(b,b,a.vlambda),a.angularVelocity+=a.wlambda},c.prototype.applyDamping=function(a){if(this.type===c.DYNAMIC){var b=this.velocity;d.scale(b,b,Math.pow(1-this.damping,a)),this.angularVelocity*=Math.pow(1-this.angularDamping,a)}},c.prototype.wakeUp=function(){var a=this.sleepState;this.sleepState=c.AWAKE,this.idleTime=0,a!==c.AWAKE&&this.emit(c.wakeUpEvent)},c.prototype.sleep=function(){this.sleepState=c.SLEEPING,this.angularVelocity=0,this.angularForce=0,d.set(this.velocity,0,0),d.set(this.force,0,0),this.emit(c.sleepEvent)},c.prototype.sleepTick=function(a,b,e){if(this.allowSleep&&this.type!==c.SLEEPING){this.wantsToSleep=!1;var f=(this.sleepState,d.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2)),g=Math.pow(this.sleepSpeedLimit,2);f>=g?(this.idleTime=0,this.sleepState=c.AWAKE):(this.idleTime+=e,this.sleepState=c.SLEEPY),this.idleTime>this.sleepTimeLimit&&(b?this.wantsToSleep=!0:this.sleep())}},c.prototype.overlaps=function(a){return this.world.overlapKeeper.bodiesAreOverlapping(this,a)};var w=d.create(),x=d.create();c.prototype.integrate=function(a){var b=this.invMass,c=this.force,e=this.position,f=this.velocity;d.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*a),d.scale(w,c,a*b),d.multiply(w,this.massMultiplier,w),d.add(f,w,f),this.integrateToTimeOfImpact(a)||(d.scale(x,f,a),d.add(e,e,x),this.fixedRotation||(this.angle+=this.angularVelocity*a)),this.aabbNeedsUpdate=!0};var y=new g,z=new h({mode:h.ALL}),A=d.create(),B=d.create(),C=d.create(),D=d.create();c.prototype.integrateToTimeOfImpact=function(a){if(this.ccdSpeedThreshold<0||d.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2))return!1;d.normalize(A,this.velocity),d.scale(B,this.velocity,a),d.add(B,B,this.position),d.sub(C,B,this.position);var b,c=this.angularVelocity*a,e=d.length(C),f=1,g=this;if(y.reset(),z.callback=function(a){a.body!==g&&(b=a.body,a.getHitPoint(B,z),d.sub(C,B,g.position),f=d.length(C)/e,a.stop())},d.copy(z.from,this.position),d.copy(z.to,B),z.update(),this.world.raycast(y,z),!b)return!1;var h=this.angle;d.copy(D,this.position);for(var i=0,j=0,k=0,l=f;l>=j&&i<this.ccdIterations;){i++,k=(l-j)/2,d.scale(x,C,f),d.add(this.position,D,x),this.angle=h+c*f,this.updateAABB();var m=this.aabb.overlaps(b.aabb)&&this.world.narrowphase.bodiesOverlap(this,b);m?j=k:l=k}return f=k,d.copy(this.position,D),this.angle=h,d.scale(x,C,f),d.add(this.position,this.position,x),this.fixedRotation||(this.angle+=c*f),!0},c.prototype.getVelocityAtPoint=function(a,b){return d.crossVZ(a,b,this.angularVelocity),d.subtract(a,this.velocity,a),a},c.sleepyEvent={type:"sleepy"},c.sleepEvent={type:"sleep"},c.wakeUpEvent={type:"wakeup"},c.DYNAMIC=1,c.STATIC=2,c.KINEMATIC=4,c.AWAKE=0,c.SLEEPY=1,c.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(a,b){function c(a,b,c){c=c||{},e.call(this,a,b,c),this.localAnchorA=d.fromValues(0,0),this.localAnchorB=d.fromValues(0,0),c.localAnchorA&&d.copy(this.localAnchorA,c.localAnchorA),c.localAnchorB&&d.copy(this.localAnchorB,c.localAnchorB),c.worldAnchorA&&this.setWorldAnchorA(c.worldAnchorA),c.worldAnchorB&&this.setWorldAnchorB(c.worldAnchorB);var f=d.create(),g=d.create();this.getWorldAnchorA(f),this.getWorldAnchorB(g);var h=d.distance(f,g);this.restLength="number"==typeof c.restLength?c.restLength:h}{var d=a("../math/vec2"),e=a("./Spring");a("../utils/Utils")}b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.setWorldAnchorA=function(a){this.bodyA.toLocalFrame(this.localAnchorA,a)},c.prototype.setWorldAnchorB=function(a){this.bodyB.toLocalFrame(this.localAnchorB,a)},c.prototype.getWorldAnchorA=function(a){this.bodyA.toWorldFrame(a,this.localAnchorA)},c.prototype.getWorldAnchorB=function(a){this.bodyB.toWorldFrame(a,this.localAnchorB)};var f=d.create(),g=d.create(),h=d.create(),i=d.create(),j=d.create(),k=d.create(),l=d.create(),m=d.create(),n=d.create();c.prototype.applyForce=function(){var a=this.stiffness,b=this.damping,c=this.restLength,e=this.bodyA,o=this.bodyB,p=f,q=g,r=h,s=i,t=n,u=j,v=k,w=l,x=m;this.getWorldAnchorA(u),this.getWorldAnchorB(v),d.sub(w,u,e.position),d.sub(x,v,o.position),d.sub(p,v,u);var y=d.len(p);d.normalize(q,p),d.sub(r,o.velocity,e.velocity),d.crossZV(t,o.angularVelocity,x),d.add(r,r,t),d.crossZV(t,e.angularVelocity,w),d.sub(r,r,t),d.scale(s,q,-a*(y-c)-b*d.dot(r,q)),d.sub(e.force,e.force,s),d.add(o.force,o.force,s);var z=d.crossLength(w,s),A=d.crossLength(x,s);e.angularForce-=z,o.angularForce+=A}},{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(a,b){function c(a,b,c){c=c||{},d.call(this,a,b,c),this.restAngle="number"==typeof c.restAngle?c.restAngle:b.angle-a.angle}var d=(a("../math/vec2"),a("./Spring"));b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.applyForce=function(){var a=this.stiffness,b=this.damping,c=this.restAngle,d=this.bodyA,e=this.bodyB,f=e.angle-d.angle,g=e.angularVelocity-d.angularVelocity,h=-a*(f-c)-b*g*0;d.angularForce-=h,e.angularForce+=h}},{"../math/vec2":30,"./Spring":34}],34:[function(a,b){function c(a,b,c){c=d.defaults(c,{stiffness:100,damping:1}),this.stiffness=c.stiffness,this.damping=c.damping,this.bodyA=a,this.bodyB=b}var d=(a("../math/vec2"),a("../utils/Utils"));b.exports=c,c.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":57}],35:[function(a,b){function c(a,b){b=b||{},this.chassisBody=a,this.wheels=[],this.groundBody=new h({mass:0}),this.world=null;var c=this;this.preStepCallback=function(){c.update()}}function d(a,b){b=b||{},this.vehicle=a,this.forwardEquation=new g(a.chassisBody,a.groundBody),this.sideEquation=new g(a.chassisBody,a.groundBody),this.steerValue=0,this.engineForce=0,this.setSideFriction(void 0!==b.sideFriction?b.sideFriction:5),this.localForwardVector=e.fromValues(0,1),b.localForwardVector&&e.copy(this.localForwardVector,b.localForwardVector),this.localPosition=e.fromValues(0,0),b.localPosition&&e.copy(this.localPosition,b.localPosition),f.apply(this,a.chassisBody,a.groundBody),this.equations.push(this.forwardEquation,this.sideEquation),this.setBrakeForce(0)}var e=a("../math/vec2"),f=(a("../utils/Utils"),a("../constraints/Constraint")),g=a("../equations/FrictionEquation"),h=a("../objects/Body");b.exports=c,c.prototype.addToWorld=function(a){this.world=a,a.addBody(this.groundBody),a.on("preStep",this.preStepCallback);for(var b=0;b<this.wheels.length;b++){var c=this.wheels[b];a.addConstraint(c)}},c.prototype.removeFromWorld=function(){var a=this.world;a.removeBody(this.groundBody),a.off("preStep",this.preStepCallback);for(var b=0;b<this.wheels.length;b++){var c=this.wheels[b];a.removeConstraint(c)}this.world=null},c.prototype.addWheel=function(a){var b=new d(this,a);return this.wheels.push(b),b},c.prototype.update=function(){for(var a=0;a<this.wheels.length;a++)this.wheels[a].update()},d.prototype=new f,d.prototype.setBrakeForce=function(a){this.forwardEquation.setSlipForce(a)},d.prototype.setSideFriction=function(a){this.sideEquation.setSlipForce(a)};var i=e.create(),j=e.create();d.prototype.getSpeed=function(){return this.vehicle.chassisBody.vectorToWorldFrame(j,this.localForwardVector),this.vehicle.chassisBody.getVelocityAtPoint(i,j),e.dot(i,j)};var k=e.create();d.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector),e.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2),this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t),e.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue),e.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue),this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition),e.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB),this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition),e.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA),e.normalize(k,this.forwardEquation.t),e.scale(k,k,this.engineForce),this.vehicle.chassisBody.applyForce(k,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(a,b){var c=b.exports={AABB:a("./collision/AABB"),AngleLockEquation:a("./equations/AngleLockEquation"),Body:a("./objects/Body"),Broadphase:a("./collision/Broadphase"),Capsule:a("./shapes/Capsule"),Circle:a("./shapes/Circle"),Constraint:a("./constraints/Constraint"),ContactEquation:a("./equations/ContactEquation"),ContactEquationPool:a("./utils/ContactEquationPool"),ContactMaterial:a("./material/ContactMaterial"),Convex:a("./shapes/Convex"),DistanceConstraint:a("./constraints/DistanceConstraint"),Equation:a("./equations/Equation"),EventEmitter:a("./events/EventEmitter"),FrictionEquation:a("./equations/FrictionEquation"),FrictionEquationPool:a("./utils/FrictionEquationPool"),GearConstraint:a("./constraints/GearConstraint"),GSSolver:a("./solver/GSSolver"),Heightfield:a("./shapes/Heightfield"),Line:a("./shapes/Line"),LockConstraint:a("./constraints/LockConstraint"),Material:a("./material/Material"),Narrowphase:a("./collision/Narrowphase"),NaiveBroadphase:a("./collision/NaiveBroadphase"),Particle:a("./shapes/Particle"),Plane:a("./shapes/Plane"),Pool:a("./utils/Pool"),RevoluteConstraint:a("./constraints/RevoluteConstraint"),PrismaticConstraint:a("./constraints/PrismaticConstraint"),Ray:a("./collision/Ray"),RaycastResult:a("./collision/RaycastResult"),Box:a("./shapes/Box"),RotationalVelocityEquation:a("./equations/RotationalVelocityEquation"),SAPBroadphase:a("./collision/SAPBroadphase"),Shape:a("./shapes/Shape"),Solver:a("./solver/Solver"),Spring:a("./objects/Spring"),TopDownVehicle:a("./objects/TopDownVehicle"),LinearSpring:a("./objects/LinearSpring"),RotationalSpring:a("./objects/RotationalSpring"),Utils:a("./utils/Utils"),World:a("./world/World"),vec2:a("./math/vec2"),version:a("../package.json").version};Object.defineProperty(c,"Rectangle",{get:function(){return console.warn("The Rectangle class has been renamed to Box."),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":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(a,b){function c(a){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(a={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, ... })")),a=a||{};var b=this.width=a.width||1,c=this.height=a.height||1,g=[d.fromValues(-b/2,-c/2),d.fromValues(b/2,-c/2),d.fromValues(b/2,c/2),d.fromValues(-b/2,c/2)],h=[d.fromValues(1,0),d.fromValues(0,1)];a.vertices=g,a.axes=h,a.type=e.BOX,f.call(this,a)}var d=a("../math/vec2"),e=a("./Shape"),f=a("./Convex");b.exports=c,c.prototype=new f,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){var b=this.width,c=this.height;return a*(c*c+b*b)/12},c.prototype.updateBoundingRadius=function(){var a=this.width,b=this.height;this.boundingRadius=Math.sqrt(a*a+b*b)/2};d.create(),d.create(),d.create(),d.create();c.prototype.computeAABB=function(a,b,c){a.setFromPoints(this.vertices,b,c,0)},c.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(a,b){function c(a){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(a={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 })")),a=a||{},this.length=a.length||1,this.radius=a.radius||1,a.type=d.CAPSULE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){var b=this.radius,c=this.length+b,d=2*b;return a*(d*d+c*c)/12},c.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2},c.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+2*this.radius*this.length};var f=e.create();c.prototype.computeAABB=function(a,b,c){var d=this.radius;e.set(f,this.length/2,0),0!==c&&e.rotate(f,f,c),e.set(a.upperBound,Math.max(f[0]+d,-f[0]+d),Math.max(f[1]+d,-f[1]+d)),e.set(a.lowerBound,Math.min(f[0]-d,-f[0]-d),Math.min(f[1]-d,-f[1]-d)),e.add(a.lowerBound,a.lowerBound,b),e.add(a.upperBound,a.upperBound,b)};var g=e.create(),h=e.create(),i=e.create(),j=e.create(),k=e.fromValues(0,1);c.prototype.raycast=function(a,b,c,d){for(var f=b.from,l=b.to,m=(b.direction,g),n=h,o=i,p=j,q=this.length/2,r=0;2>r;r++){var s=this.radius*(2*r-1);e.set(o,-q,s),e.set(p,q,s),e.toGlobalFrame(o,o,c,d),e.toGlobalFrame(p,p,c,d);var t=e.getLineSegmentsIntersectionFraction(f,l,o,p);if(t>=0&&(e.rotate(n,k,d),e.scale(n,n,2*r-1),b.reportIntersection(a,t,n,-1),a.shouldStop(b)))return}for(var u=Math.pow(this.radius,2)+Math.pow(q,2),r=0;2>r;r++){e.set(o,q*(2*r-1),0),e.toGlobalFrame(o,o,c,d);var v=Math.pow(l[0]-f[0],2)+Math.pow(l[1]-f[1],2),w=2*((l[0]-f[0])*(f[0]-o[0])+(l[1]-f[1])*(f[1]-o[1])),x=Math.pow(f[0]-o[0],2)+Math.pow(f[1]-o[1],2)-Math.pow(this.radius,2),t=Math.pow(w,2)-4*v*x;if(!(0>t))if(0===t){if(e.lerp(m,f,l,t),e.squaredDistance(m,c)>u&&(e.sub(n,m,o),e.normalize(n,n),b.reportIntersection(a,t,n,-1),a.shouldStop(b)))return}else{var y=Math.sqrt(t),z=1/(2*v),A=(-w-y)*z,B=(-w+y)*z;if(A>=0&&1>=A&&(e.lerp(m,f,l,A),e.squaredDistance(m,c)>u&&(e.sub(n,m,o),e.normalize(n,n),b.reportIntersection(a,A,n,-1),a.shouldStop(b))))return;if(B>=0&&1>=B&&(e.lerp(m,f,l,B),e.squaredDistance(m,c)>u&&(e.sub(n,m,o),e.normalize(n,n),b.reportIntersection(a,B,n,-1),a.shouldStop(b))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(a,b){function c(a){"number"==typeof arguments[0]&&(a={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),a=a||{},this.radius=a.radius||1,a.type=d.CIRCLE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){var b=this.radius;return a*b*b/2},c.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},c.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},c.prototype.computeAABB=function(a,b){var c=this.radius;e.set(a.upperBound,c,c),e.set(a.lowerBound,-c,-c),b&&(e.add(a.lowerBound,a.lowerBound,b),e.add(a.upperBound,a.upperBound,b))};var f=e.create(),g=e.create();c.prototype.raycast=function(a,b,c){var d=b.from,h=b.to,i=this.radius,j=Math.pow(h[0]-d[0],2)+Math.pow(h[1]-d[1],2),k=2*((h[0]-d[0])*(d[0]-c[0])+(h[1]-d[1])*(d[1]-c[1])),l=Math.pow(d[0]-c[0],2)+Math.pow(d[1]-c[1],2)-Math.pow(i,2),m=Math.pow(k,2)-4*j*l,n=f,o=g;if(!(0>m))if(0===m)e.lerp(n,d,h,m),e.sub(o,n,c),e.normalize(o,o),b.reportIntersection(a,m,o,-1);else{var p=Math.sqrt(m),q=1/(2*j),r=(-k-p)*q,s=(-k+p)*q;if(r>=0&&1>=r&&(e.lerp(n,d,h,r),e.sub(o,n,c),e.normalize(o,o),b.reportIntersection(a,r,o,-1),a.shouldStop(b)))return;s>=0&&1>=s&&(e.lerp(n,d,h,s),e.sub(o,n,c),e.normalize(o,o),b.reportIntersection(a,s,o,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(a,b){function c(a){Array.isArray(arguments[0])&&(a={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),a=a||{},this.vertices=[];for(var b=void 0!==a.vertices?a.vertices:[],c=0;c<b.length;c++){var f=e.create();e.copy(f,b[c]),this.vertices.push(f)}if(this.axes=[],a.axes)for(var c=0;c<a.axes.length;c++){var g=e.create();e.copy(g,a.axes[c]),this.axes.push(g)}else for(var c=0;c<this.vertices.length;c++){var h=this.vertices[c],i=this.vertices[(c+1)%this.vertices.length],j=e.create();e.sub(j,i,h),e.rotate90cw(j,j),e.normalize(j,j),this.axes.push(j)}if(this.centerOfMass=e.fromValues(0,0),this.triangles=[],this.vertices.length&&(this.updateTriangles(),this.updateCenterOfMass()),this.boundingRadius=0,a.type=d.CONVEX,d.call(this,a),this.updateBoundingRadius(),this.updateArea(),this.area<0)throw new Error("Convex vertices must be given in conter-clockwise winding.")}{var d=a("./Shape"),e=a("../math/vec2"),f=a("../math/polyk");a("poly-decomp")}b.exports=c,c.prototype=new d,c.prototype.constructor=c;var g=e.create(),h=e.create();c.prototype.projectOntoLocalAxis=function(a,b){for(var c,d,f=null,h=null,a=g,i=0;i<this.vertices.length;i++)c=this.vertices[i],d=e.dot(c,a),(null===f||d>f)&&(f=d),(null===h||h>d)&&(h=d);if(h>f){var j=h;h=f,f=j}e.set(b,h,f)},c.prototype.projectOntoWorldAxis=function(a,b,c,d){var f=h;this.projectOntoLocalAxis(a,d),0!==c?e.rotate(f,a,c):f=a;var g=e.dot(b,f);e.set(d,d[0]+g,d[1]+g)},c.prototype.updateTriangles=function(){this.triangles.length=0;for(var a=[],b=0;b<this.vertices.length;b++){var c=this.vertices[b];a.push(c[0],c[1])}for(var d=f.Triangulate(a),b=0;b<d.length;b+=3){var e=d[b],g=d[b+1],h=d[b+2];this.triangles.push([e,g,h])}};{var i=e.create(),j=e.create(),k=e.create(),l=e.create(),m=e.create();e.create(),e.create(),e.create(),e.create()}c.prototype.updateCenterOfMass=function(){var a=this.triangles,b=this.vertices,d=this.centerOfMass,f=i,g=k,h=l,n=m,o=j;e.set(d,0,0);for(var p=0,q=0;q!==a.length;q++){var r=a[q],g=b[r[0]],h=b[r[1]],n=b[r[2]];e.centroid(f,g,h,n);var s=c.triangleArea(g,h,n);p+=s,e.scale(o,f,s),e.add(d,d,o)}e.scale(d,d,1/p)},c.prototype.computeMomentOfInertia=function(a){for(var b=0,c=0,d=this.vertices.length,f=d-1,g=0;d>g;f=g,g++){var h=this.vertices[f],i=this.vertices[g],j=Math.abs(e.crossLength(h,i)),k=e.dot(i,i)+e.dot(i,h)+e.dot(h,h);b+=j*k,c+=j}return a/6*(b/c)},c.prototype.updateBoundingRadius=function(){for(var a=this.vertices,b=0,c=0;c!==a.length;c++){var d=e.squaredLength(a[c]);d>b&&(b=d)}this.boundingRadius=Math.sqrt(b)},c.triangleArea=function(a,b,c){return.5*((b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]))},c.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var a=this.triangles,b=this.vertices,d=0;d!==a.length;d++){var e=a[d],f=b[e[0]],g=b[e[1]],h=b[e[2]],i=c.triangleArea(f,g,h);this.area+=i}},c.prototype.computeAABB=function(a,b,c){a.setFromPoints(this.vertices,b,c,0)};var n=e.create(),o=e.create(),p=e.create();c.prototype.raycast=function(a,b,c,d){var f=n,g=o,h=p,i=this.vertices;e.toLocalFrame(f,b.from,c,d),e.toLocalFrame(g,b.to,c,d);for(var j=i.length,k=0;j>k&&!a.shouldStop(b);k++){var l=i[k],m=i[(k+1)%j],q=e.getLineSegmentsIntersectionFraction(f,g,l,m);q>=0&&(e.sub(h,m,l),e.rotate(h,h,-Math.PI/2+d),e.normalize(h,h),b.reportIntersection(a,q,h,k))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(a,b){function c(a){if(Array.isArray(arguments[0])){if(a={heights:arguments[0]},"object"==typeof arguments[1])for(var b in arguments[1])a[b]=arguments[1][b];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}a=a||{},this.heights=a.heights?a.heights.slice(0):[],this.maxValue=a.maxValue||null,this.minValue=a.minValue||null,this.elementWidth=a.elementWidth||.1,(void 0===a.maxValue||void 0===a.minValue)&&this.updateMaxMinValues(),a.type=d.HEIGHTFIELD,d.call(this,a)}{var d=a("./Shape"),e=a("../math/vec2");a("../utils/Utils")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.updateMaxMinValues=function(){for(var a=this.heights,b=a[0],c=a[0],d=0;d!==a.length;d++){var e=a[d];e>b&&(b=e),c>e&&(c=e)}this.maxValue=b,this.minValue=c},c.prototype.computeMomentOfInertia=function(){return Number.MAX_VALUE},c.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},c.prototype.updateArea=function(){for(var a=this.heights,b=0,c=0;c<a.length-1;c++)b+=(a[c]+a[c+1])/2*this.elementWidth;this.area=b};var f=[e.create(),e.create(),e.create(),e.create()];c.prototype.computeAABB=function(a,b,c){e.set(f[0],0,this.maxValue),e.set(f[1],this.elementWidth*this.heights.length,this.maxValue),e.set(f[2],this.elementWidth*this.heights.length,this.minValue),e.set(f[3],0,this.minValue),a.setFromPoints(f,b,c)},c.prototype.getLineSegment=function(a,b,c){var d=this.heights,f=this.elementWidth;e.set(a,c*f,d[c]),e.set(b,(c+1)*f,d[c+1])},c.prototype.getSegmentIndex=function(a){return Math.floor(a[0]/this.elementWidth)},c.prototype.getClampedSegmentIndex=function(a){var b=this.getSegmentIndex(a);return b=Math.min(this.heights.length,Math.max(b,0))};{var g=(e.create(),e.create()),h=e.create(),i=e.create(),j=e.create(),k=e.create();e.fromValues(0,1)}c.prototype.raycast=function(a,b,c,d){var f=b.from,l=b.to,m=(b.direction,g),n=h,o=i,p=j,q=k;e.toLocalFrame(p,f,c,d),e.toLocalFrame(q,l,c,d);var r=this.getClampedSegmentIndex(p),s=this.getClampedSegmentIndex(q);if(r>s){var t=r;r=s,s=t}for(var u=0;u<this.heights.length-1;u++){this.getLineSegment(n,o,u);var v=e.getLineSegmentsIntersectionFraction(p,q,n,o);if(v>=0&&(e.sub(m,o,n),e.rotate(m,m,d+Math.PI/2),e.normalize(m,m),b.reportIntersection(a,v,m,-1),a.shouldStop(b)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(a,b){function c(a){"number"==typeof arguments[0]&&(a={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),a=a||{},this.length=a.length||1,a.type=d.LINE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(a){return a*Math.pow(this.length,2)/12},c.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var f=[e.create(),e.create()];c.prototype.computeAABB=function(a,b,c){var d=this.length/2;e.set(f[0],-d,0),e.set(f[1],d,0),a.setFromPoints(f,b,c,0)};var g=(e.create(),e.create()),h=e.create(),i=e.create(),j=e.fromValues(0,1);c.prototype.raycast=function(a,b,c,d){var f=b.from,k=b.to,l=h,m=i,n=this.length/2;e.set(l,-n,0),e.set(m,n,0),e.toGlobalFrame(l,l,c,d),e.toGlobalFrame(m,m,c,d);var o=e.getLineSegmentsIntersectionFraction(l,m,f,k);if(o>=0){var p=g;e.rotate(p,j,d),b.reportIntersection(a,o,p,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(a,b){function c(a){a=a||{},a.type=d.PARTICLE,d.call(this,a)}var d=a("./Shape"),e=a("../math/vec2");b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(){return 0},c.prototype.updateBoundingRadius=function(){this.boundingRadius=0},c.prototype.computeAABB=function(a,b){e.copy(a.lowerBound,b),e.copy(a.upperBound,b)}},{"../math/vec2":30,"./Shape":45}],44:[function(a,b){function c(a){a=a||{},a.type=d.PLANE,d.call(this,a)}{var d=a("./Shape"),e=a("../math/vec2");a("../utils/Utils")}b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.computeMomentOfInertia=function(){return 0},c.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},c.prototype.computeAABB=function(a,b,c){var d=c%(2*Math.PI),f=e.set,g=Number.MAX_VALUE,h=a.lowerBound,i=a.upperBound;0===d?(f(h,-g,-g),f(i,g,0)):d===Math.PI/2?(f(h,0,-g),f(i,g,g)):d===Math.PI?(f(h,-g,0),f(i,g,g)):d===3*Math.PI/2?(f(h,-g,-g),f(i,0,g)):(f(h,-g,-g),f(i,g,g)),e.add(h,h,b),e.add(i,i,b)},c.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var f=e.create(),g=(e.create(),e.create(),e.create()),h=e.create();c.prototype.raycast=function(a,b,c,d){var i=b.from,j=b.to,k=b.direction,l=f,m=g,n=h;e.set(m,0,1),e.rotate(m,m,d),e.sub(n,i,c);var o=e.dot(n,m);e.sub(n,j,c);var p=e.dot(n,m);if(!(o*p>0||e.squaredDistance(i,j)<o*o)){var q=e.dot(m,k);e.sub(l,i,c);var r=-e.dot(m,l)/q/b.length;b.reportIntersection(a,r,m,-1)}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(a,b){function c(a){a=a||{},this.body=null,this.position=d.fromValues(0,0),a.position&&d.copy(this.position,a.position),this.angle=a.angle||0,this.type=a.type||0,this.id=c.idCounter++,this.boundingRadius=0,this.collisionGroup=void 0!==a.collisionGroup?a.collisionGroup:1,this.collisionResponse=void 0!==a.collisionResponse?a.collisionResponse:!0,this.collisionMask=void 0!==a.collisionMask?a.collisionMask:1,this.material=a.material||null,this.area=0,this.sensor=void 0!==a.sensor?a.sensor:!1,this.type&&this.updateBoundingRadius(),this.updateArea()}b.exports=c;var d=a("../math/vec2");c.idCounter=0,c.CIRCLE=1,c.PARTICLE=2,c.PLANE=4,c.CONVEX=8,c.LINE=16,c.BOX=32,Object.defineProperty(c,"RECTANGLE",{get:function(){return console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead."),c.BOX}}),c.CAPSULE=64,c.HEIGHTFIELD=128,c.prototype.computeMomentOfInertia=function(){},c.prototype.updateBoundingRadius=function(){},c.prototype.updateArea=function(){},c.prototype.computeAABB=function(){},c.prototype.raycast=function(){}},{"../math/vec2":30}],46:[function(a,b){function c(a){f.call(this,a,f.GS),a=a||{},this.iterations=a.iterations||10,this.tolerance=a.tolerance||1e-7,this.arrayStep=30,this.lambda=new g.ARRAY_TYPE(this.arrayStep),this.Bs=new g.ARRAY_TYPE(this.arrayStep),this.invCs=new g.ARRAY_TYPE(this.arrayStep),this.useZeroRHS=!1,this.frictionIterations=0,this.usedIterations=0}function d(a){for(var b=a.length;b--;)a[b]=0}var e=a("../math/vec2"),f=a("./Solver"),g=a("../utils/Utils"),h=a("../equations/FrictionEquation");b.exports=c,c.prototype=new f,c.prototype.constructor=c,c.prototype.solve=function(a,b){this.sortEquations();var f=0,i=this.iterations,j=this.frictionIterations,k=this.equations,l=k.length,m=Math.pow(this.tolerance*l,2),n=b.bodies,o=b.bodies.length,p=(e.add,e.set,this.useZeroRHS),q=this.lambda;if(this.usedIterations=0,l)for(var r=0;r!==o;r++){var s=n[r];s.updateSolveMassProperties()}q.length<l&&(q=this.lambda=new g.ARRAY_TYPE(l+this.arrayStep),this.Bs=new g.ARRAY_TYPE(l+this.arrayStep),this.invCs=new g.ARRAY_TYPE(l+this.arrayStep)),d(q);
+for(var t=this.invCs,u=this.Bs,q=this.lambda,r=0;r!==k.length;r++){var v=k[r];(v.timeStep!==a||v.needsUpdate)&&(v.timeStep=a,v.update()),u[r]=v.computeB(v.a,v.b,a),t[r]=v.computeInvC(v.epsilon)}var v,w,r,x;if(0!==l){for(r=0;r!==o;r++){var s=n[r];s.resetConstraintVelocity()}if(j){for(f=0;f!==j;f++){for(w=0,x=0;x!==l;x++){v=k[x];var y=c.iterateEquation(x,v,v.epsilon,u,t,q,p,a,f);w+=Math.abs(y)}if(this.usedIterations++,m>=w*w)break}for(c.updateMultipliers(k,q,1/a),x=0;x!==l;x++){var z=k[x];if(z instanceof h){for(var A=0,B=0;B!==z.contactEquations.length;B++)A+=z.contactEquations[B].multiplier;A*=z.frictionCoefficient/z.contactEquations.length,z.maxForce=A,z.minForce=-A}}}for(f=0;f!==i;f++){for(w=0,x=0;x!==l;x++){v=k[x];var y=c.iterateEquation(x,v,v.epsilon,u,t,q,p,a,f);w+=Math.abs(y)}if(this.usedIterations++,m>=w*w)break}for(r=0;r!==o;r++)n[r].addConstraintVelocity();c.updateMultipliers(k,q,1/a)}},c.updateMultipliers=function(a,b,c){for(var d=a.length;d--;)a[d].multiplier=b[d]*c},c.iterateEquation=function(a,b,c,d,e,f,g,h){var i=d[a],j=e[a],k=f[a],l=b.computeGWlambda(),m=b.maxForce,n=b.minForce;g&&(i=0);var o=j*(i-l-c*k),p=k+o;return n*h>p?o=n*h-k:p>m*h&&(o=m*h-k),f[a]+=o,b.addToWlambda(o),o}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(a,b){function c(a,b){a=a||{},d.call(this),this.type=b,this.equations=[],this.equationSortFunction=a.equationSortFunction||!1}var d=(a("../utils/Utils"),a("../events/EventEmitter"));b.exports=c,c.prototype=new d,c.prototype.constructor=c,c.prototype.solve=function(){throw new Error("Solver.solve should be implemented by subclasses!")};var e={bodies:[]};c.prototype.solveIsland=function(a,b){this.removeAllEquations(),b.equations.length&&(this.addEquations(b.equations),e.bodies.length=0,b.getBodies(e.bodies),e.bodies.length&&this.solve(a,e))},c.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},c.prototype.addEquation=function(a){a.enabled&&this.equations.push(a)},c.prototype.addEquations=function(a){for(var b=0,c=a.length;b!==c;b++){var d=a[b];d.enabled&&this.equations.push(d)}},c.prototype.removeEquation=function(a){var b=this.equations.indexOf(a);-1!==b&&this.equations.splice(b,1)},c.prototype.removeAllEquations=function(){this.equations.length=0},c.GS=1,c.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../equations/ContactEquation"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.bodyA=a.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../equations/FrictionEquation"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.bodyA=a.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../world/IslandNode"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(a,b){function c(){e.apply(this,arguments)}var d=a("../world/Island"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(a,b){function c(){this.overlappingShapesLastState=new d,this.overlappingShapesCurrentState=new d,this.recordPool=new e({size:16}),this.tmpDict=new d,this.tmpArray1=[]}{var d=a("./TupleDictionary"),e=(a("./OverlapKeeperRecord"),a("./OverlapKeeperRecordPool"));a("./Utils")}b.exports=c,c.prototype.tick=function(){for(var a=this.overlappingShapesLastState,b=this.overlappingShapesCurrentState,c=a.keys.length;c--;){{var d=a.keys[c],e=a.getByKey(d);b.getByKey(d)}e&&this.recordPool.release(e)}a.reset(),a.copy(b),b.reset()},c.prototype.setOverlapping=function(a,b,c,d){var e=(this.overlappingShapesLastState,this.overlappingShapesCurrentState);if(!e.get(b.id,d.id)){var f=this.recordPool.get();f.set(a,b,c,d),e.set(b.id,d.id,f)}},c.prototype.getNewOverlaps=function(a){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,a)},c.prototype.getEndOverlaps=function(a){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,a)},c.prototype.bodiesAreOverlapping=function(a,b){for(var c=this.overlappingShapesCurrentState,d=c.keys.length;d--;){var e=c.keys[d],f=c.data[e];if(f.bodyA===a&&f.bodyB===b||f.bodyA===b&&f.bodyB===a)return!0}return!1},c.prototype.getDiff=function(a,b,c){var c=c||[],d=a,e=b;c.length=0;for(var f=e.keys.length;f--;){var g=e.keys[f],h=e.data[g];if(!h)throw new Error("Key "+g+" had no data!");var i=d.data[g];i||c.push(h)}return c},c.prototype.isNewOverlap=function(a,b){var c=0|a.id,d=0|b.id,e=this.overlappingShapesLastState,f=this.overlappingShapesCurrentState;return!e.get(c,d)&&!!f.get(c,d)},c.prototype.getNewBodyOverlaps=function(a){this.tmpArray1.length=0;var b=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(b,a)},c.prototype.getEndBodyOverlaps=function(a){this.tmpArray1.length=0;var b=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(b,a)},c.prototype.getBodyDiff=function(a,b){b=b||[];for(var c=this.tmpDict,d=a.length;d--;){var e=a[d];c.set(0|e.bodyA.id,0|e.bodyB.id,e)}for(d=c.keys.length;d--;){var e=c.getByKey(c.keys[d]);e&&b.push(e.bodyA,e.bodyB)}return c.reset(),b}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(a,b){function c(a,b,c,d){this.shapeA=b,this.shapeB=d,this.bodyA=a,this.bodyB=c}b.exports=c,c.prototype.set=function(a,b,d,e){c.call(this,a,b,d,e)}},{}],54:[function(a,b){function c(){e.apply(this,arguments)}var d=a("./OverlapKeeperRecord"),e=a("./Pool");b.exports=c,c.prototype=new e,c.prototype.constructor=c,c.prototype.create=function(){return new d},c.prototype.destroy=function(a){return a.bodyA=a.bodyB=a.shapeA=a.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(a,b){function c(a){a=a||{},this.objects=[],void 0!==a.size&&this.resize(a.size)}b.exports=c,c.prototype.resize=function(a){for(var b=this.objects;b.length>a;)b.pop();for(;b.length<a;)b.push(this.create());return this},c.prototype.get=function(){var a=this.objects;return a.length?a.pop():this.create()},c.prototype.release=function(a){return this.destroy(a),this.objects.push(a),this}},{}],56:[function(a,b){function c(){this.data={},this.keys=[]}var d=a("./Utils");b.exports=c,c.prototype.getKey=function(a,b){return a=0|a,b=0|b,(0|a)===(0|b)?-1:0|((0|a)>(0|b)?a<<16|65535&b:b<<16|65535&a)},c.prototype.getByKey=function(a){return a=0|a,this.data[a]},c.prototype.get=function(a,b){return this.data[this.getKey(a,b)]},c.prototype.set=function(a,b,c){if(!c)throw new Error("No data!");var d=this.getKey(a,b);return this.data[d]||this.keys.push(d),this.data[d]=c,d},c.prototype.reset=function(){for(var a=this.data,b=this.keys,c=b.length;c--;)delete a[b[c]];b.length=0},c.prototype.copy=function(a){this.reset(),d.appendArray(this.keys,a.keys);for(var b=a.keys.length;b--;){var c=a.keys[b];this.data[c]=a.data[c]}}},{"./Utils":57}],57:[function(a,b){function c(){}b.exports=c,c.appendArray=function(a,b){if(b.length<15e4)a.push.apply(a,b);else for(var c=0,d=b.length;c!==d;++c)a.push(b[c])},c.splice=function(a,b,c){c=c||1;for(var d=b,e=a.length-c;e>d;d++)a[d]=a[d+c];a.length=e},c.ARRAY_TYPE="undefined"!=typeof P2_ARRAY_TYPE?P2_ARRAY_TYPE:"undefined"!=typeof Float32Array?Float32Array:Array,c.extend=function(a,b){for(var c in b)a[c]=b[c]},c.defaults=function(a,b){a=a||{};for(var c in b)c in a||(a[c]=b[c]);return a}},{}],58:[function(a,b){function c(){this.equations=[],this.bodies=[]}var d=a("../objects/Body");b.exports=c,c.prototype.reset=function(){this.equations.length=this.bodies.length=0};var e=[];c.prototype.getBodies=function(a){var b=a||[],c=this.equations;e.length=0;for(var d=0;d!==c.length;d++){var f=c[d];-1===e.indexOf(f.bodyA.id)&&(b.push(f.bodyA),e.push(f.bodyA.id)),-1===e.indexOf(f.bodyB.id)&&(b.push(f.bodyB),e.push(f.bodyB.id))}return b},c.prototype.wantsToSleep=function(){for(var a=0;a<this.bodies.length;a++){var b=this.bodies[a];if(b.type===d.DYNAMIC&&!b.wantsToSleep)return!1}return!0},c.prototype.sleep=function(){for(var a=0;a<this.bodies.length;a++){var b=this.bodies[a];b.sleep()}return!0}},{"../objects/Body":31}],59:[function(a,b){function c(){this.nodePool=new d({size:16}),this.islandPool=new e({size:8}),this.equations=[],this.islands=[],this.nodes=[],this.queue=[]}var d=(a("../math/vec2"),a("./Island"),a("./IslandNode"),a("./../utils/IslandNodePool")),e=a("./../utils/IslandPool"),f=a("../objects/Body");b.exports=c,c.getUnvisitedNode=function(a){for(var b=a.length,c=0;c!==b;c++){var d=a[c];if(!d.visited&&d.body.type===f.DYNAMIC)return d}return!1},c.prototype.visit=function(a,b,c){b.push(a.body);for(var d=a.equations.length,e=0;e!==d;e++){var f=a.equations[e];-1===c.indexOf(f)&&c.push(f)}},c.prototype.bfs=function(a,b,d){var e=this.queue;for(e.length=0,e.push(a),a.visited=!0,this.visit(a,b,d);e.length;)for(var g,h=e.pop();g=c.getUnvisitedNode(h.neighbors);)g.visited=!0,this.visit(g,b,d),g.body.type===f.DYNAMIC&&e.push(g)},c.prototype.split=function(a){for(var b=a.bodies,d=this.nodes,e=this.equations;d.length;)this.nodePool.release(d.pop());for(var f=0;f!==b.length;f++){var g=this.nodePool.get();g.body=b[f],d.push(g)}for(var h=0;h!==e.length;h++){var i=e[h],f=b.indexOf(i.bodyA),j=b.indexOf(i.bodyB),k=d[f],l=d[j];k.neighbors.push(l),l.neighbors.push(k),k.equations.push(i),l.equations.push(i)}for(var m=this.islands,f=0;f<m.length;f++)this.islandPool.release(m[f]);m.length=0;for(var n;n=c.getUnvisitedNode(d);){var o=this.islandPool.get();this.bfs(n,o.bodies,o.equations),m.push(o)}return m}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(a,b){function c(a){this.body=a,this.neighbors=[],this.equations=[],this.visited=!1}b.exports=c,c.prototype.reset=function(){this.equations.length=0,this.neighbors.length=0,this.visited=!1,this.body=null}},{}],61:[function(a,b){function c(a){k.apply(this),a=a||{},this.springs=[],this.bodies=[],this.disabledBodyCollisionPairs=[],this.solver=a.solver||new d,this.narrowphase=new q(this),this.islandManager=new t,this.gravity=e.fromValues(0,-9.78),a.gravity&&e.copy(this.gravity,a.gravity),this.frictionGravity=e.length(this.gravity)||10,this.useWorldGravityAsFrictionGravity=!0,this.useFrictionGravityOnZeroGravity=!0,this.broadphase=a.broadphase||new p,this.broadphase.setWorld(this),this.constraints=[],this.defaultMaterial=new m,this.defaultContactMaterial=new n(this.defaultMaterial,this.defaultMaterial),this.lastTimeStep=1/60,this.applySpringForces=!0,this.applyDamping=!0,this.applyGravity=!0,this.solveConstraints=!0,this.contactMaterials=[],this.time=0,this.accumulator=0,this.stepping=!1,this.bodiesToBeRemoved=[],this.islandSplit="undefined"!=typeof a.islandSplit?!!a.islandSplit:!0,this.emitImpactEvent=!0,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=c.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 s}{var d=a("../solver/GSSolver"),e=(a("../solver/Solver"),a("../collision/Ray"),a("../math/vec2")),f=a("../shapes/Circle"),g=a("../shapes/Convex"),h=(a("../shapes/Line"),a("../shapes/Plane")),i=a("../shapes/Capsule"),j=a("../shapes/Particle"),k=a("../events/EventEmitter"),l=a("../objects/Body"),m=(a("../shapes/Shape"),a("../objects/LinearSpring"),a("../material/Material")),n=a("../material/ContactMaterial"),o=(a("../constraints/DistanceConstraint"),a("../constraints/Constraint"),a("../constraints/LockConstraint"),a("../constraints/RevoluteConstraint"),a("../constraints/PrismaticConstraint"),a("../constraints/GearConstraint"),a("../../package.json"),a("../collision/Broadphase"),a("../collision/AABB")),p=a("../collision/SAPBroadphase"),q=a("../collision/Narrowphase"),r=a("../utils/Utils"),s=a("../utils/OverlapKeeper"),t=a("./IslandManager");a("../objects/RotationalSpring")}b.exports=c,c.prototype=new Object(k.prototype),c.prototype.constructor=c,c.NO_SLEEPING=1,c.BODY_SLEEPING=2,c.ISLAND_SLEEPING=4,c.prototype.addConstraint=function(a){this.constraints.push(a)},c.prototype.addContactMaterial=function(a){this.contactMaterials.push(a)},c.prototype.removeContactMaterial=function(a){var b=this.contactMaterials.indexOf(a);-1!==b&&r.splice(this.contactMaterials,b,1)},c.prototype.getContactMaterial=function(a,b){for(var c=this.contactMaterials,d=0,e=c.length;d!==e;d++){var f=c[d];if(f.materialA.id===a.id&&f.materialB.id===b.id||f.materialA.id===b.id&&f.materialB.id===a.id)return f}return!1},c.prototype.removeConstraint=function(a){var b=this.constraints.indexOf(a);-1!==b&&r.splice(this.constraints,b,1)};{var u=(e.create(),e.create(),e.create(),e.create(),e.create(),e.create(),e.create()),v=e.fromValues(0,0),w=e.fromValues(0,0);e.fromValues(0,0),e.fromValues(0,0)}c.prototype.step=function(a,b,c){if(c=c||10,b=b||0,0===b)this.internalStep(a),this.time+=a;else{this.accumulator+=b;for(var d=0;this.accumulator>=a&&c>d;)this.internalStep(a),this.time+=a,this.accumulator-=a,d++;for(var f=this.accumulator%a/a,g=0;g!==this.bodies.length;g++){var h=this.bodies[g];e.lerp(h.interpolatedPosition,h.previousPosition,h.position,f),h.interpolatedAngle=h.previousAngle+f*(h.angle-h.previousAngle)}}};var x=[];c.prototype.internalStep=function(a){this.stepping=!0;var b=this.springs.length,d=this.springs,f=this.bodies,g=this.gravity,h=this.solver,i=this.bodies.length,j=this.broadphase,k=this.narrowphase,m=this.constraints,n=u,o=(e.scale,e.add),p=(e.rotate,this.islandManager);if(this.overlapKeeper.tick(),this.lastTimeStep=a,this.useWorldGravityAsFrictionGravity){var q=e.length(this.gravity);0===q&&this.useFrictionGravityOnZeroGravity||(this.frictionGravity=q)}if(this.applyGravity)for(var s=0;s!==i;s++){var t=f[s],v=t.force;t.type===l.DYNAMIC&&t.sleepState!==l.SLEEPING&&(e.scale(n,g,t.mass*t.gravityScale),o(v,v,n))}if(this.applySpringForces)for(var s=0;s!==b;s++){var w=d[s];w.applyForce()}if(this.applyDamping)for(var s=0;s!==i;s++){var t=f[s];t.type===l.DYNAMIC&&t.applyDamping(a)}for(var y=j.getCollisionPairs(this),z=this.disabledBodyCollisionPairs,s=z.length-2;s>=0;s-=2)for(var A=y.length-2;A>=0;A-=2)(z[s]===y[A]&&z[s+1]===y[A+1]||z[s+1]===y[A]&&z[s]===y[A+1])&&y.splice(A,2);var B=m.length;for(s=0;s!==B;s++){var C=m[s];if(!C.collideConnected)for(var A=y.length-2;A>=0;A-=2)(C.bodyA===y[A]&&C.bodyB===y[A+1]||C.bodyB===y[A]&&C.bodyA===y[A+1])&&y.splice(A,2)}this.postBroadphaseEvent.pairs=y,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,k.reset(this);for(var s=0,D=y.length;s!==D;s+=2)for(var E=y[s],F=y[s+1],G=0,H=E.shapes.length;G!==H;G++)for(var I=E.shapes[G],J=I.position,K=I.angle,L=0,M=F.shapes.length;L!==M;L++){var N=F.shapes[L],O=N.position,P=N.angle,Q=this.defaultContactMaterial;if(I.material&&N.material){var R=this.getContactMaterial(I.material,N.material);R&&(Q=R)}this.runNarrowphase(k,E,I,J,K,F,N,O,P,Q,this.frictionGravity)}for(var s=0;s!==i;s++){var S=f[s];S._wakeUpAfterNarrowphase&&(S.wakeUp(),S._wakeUpAfterNarrowphase=!1)}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(x);for(var T=this.endContactEvent,L=x.length;L--;){var U=x[L];T.shapeA=U.shapeA,T.shapeB=U.shapeB,T.bodyA=U.bodyA,T.bodyB=U.bodyB,this.emit(T)}x.length=0}var V=this.preSolveEvent;V.contactEquations=k.contactEquations,V.frictionEquations=k.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var B=m.length;for(s=0;s!==B;s++)m[s].update();if(k.contactEquations.length||k.frictionEquations.length||B)if(this.islandSplit){for(p.equations.length=0,r.appendArray(p.equations,k.contactEquations),r.appendArray(p.equations,k.frictionEquations),s=0;s!==B;s++)r.appendArray(p.equations,m[s].equations);p.split(this);for(var s=0;s!==p.islands.length;s++){var W=p.islands[s];W.equations.length&&h.solveIsland(a,W)}}else{for(h.addEquations(k.contactEquations),h.addEquations(k.frictionEquations),s=0;s!==B;s++)h.addEquations(m[s].equations);this.solveConstraints&&h.solve(a,this),h.removeAllEquations()}for(var s=0;s!==i;s++){var S=f[s];S.integrate(a)}for(var s=0;s!==i;s++)f[s].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var X=this.impactEvent,s=0;s!==k.contactEquations.length;s++){var Y=k.contactEquations[s];Y.firstImpact&&(X.bodyA=Y.bodyA,X.bodyB=Y.bodyB,X.shapeA=Y.shapeA,X.shapeB=Y.shapeB,X.contactEquation=Y,this.emit(X))}if(this.sleepMode===c.BODY_SLEEPING)for(s=0;s!==i;s++)f[s].sleepTick(this.time,!1,a);else if(this.sleepMode===c.ISLAND_SLEEPING&&this.islandSplit){for(s=0;s!==i;s++)f[s].sleepTick(this.time,!0,a);for(var s=0;s<this.islandManager.islands.length;s++){var W=this.islandManager.islands[s];W.wantsToSleep()&&W.sleep()}}this.stepping=!1;for(var Z=this.bodiesToBeRemoved,s=0;s!==Z.length;s++)this.removeBody(Z[s]);Z.length=0,this.emit(this.postStepEvent)},c.prototype.runNarrowphase=function(a,b,c,d,f,g,h,i,j,k,m){if(0!==(c.collisionGroup&h.collisionMask)&&0!==(h.collisionGroup&c.collisionMask)){e.rotate(v,d,b.angle),e.rotate(w,i,g.angle),e.add(v,v,b.position),e.add(w,w,g.position);var n=f+b.angle,o=j+g.angle;a.enableFriction=k.friction>0,a.frictionCoefficient=k.friction;var p;p=b.type===l.STATIC||b.type===l.KINEMATIC?g.mass:g.type===l.STATIC||g.type===l.KINEMATIC?b.mass:b.mass*g.mass/(b.mass+g.mass),a.slipForce=k.friction*m*p,a.restitution=k.restitution,a.surfaceVelocity=k.surfaceVelocity,a.frictionStiffness=k.frictionStiffness,a.frictionRelaxation=k.frictionRelaxation,a.stiffness=k.stiffness,a.relaxation=k.relaxation,a.contactSkinSize=k.contactSkinSize,a.enabledEquations=b.collisionResponse&&g.collisionResponse&&c.collisionResponse&&h.collisionResponse;var q=a[c.type|h.type],r=0;if(q){var s=c.sensor||h.sensor,t=a.frictionEquations.length;r=c.type<h.type?q.call(a,b,c,v,n,g,h,w,o,s):q.call(a,g,h,w,o,b,c,v,n,s);var u=a.frictionEquations.length-t;if(r){if(b.allowSleep&&b.type===l.DYNAMIC&&b.sleepState===l.SLEEPING&&g.sleepState===l.AWAKE&&g.type!==l.STATIC){var x=e.squaredLength(g.velocity)+Math.pow(g.angularVelocity,2),y=Math.pow(g.sleepSpeedLimit,2);x>=2*y&&(b._wakeUpAfterNarrowphase=!0)}if(g.allowSleep&&g.type===l.DYNAMIC&&g.sleepState===l.SLEEPING&&b.sleepState===l.AWAKE&&b.type!==l.STATIC){var z=e.squaredLength(b.velocity)+Math.pow(b.angularVelocity,2),A=Math.pow(b.sleepSpeedLimit,2);z>=2*A&&(g._wakeUpAfterNarrowphase=!0)}if(this.overlapKeeper.setOverlapping(b,c,g,h),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(c,h)){var B=this.beginContactEvent;if(B.shapeA=c,B.shapeB=h,B.bodyA=b,B.bodyB=g,B.contactEquations.length=0,"number"==typeof r)for(var C=a.contactEquations.length-r;C<a.contactEquations.length;C++)B.contactEquations.push(a.contactEquations[C]);this.emit(B)}if("number"==typeof r&&u>1)for(var C=a.frictionEquations.length-u;C<a.frictionEquations.length;C++){var D=a.frictionEquations[C];D.setSlipForce(D.getSlipForce()/u)}}}}},c.prototype.addSpring=function(a){this.springs.push(a);var b=this.addSpringEvent;b.spring=a,this.emit(b),b.spring=null},c.prototype.removeSpring=function(a){var b=this.springs.indexOf(a);-1!==b&&r.splice(this.springs,b,1)},c.prototype.addBody=function(a){if(-1===this.bodies.indexOf(a)){this.bodies.push(a),a.world=this;var b=this.addBodyEvent;b.body=a,this.emit(b),b.body=null}},c.prototype.removeBody=function(a){if(this.stepping)this.bodiesToBeRemoved.push(a);else{a.world=null;var b=this.bodies.indexOf(a);-1!==b&&(r.splice(this.bodies,b,1),this.removeBodyEvent.body=a,a.resetConstraintVelocity(),this.emit(this.removeBodyEvent),this.removeBodyEvent.body=null)}},c.prototype.getBodyById=function(a){for(var b=this.bodies,c=0;c<b.length;c++){var d=b[c];if(d.id===a)return d}return!1},c.prototype.disableBodyCollision=function(a,b){this.disabledBodyCollisionPairs.push(a,b)},c.prototype.enableBodyCollision=function(a,b){for(var c=this.disabledBodyCollisionPairs,d=0;d<c.length;d+=2)if(c[d]===a&&c[d+1]===b||c[d+1]===a&&c[d]===b)return void c.splice(d,2)},c.prototype.clear=function(){this.time=0,this.solver&&this.solver.equations.length&&this.solver.removeAllEquations();for(var a=this.constraints,b=a.length-1;b>=0;b--)this.removeConstraint(a[b]);for(var d=this.bodies,b=d.length-1;b>=0;b--)this.removeBody(d[b]);for(var e=this.springs,b=e.length-1;b>=0;b--)this.removeSpring(e[b]);for(var f=this.contactMaterials,b=f.length-1;b>=0;b--)this.removeContactMaterial(f[b]);c.apply(this)};var y=e.create(),z=(e.fromValues(0,0),e.fromValues(0,0));c.prototype.hitTest=function(a,b,c){c=c||0;var d=new l({position:a}),k=new j,m=a,n=0,o=y,p=z;d.addShape(k);for(var q=this.narrowphase,r=[],s=0,t=b.length;s!==t;s++)for(var u=b[s],v=0,w=u.shapes.length;v!==w;v++){var x=u.shapes[v];e.rotate(o,x.position,u.angle),e.add(o,o,u.position);var A=x.angle+u.angle;(x instanceof f&&q.circleParticle(u,x,o,A,d,k,m,n,!0)||x instanceof g&&q.particleConvex(d,k,m,n,u,x,o,A,!0)||x instanceof h&&q.particlePlane(d,k,m,n,u,x,o,A,!0)||x instanceof i&&q.particleCapsule(d,k,m,n,u,x,o,A,!0)||x instanceof j&&e.squaredLength(e.sub(p,o,a))<c*c)&&r.push(u)}return r},c.prototype.setGlobalStiffness=function(a){for(var b=this.constraints,c=0;c!==b.length;c++)for(var d=b[c],e=0;e!==d.equations.length;e++){var f=d.equations[e];f.stiffness=a,f.needsUpdate=!0}for(var g=this.contactMaterials,c=0;c!==g.length;c++){var d=g[c];d.stiffness=d.frictionStiffness=a}var d=this.defaultContactMaterial;d.stiffness=d.frictionStiffness=a},c.prototype.setGlobalRelaxation=function(a){for(var b=0;b!==this.constraints.length;b++)for(var c=this.constraints[b],d=0;d!==c.equations.length;d++){var e=c.equations[d];e.relaxation=a,e.needsUpdate=!0}for(var b=0;b!==this.contactMaterials.length;b++){var c=this.contactMaterials[b];c.relaxation=c.frictionRelaxation=a}var c=this.defaultContactMaterial;c.relaxation=c.frictionRelaxation=a};var A=new o,B=[];c.prototype.raycast=function(a,b){return b.getAABB(A),this.broadphase.aabbQuery(this,A,B),b.intersectBodies(a,B),B.length=0,a.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":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])(36)}),function(){var a=this,b=b||{};return b.WEBGL_RENDERER=0,b.CANVAS_RENDERER=1,b.VERSION="v2.2.8",b._UID=0,"undefined"!=typeof Float32Array?(b.Float32Array=Float32Array,b.Uint16Array=Uint16Array,b.Uint32Array=Uint32Array,b.ArrayBuffer=ArrayBuffer):(b.Float32Array=Array,b.Uint16Array=Array),b.PI_2=2*Math.PI,b.RAD_TO_DEG=180/Math.PI,b.DEG_TO_RAD=Math.PI/180,b.RETINA_PREFIX="@2x",b.defaultRenderOptions={view:null,transparent:!1,antialias:!1,preserveDrawingBuffer:!1,resolution:1,clearBeforeRender:!0,autoResize:!1},b.DisplayObject=function(){this.position=new b.Point(0,0),this.scale=new b.Point(1,1),this.transformCallback=null,this.transformCallbackContext=null,this.pivot=new b.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.renderable=!1,this.parent=null,this.stage=null,this.worldAlpha=1,this.worldTransform=new b.Matrix,this.worldPosition=new b.Point(0,0),this.worldScale=new b.Point(1,1),this.worldRotation=0,this._sr=0,this._cr=1,this.filterArea=null,this._bounds=new b.Rectangle(0,0,1,1),this._currentBounds=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheIsDirty=!1},b.DisplayObject.prototype.constructor=b.DisplayObject,b.DisplayObject.prototype.destroy=function(){if(this.children){for(var a=this.children.length;a--;)this.children[a].destroy();this.children=[]}this.transformCallback=null,this.transformCallbackContext=null,this.hitArea=null,this.parent=null,this.stage=null,this.worldTransform=null,this.filterArea=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.renderable=!1,this._destroyCachedSprite()},Object.defineProperty(b.DisplayObject.prototype,"worldVisible",{get:function(){var a=this;do{if(!a.visible)return!1;a=a.parent}while(a);return!0}}),Object.defineProperty(b.DisplayObject.prototype,"mask",{get:function(){return this._mask},set:function(a){this._mask&&(this._mask.isMask=!1),this._mask=a,this._mask&&(this._mask.isMask=!0)}}),Object.defineProperty(b.DisplayObject.prototype,"filters",{get:function(){return this._filters},set:function(a){if(a){for(var b=[],c=0;c<a.length;c++)for(var d=a[c].passes,e=0;e<d.length;e++)b.push(d[e]);this._filterBlock={target:this,filterPasses:b}}this._filters=a}}),Object.defineProperty(b.DisplayObject.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(a){this._cacheAsBitmap!==a&&(a?this._generateCachedSprite():this._destroyCachedSprite(),this._cacheAsBitmap=a)}}),b.DisplayObject.prototype.updateTransform=function(a){if(a||this.parent||this.game){var c=this.parent;a?c=a:this.parent||(c=this.game.world);var d,e,f,g,h,i,j=c.worldTransform,k=this.worldTransform;this.rotation%b.PI_2?(this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation)),d=this._cr*this.scale.x,e=this._sr*this.scale.x,f=-this._sr*this.scale.y,g=this._cr*this.scale.y,h=this.position.x,i=this.position.y,(this.pivot.x||this.pivot.y)&&(h-=this.pivot.x*d+this.pivot.y*f,i-=this.pivot.x*e+this.pivot.y*g),k.a=d*j.a+e*j.c,k.b=d*j.b+e*j.d,k.c=f*j.a+g*j.c,k.d=f*j.b+g*j.d,k.tx=h*j.a+i*j.c+j.tx,k.ty=h*j.b+i*j.d+j.ty):(d=this.scale.x,g=this.scale.y,h=this.position.x-this.pivot.x*d,i=this.position.y-this.pivot.y*g,k.a=d*j.a,k.b=d*j.b,k.c=g*j.c,k.d=g*j.d,k.tx=h*j.a+i*j.c+j.tx,k.ty=h*j.b+i*j.d+j.ty),this.worldAlpha=this.alpha*c.worldAlpha,this.worldPosition.set(k.tx,k.ty),this.worldScale.set(Math.sqrt(k.a*k.a+k.b*k.b),Math.sqrt(k.c*k.c+k.d*k.d)),this.worldRotation=Math.atan2(-k.c,k.d),this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,k,j)}},b.DisplayObject.prototype.displayObjectUpdateTransform=b.DisplayObject.prototype.updateTransform,b.DisplayObject.prototype.getBounds=function(a){return a=a,b.EmptyRectangle},b.DisplayObject.prototype.getLocalBounds=function(){return this.getBounds(b.identityMatrix)},b.DisplayObject.prototype.setStageReference=function(a){this.stage=a},b.DisplayObject.prototype.preUpdate=function(){},b.DisplayObject.prototype.generateTexture=function(a,c,d){var e=this.getLocalBounds(),f=new b.RenderTexture(0|e.width,0|e.height,d,c,a);return b.DisplayObject._tempMatrix.tx=-e.x,b.DisplayObject._tempMatrix.ty=-e.y,f.render(this,b.DisplayObject._tempMatrix),f},b.DisplayObject.prototype.updateCache=function(){this._generateCachedSprite()},b.DisplayObject.prototype.toGlobal=function(a){return this.displayObjectUpdateTransform(),this.worldTransform.apply(a)},b.DisplayObject.prototype.toLocal=function(a,b){return b&&(a=b.toGlobal(a)),this.displayObjectUpdateTransform(),this.worldTransform.applyInverse(a)},b.DisplayObject.prototype._renderCachedSprite=function(a){this._cachedSprite.worldAlpha=this.worldAlpha,a.gl?b.Sprite.prototype._renderWebGL.call(this._cachedSprite,a):b.Sprite.prototype._renderCanvas.call(this._cachedSprite,a)},b.DisplayObject.prototype._generateCachedSprite=function(){this._cacheAsBitmap=!1;var a=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.texture.resize(0|a.width,0|a.height);else{var c=new b.RenderTexture(0|a.width,0|a.height);this._cachedSprite=new b.Sprite(c),this._cachedSprite.worldTransform=this.worldTransform}var d=this._filters;this._filters=null,this._cachedSprite.filters=d,b.DisplayObject._tempMatrix.tx=-a.x,b.DisplayObject._tempMatrix.ty=-a.y,this._cachedSprite.texture.render(this,b.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-(a.x/a.width),this._cachedSprite.anchor.y=-(a.y/a.height),this._filters=d,this._cacheAsBitmap=!0},b.DisplayObject.prototype._destroyCachedSprite=function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)},b.DisplayObject.prototype._renderWebGL=function(a){a=a},b.DisplayObject.prototype._renderCanvas=function(a){a=a},Object.defineProperty(b.DisplayObject.prototype,"x",{get:function(){return this.position.x},set:function(a){this.position.x=a}}),Object.defineProperty(b.DisplayObject.prototype,"y",{get:function(){return this.position.y},set:function(a){this.position.y=a}}),b.DisplayObjectContainer=function(){b.DisplayObject.call(this),this.children=[]},b.DisplayObjectContainer.prototype=Object.create(b.DisplayObject.prototype),b.DisplayObjectContainer.prototype.constructor=b.DisplayObjectContainer,Object.defineProperty(b.DisplayObjectContainer.prototype,"width",{get:function(){return this.scale.x*this.getLocalBounds().width},set:function(a){var b=this.getLocalBounds().width;this.scale.x=0!==b?a/b:1,this._width=a}}),Object.defineProperty(b.DisplayObjectContainer.prototype,"height",{get:function(){return this.scale.y*this.getLocalBounds().height},set:function(a){var b=this.getLocalBounds().height;this.scale.y=0!==b?a/b:1,this._height=a}}),b.DisplayObjectContainer.prototype.addChild=function(a){return this.addChildAt(a,this.children.length)},b.DisplayObjectContainer.prototype.addChildAt=function(a,b){if(b>=0&&b<=this.children.length)return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),this.stage&&a.setStageReference(this.stage),a;throw new Error(a+"addChildAt: The index "+b+" supplied is out of bounds "+this.children.length)},b.DisplayObjectContainer.prototype.swapChildren=function(a,b){if(a!==b){var c=this.getChildIndex(a),d=this.getChildIndex(b);if(0>c||0>d)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[c]=b,this.children[d]=a}},b.DisplayObjectContainer.prototype.getChildIndex=function(a){var b=this.children.indexOf(a);if(-1===b)throw new Error("The supplied DisplayObject must be a child of the caller");return b},b.DisplayObjectContainer.prototype.setChildIndex=function(a,b){if(0>b||b>=this.children.length)throw new Error("The supplied index is out of bounds");var c=this.getChildIndex(a);this.children.splice(c,1),this.children.splice(b,0,a)},b.DisplayObjectContainer.prototype.getChildAt=function(a){if(0>a||a>=this.children.length)throw new Error("getChildAt: Supplied index "+a+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[a]},b.DisplayObjectContainer.prototype.removeChild=function(a){var b=this.children.indexOf(a);
+if(-1!==b)return this.removeChildAt(b)},b.DisplayObjectContainer.prototype.removeChildAt=function(a){var b=this.getChildAt(a);return this.stage&&b.removeStageReference(),b.parent=void 0,this.children.splice(a,1),b},b.DisplayObjectContainer.prototype.removeChildren=function(a,b){var c=a||0,d="number"==typeof b?b:this.children.length,e=d-c;if(e>0&&d>=e){for(var f=this.children.splice(c,e),g=0;g<f.length;g++){var h=f[g];this.stage&&h.removeStageReference(),h.parent=void 0}return f}if(0===e&&0===this.children.length)return[];throw new Error("removeChildren: Range Error, numeric values are outside the acceptable range")},b.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible&&(this.displayObjectUpdateTransform(),!this._cacheAsBitmap))for(var a=0;a<this.children.length;a++)this.children[a].updateTransform()},b.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform=b.DisplayObjectContainer.prototype.updateTransform,b.DisplayObjectContainer.prototype.getBounds=function(){if(0===this.children.length)return b.EmptyRectangle;for(var a,c,d,e=1/0,f=1/0,g=-1/0,h=-1/0,i=!1,j=0,k=this.children.length;k>j;j++){var l=this.children[j];l.visible&&(i=!0,a=this.children[j].getBounds(),e=e<a.x?e:a.x,f=f<a.y?f:a.y,c=a.width+a.x,d=a.height+a.y,g=g>c?g:c,h=h>d?h:d)}if(!i)return b.EmptyRectangle;var m=this._bounds;return m.x=e,m.y=f,m.width=g-e,m.height=h-f,m},b.DisplayObjectContainer.prototype.getLocalBounds=function(){var a=this.worldTransform;this.worldTransform=b.identityMatrix;for(var c=0,d=this.children.length;d>c;c++)this.children[c].updateTransform();var e=this.getBounds();return this.worldTransform=a,e},b.DisplayObjectContainer.prototype.setStageReference=function(a){this.stage=a;for(var b=0;b<this.children.length;b++)this.children[b].setStageReference(a)},b.DisplayObjectContainer.prototype.removeStageReference=function(){for(var a=0;a<this.children.length;a++)this.children[a].removeStageReference();this.stage=null},b.DisplayObjectContainer.prototype._renderWebGL=function(a){if(this.visible&&!(this.alpha<=0)){if(this._cacheAsBitmap)return void this._renderCachedSprite(a);var b;if(this._mask||this._filters){for(this._filters&&(a.spriteBatch.flush(),a.filterManager.pushFilter(this._filterBlock)),this._mask&&(a.spriteBatch.stop(),a.maskManager.pushMask(this.mask,a),a.spriteBatch.start()),b=0;b<this.children.length;b++)this.children[b]._renderWebGL(a);a.spriteBatch.stop(),this._mask&&a.maskManager.popMask(this._mask,a),this._filters&&a.filterManager.popFilter(),a.spriteBatch.start()}else for(b=0;b<this.children.length;b++)this.children[b]._renderWebGL(a)}},b.DisplayObjectContainer.prototype._renderCanvas=function(a){if(this.visible!==!1&&0!==this.alpha){if(this._cacheAsBitmap)return void this._renderCachedSprite(a);this._mask&&a.maskManager.pushMask(this._mask,a);for(var b=0;b<this.children.length;b++)this.children[b]._renderCanvas(a);this._mask&&a.maskManager.popMask(a)}},b.Sprite=function(a){b.DisplayObjectContainer.call(this),this.anchor=new b.Point,this.texture=a||b.Texture.emptyTexture,this._width=0,this._height=0,this.tint=16777215,this.cachedTint=-1,this.tintedTexture=null,this.blendMode=b.blendModes.NORMAL,this.shader=null,this.texture.baseTexture.hasLoaded&&this.onTextureUpdate(),this.renderable=!0},b.Sprite.prototype=Object.create(b.DisplayObjectContainer.prototype),b.Sprite.prototype.constructor=b.Sprite,Object.defineProperty(b.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(a){this.scale.x=a/this.texture.frame.width,this._width=a}}),Object.defineProperty(b.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(a){this.scale.y=a/this.texture.frame.height,this._height=a}}),b.Sprite.prototype.setTexture=function(a){this.texture=a,this.texture.valid=!0},b.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height)},b.Sprite.prototype.getBounds=function(a){var b=this.texture.frame.width,c=this.texture.frame.height,d=b*(1-this.anchor.x),e=b*-this.anchor.x,f=c*(1-this.anchor.y),g=c*-this.anchor.y,h=a||this.worldTransform,i=h.a,j=h.b,k=h.c,l=h.d,m=h.tx,n=h.ty,o=-1/0,p=-1/0,q=1/0,r=1/0;if(0===j&&0===k)0>i&&(i*=-1),0>l&&(l*=-1),q=i*e+m,o=i*d+m,r=l*g+n,p=l*f+n;else{var s=i*e+k*g+m,t=l*g+j*e+n,u=i*d+k*g+m,v=l*g+j*d+n,w=i*d+k*f+m,x=l*f+j*d+n,y=i*e+k*f+m,z=l*f+j*e+n;q=q>s?s:q,q=q>u?u:q,q=q>w?w:q,q=q>y?y:q,r=r>t?t:r,r=r>v?v:r,r=r>x?x:r,r=r>z?z:r,o=s>o?s:o,o=u>o?u:o,o=w>o?w:o,o=y>o?y:o,p=t>p?t:p,p=v>p?v:p,p=x>p?x:p,p=z>p?z:p}var A=this._bounds;return A.x=q,A.width=o-q,A.y=r,A.height=p-r,this._currentBounds=A,A},b.Sprite.prototype._renderWebGL=function(a,b){if(this.visible&&!(this.alpha<=0)&&this.renderable){var c=this.worldTransform;if(b&&(c=b),this._mask||this._filters){var d=a.spriteBatch;this._filters&&(d.flush(),a.filterManager.pushFilter(this._filterBlock)),this._mask&&(d.stop(),a.maskManager.pushMask(this.mask,a),d.start()),d.render(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(a);d.stop(),this._mask&&a.maskManager.popMask(this._mask,a),this._filters&&a.filterManager.popFilter(),d.start()}else{a.spriteBatch.render(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(a,c)}}},b.Sprite.prototype._renderCanvas=function(a,c){if(!(this.visible===!1||0===this.alpha||this.renderable===!1||this.texture.crop.width<=0||this.texture.crop.height<=0)){var d=this.worldTransform;if(c&&(d=c),this.blendMode!==a.currentBlendMode&&(a.currentBlendMode=this.blendMode,a.context.globalCompositeOperation=b.blendModesCanvas[a.currentBlendMode]),this._mask&&a.maskManager.pushMask(this._mask,a),this.texture.valid){var e=this.texture.baseTexture.resolution/a.resolution;a.context.globalAlpha=this.worldAlpha,a.smoothProperty&&a.scaleMode!==this.texture.baseTexture.scaleMode&&(a.scaleMode=this.texture.baseTexture.scaleMode,a.context[a.smoothProperty]=a.scaleMode===b.scaleModes.LINEAR);var f=this.texture.trim?this.texture.trim.x-this.anchor.x*this.texture.trim.width:this.anchor.x*-this.texture.frame.width,g=this.texture.trim?this.texture.trim.y-this.anchor.y*this.texture.trim.height:this.anchor.y*-this.texture.frame.height;a.roundPixels?(a.context.setTransform(d.a,d.b,d.c,d.d,d.tx*a.resolution|0,d.ty*a.resolution|0),f=0|f,g=0|g):a.context.setTransform(d.a,d.b,d.c,d.d,d.tx*a.resolution,d.ty*a.resolution);var h=this.texture.crop.width,i=this.texture.crop.height;if(f/=e,g/=e,16777215!==this.tint)(this.texture.requiresReTint||this.cachedTint!==this.tint)&&(this.tintedTexture=b.CanvasTinter.getTintedTexture(this,this.tint),this.cachedTint=this.tint),a.context.drawImage(this.tintedTexture,0,0,h,i,f,g,h/e,i/e);else{var j=this.texture.crop.x,k=this.texture.crop.y;a.context.drawImage(this.texture.baseTexture.source,j,k,h,i,f,g,h/e,i/e)}}for(var l=0;l<this.children.length;l++)this.children[l]._renderCanvas(a);this._mask&&a.maskManager.popMask(a)}},b.Sprite.fromFrame=function(a){var c=b.TextureCache[a];if(!c)throw new Error('The frameId "'+a+'" does not exist in the texture cache'+this);return new b.Sprite(c)},b.Sprite.fromImage=function(a,c,d){var e=b.Texture.fromImage(a,c,d);return new b.Sprite(e)},b.SpriteBatch=function(a){b.DisplayObjectContainer.call(this),this.textureThing=a,this.ready=!1},b.SpriteBatch.prototype=Object.create(b.DisplayObjectContainer.prototype),b.SpriteBatch.prototype.constructor=b.SpriteBatch,b.SpriteBatch.prototype.initWebGL=function(a){this.fastSpriteBatch=new b.WebGLFastSpriteBatch(a),this.ready=!0},b.SpriteBatch.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},b.SpriteBatch.prototype._renderWebGL=function(a){!this.visible||this.alpha<=0||!this.children.length||(this.ready||this.initWebGL(a.gl),this.fastSpriteBatch.gl!==a.gl&&this.fastSpriteBatch.setContext(a.gl),a.spriteBatch.stop(),a.shaderManager.setShader(a.shaderManager.fastShader),this.fastSpriteBatch.begin(this,a),this.fastSpriteBatch.render(this),a.spriteBatch.start())},b.SpriteBatch.prototype._renderCanvas=function(a){if(this.visible&&!(this.alpha<=0)&&this.children.length){var b=a.context;b.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var c=this.worldTransform,d=!0,e=0;e<this.children.length;e++){var f=this.children[e];if(f.visible){var g=f.texture,h=g.frame;if(b.globalAlpha=this.worldAlpha*f.alpha,f.rotation%(2*Math.PI)===0)d&&(b.setTransform(c.a,c.b,c.c,c.d,c.tx,c.ty),d=!1),b.drawImage(g.baseTexture.source,h.x,h.y,h.width,h.height,f.anchor.x*-h.width*f.scale.x+f.position.x+.5|0,f.anchor.y*-h.height*f.scale.y+f.position.y+.5|0,h.width*f.scale.x,h.height*f.scale.y);else{d||(d=!0),f.displayObjectUpdateTransform();var i=f.worldTransform;a.roundPixels?b.setTransform(i.a,i.b,i.c,i.d,0|i.tx,0|i.ty):b.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty),b.drawImage(g.baseTexture.source,h.x,h.y,h.width,h.height,f.anchor.x*-h.width+.5|0,f.anchor.y*-h.height+.5|0,h.width,h.height)}}}}},b.Stage=function(a){b.DisplayObjectContainer.call(this),this.worldTransform=new b.Matrix,this.stage=this,this.setBackgroundColor(a)},b.Stage.prototype=Object.create(b.DisplayObjectContainer.prototype),b.Stage.prototype.constructor=b.Stage,b.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var a=0;a<this.children.length;a++)this.children[a].updateTransform()},b.Stage.prototype.setBackgroundColor=function(a){this.backgroundColor=a||0,this.backgroundColorSplit=b.hex2rgb(this.backgroundColor);var c=this.backgroundColor.toString(16);c="000000".substr(0,6-c.length)+c,this.backgroundColorString="#"+c},b.hex2rgb=function(a){return[(a>>16&255)/255,(a>>8&255)/255,(255&a)/255]},b.rgb2hex=function(a){return(255*a[0]<<16)+(255*a[1]<<8)+255*a[2]},b.canUseNewCanvasBlendModes=function(){if(void 0===document)return!1;var a="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",b="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",c=new Image;c.src=a+"AP804Oa6"+b;var d=new Image;d.src=a+"/wCKxvRF"+b;var e=document.createElement("canvas");e.width=6,e.height=1;var f=e.getContext("2d");if(f.globalCompositeOperation="multiply",f.drawImage(c,0,0),f.drawImage(d,2,0),!f.getImageData(2,0,1,1))return!1;var g=f.getImageData(2,0,1,1).data;return 255===g[0]&&0===g[1]&&0===g[2]},b.getNextPowerOfTwo=function(a){if(a>0&&0===(a&a-1))return a;for(var b=1;a>b;)b<<=1;return b},b.isPowerOfTwo=function(a,b){return a>0&&0===(a&a-1)&&b>0&&0===(b&b-1)},b.PolyK={},b.PolyK.Triangulate=function(a){var c=!0,d=a.length>>1;if(3>d)return[];for(var e=[],f=[],g=0;d>g;g++)f.push(g);g=0;for(var h=d;h>3;){var i=f[(g+0)%h],j=f[(g+1)%h],k=f[(g+2)%h],l=a[2*i],m=a[2*i+1],n=a[2*j],o=a[2*j+1],p=a[2*k],q=a[2*k+1],r=!1;if(b.PolyK._convex(l,m,n,o,p,q,c)){r=!0;for(var s=0;h>s;s++){var t=f[s];if(t!==i&&t!==j&&t!==k&&b.PolyK._PointInTriangle(a[2*t],a[2*t+1],l,m,n,o,p,q)){r=!1;break}}}if(r)e.push(i,j,k),f.splice((g+1)%h,1),h--,g=0;else if(g++>3*h){if(!c)return null;for(e=[],f=[],g=0;d>g;g++)f.push(g);g=0,h=d,c=!1}}return e.push(f[0],f[1],f[2]),e},b.PolyK._PointInTriangle=function(a,b,c,d,e,f,g,h){var i=g-c,j=h-d,k=e-c,l=f-d,m=a-c,n=b-d,o=i*i+j*j,p=i*k+j*l,q=i*m+j*n,r=k*k+l*l,s=k*m+l*n,t=1/(o*r-p*p),u=(r*q-p*s)*t,v=(o*s-p*q)*t;return u>=0&&v>=0&&1>u+v},b.PolyK._convex=function(a,b,c,d,e,f,g){return(b-d)*(e-c)+(c-a)*(f-d)>=0===g},b.initDefaultShaders=function(){},b.CompileVertexShader=function(a,c){return b._CompileShader(a,c,a.VERTEX_SHADER)},b.CompileFragmentShader=function(a,c){return b._CompileShader(a,c,a.FRAGMENT_SHADER)},b._CompileShader=function(a,b,c){var d=b;Array.isArray(b)&&(d=b.join("\n"));var e=a.createShader(c);return a.shaderSource(e,d),a.compileShader(e),a.getShaderParameter(e,a.COMPILE_STATUS)?e:(window.console.log(a.getShaderInfoLog(e)),null)},b.compileProgram=function(a,c,d){var e=b.CompileFragmentShader(a,d),f=b.CompileVertexShader(a,c),g=a.createProgram();return a.attachShader(g,f),a.attachShader(g,e),a.linkProgram(g),a.getProgramParameter(g,a.LINK_STATUS)||window.console.log("Could not initialise shaders"),g},b.PixiShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.textureCount=0,this.firstRun=!0,this.dirty=!0,this.attributes=[],this.init()},b.PixiShader.prototype.constructor=b.PixiShader,b.PixiShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc||b.PixiShader.defaultVertexSrc,this.fragmentSrc);a.useProgram(c),this.uSampler=a.getUniformLocation(c,"uSampler"),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.dimensions=a.getUniformLocation(c,"dimensions"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.aTextureCoord=a.getAttribLocation(c,"aTextureCoord"),this.colorAttribute=a.getAttribLocation(c,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var d in this.uniforms)this.uniforms[d].uniformLocation=a.getUniformLocation(c,d);this.initUniforms(),this.program=c},b.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var a,b=this.gl;for(var c in this.uniforms){a=this.uniforms[c];var d=a.type;"sampler2D"===d?(a._init=!1,null!==a.value&&this.initSampler2D(a)):"mat2"===d||"mat3"===d||"mat4"===d?(a.glMatrix=!0,a.glValueLength=1,"mat2"===d?a.glFunc=b.uniformMatrix2fv:"mat3"===d?a.glFunc=b.uniformMatrix3fv:"mat4"===d&&(a.glFunc=b.uniformMatrix4fv)):(a.glFunc=b["uniform"+d],a.glValueLength="2f"===d||"2i"===d?2:"3f"===d||"3i"===d?3:"4f"===d||"4i"===d?4:1)}},b.PixiShader.prototype.initSampler2D=function(a){if(a.value&&a.value.baseTexture&&a.value.baseTexture.hasLoaded){var b=this.gl;if(b.activeTexture(b["TEXTURE"+this.textureCount]),b.bindTexture(b.TEXTURE_2D,a.value.baseTexture._glTextures[b.id]),a.textureData){var c=a.textureData,d=c.magFilter?c.magFilter:b.LINEAR,e=c.minFilter?c.minFilter:b.LINEAR,f=c.wrapS?c.wrapS:b.CLAMP_TO_EDGE,g=c.wrapT?c.wrapT:b.CLAMP_TO_EDGE,h=c.luminance?b.LUMINANCE:b.RGBA;if(c.repeat&&(f=b.REPEAT,g=b.REPEAT),b.pixelStorei(b.UNPACK_FLIP_Y_WEBGL,!!c.flipY),c.width){var i=c.width?c.width:512,j=c.height?c.height:2,k=c.border?c.border:0;b.texImage2D(b.TEXTURE_2D,0,h,i,j,k,h,b.UNSIGNED_BYTE,null)}else b.texImage2D(b.TEXTURE_2D,0,h,b.RGBA,b.UNSIGNED_BYTE,a.value.baseTexture.source);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,d),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,e),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,f),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,g)}b.uniform1i(a.uniformLocation,this.textureCount),a._init=!0,this.textureCount++}},b.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var a,c=this.gl;for(var d in this.uniforms)a=this.uniforms[d],1===a.glValueLength?a.glMatrix===!0?a.glFunc.call(c,a.uniformLocation,a.transpose,a.value):a.glFunc.call(c,a.uniformLocation,a.value):2===a.glValueLength?a.glFunc.call(c,a.uniformLocation,a.value.x,a.value.y):3===a.glValueLength?a.glFunc.call(c,a.uniformLocation,a.value.x,a.value.y,a.value.z):4===a.glValueLength?a.glFunc.call(c,a.uniformLocation,a.value.x,a.value.y,a.value.z,a.value.w):"sampler2D"===a.type&&(a._init?(c.activeTexture(c["TEXTURE"+this.textureCount]),a.value.baseTexture._dirty[c.id]?b.instances[c.id].updateTexture(a.value.baseTexture):c.bindTexture(c.TEXTURE_2D,a.value.baseTexture._glTextures[c.id]),c.uniform1i(a.uniformLocation,this.textureCount),this.textureCount++):this.initSampler2D(a))},b.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},b.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec4 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {","   gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);","   vTextureCoord = aTextureCoord;","   vColor = vec4(aColor.rgb * aColor.a, aColor.a);","}"],b.PixiFastShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {","   vec2 v;","   vec2 sv = aVertexPosition * aScale;","   v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);","   v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);","   v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;","   gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);","   vTextureCoord = aTextureCoord;","   vColor = aColor;","}"],this.textureCount=0,this.init()},b.PixiFastShader.prototype.constructor=b.PixiFastShader,b.PixiFastShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.uSampler=a.getUniformLocation(c,"uSampler"),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.dimensions=a.getUniformLocation(c,"dimensions"),this.uMatrix=a.getUniformLocation(c,"uMatrix"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.aPositionCoord=a.getAttribLocation(c,"aPositionCoord"),this.aScale=a.getAttribLocation(c,"aScale"),this.aRotation=a.getAttribLocation(c,"aRotation"),this.aTextureCoord=a.getAttribLocation(c,"aTextureCoord"),this.colorAttribute=a.getAttribLocation(c,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute],this.program=c},b.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},b.StripShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","void main(void) {","   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);","   v -= offsetVector.xyx;","   gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);","   vTextureCoord = aTextureCoord;","}"],this.init()},b.StripShader.prototype.constructor=b.StripShader,b.StripShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.uSampler=a.getUniformLocation(c,"uSampler"),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.colorAttribute=a.getAttribLocation(c,"aColor"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.aTextureCoord=a.getAttribLocation(c,"aTextureCoord"),this.attributes=[this.aVertexPosition,this.aTextureCoord],this.translationMatrix=a.getUniformLocation(c,"translationMatrix"),this.alpha=a.getUniformLocation(c,"alpha"),this.program=c},b.StripShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},b.PrimitiveShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {","   gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform float flipY;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {","   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);","   v -= offsetVector.xyx;","   gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);","   vColor = aColor * vec4(tint * alpha, alpha);","}"],this.init()},b.PrimitiveShader.prototype.constructor=b.PrimitiveShader,b.PrimitiveShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.tintColor=a.getUniformLocation(c,"tint"),this.flipY=a.getUniformLocation(c,"flipY"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.colorAttribute=a.getAttribLocation(c,"aColor"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=a.getUniformLocation(c,"translationMatrix"),this.alpha=a.getUniformLocation(c,"alpha"),this.program=c},b.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},b.ComplexPrimitiveShader=function(a){this._UID=b._UID++,this.gl=a,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {","   gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform vec3 tint;","uniform float alpha;","uniform vec3 color;","uniform float flipY;","varying vec4 vColor;","void main(void) {","   vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);","   v -= offsetVector.xyx;","   gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);","   vColor = vec4(color * alpha * tint, alpha);","}"],this.init()},b.ComplexPrimitiveShader.prototype.constructor=b.ComplexPrimitiveShader,b.ComplexPrimitiveShader.prototype.init=function(){var a=this.gl,c=b.compileProgram(a,this.vertexSrc,this.fragmentSrc);a.useProgram(c),this.projectionVector=a.getUniformLocation(c,"projectionVector"),this.offsetVector=a.getUniformLocation(c,"offsetVector"),this.tintColor=a.getUniformLocation(c,"tint"),this.color=a.getUniformLocation(c,"color"),this.flipY=a.getUniformLocation(c,"flipY"),this.aVertexPosition=a.getAttribLocation(c,"aVertexPosition"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=a.getUniformLocation(c,"translationMatrix"),this.alpha=a.getUniformLocation(c,"alpha"),this.program=c},b.ComplexPrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},b.WebGLGraphics=function(){},b.WebGLGraphics.renderGraphics=function(a,c){var d,e=c.gl,f=c.projection,g=c.offset,h=c.shaderManager.primitiveShader;a.dirty&&b.WebGLGraphics.updateGraphics(a,e);for(var i=a._webGL[e.id],j=0;j<i.data.length;j++)1===i.data[j].mode?(d=i.data[j],c.stencilManager.pushStencil(a,d,c),e.drawElements(e.TRIANGLE_FAN,4,e.UNSIGNED_SHORT,2*(d.indices.length-4)),c.stencilManager.popStencil(a,d,c)):(d=i.data[j],c.shaderManager.setShader(h),h=c.shaderManager.primitiveShader,e.uniformMatrix3fv(h.translationMatrix,!1,a.worldTransform.toArray(!0)),e.uniform1f(h.flipY,1),e.uniform2f(h.projectionVector,f.x,-f.y),e.uniform2f(h.offsetVector,-g.x,-g.y),e.uniform3fv(h.tintColor,b.hex2rgb(a.tint)),e.uniform1f(h.alpha,a.worldAlpha),e.bindBuffer(e.ARRAY_BUFFER,d.buffer),e.vertexAttribPointer(h.aVertexPosition,2,e.FLOAT,!1,24,0),e.vertexAttribPointer(h.colorAttribute,4,e.FLOAT,!1,24,8),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,d.indexBuffer),e.drawElements(e.TRIANGLE_STRIP,d.indices.length,e.UNSIGNED_SHORT,0))},b.WebGLGraphics.updateGraphics=function(a,c){var d=a._webGL[c.id];d||(d=a._webGL[c.id]={lastIndex:0,data:[],gl:c}),a.dirty=!1;var e;if(a.clearDirty){for(a.clearDirty=!1,e=0;e<d.data.length;e++){var f=d.data[e];f.reset(),b.WebGLGraphics.graphicsDataPool.push(f)}d.data=[],d.lastIndex=0}var g;for(e=d.lastIndex;e<a.graphicsData.length;e++){var h=a.graphicsData[e];if(h.type===b.Graphics.POLY){if(h.points=h.shape.points.slice(),h.shape.closed&&(h.points[0]!==h.points[h.points.length-2]||h.points[1]!==h.points[h.points.length-1])&&h.points.push(h.points[0],h.points[1]),h.fill&&h.points.length>=6)if(h.points.length<12){g=b.WebGLGraphics.switchMode(d,0);var i=b.WebGLGraphics.buildPoly(h,g);i||(g=b.WebGLGraphics.switchMode(d,1),b.WebGLGraphics.buildComplexPoly(h,g))}else g=b.WebGLGraphics.switchMode(d,1),b.WebGLGraphics.buildComplexPoly(h,g);h.lineWidth>0&&(g=b.WebGLGraphics.switchMode(d,0),b.WebGLGraphics.buildLine(h,g))}else g=b.WebGLGraphics.switchMode(d,0),h.type===b.Graphics.RECT?b.WebGLGraphics.buildRectangle(h,g):h.type===b.Graphics.CIRC||h.type===b.Graphics.ELIP?b.WebGLGraphics.buildCircle(h,g):h.type===b.Graphics.RREC&&b.WebGLGraphics.buildRoundedRectangle(h,g);d.lastIndex++}for(e=0;e<d.data.length;e++)g=d.data[e],g.dirty&&g.upload()},b.WebGLGraphics.switchMode=function(a,c){var d;return a.data.length?(d=a.data[a.data.length-1],(d.mode!==c||1===c)&&(d=b.WebGLGraphics.graphicsDataPool.pop()||new b.WebGLGraphicsData(a.gl),d.mode=c,a.data.push(d))):(d=b.WebGLGraphics.graphicsDataPool.pop()||new b.WebGLGraphicsData(a.gl),d.mode=c,a.data.push(d)),d.dirty=!0,d},b.WebGLGraphics.buildRectangle=function(a,c){var d=a.shape,e=d.x,f=d.y,g=d.width,h=d.height;if(a.fill){var i=b.hex2rgb(a.fillColor),j=a.fillAlpha,k=i[0]*j,l=i[1]*j,m=i[2]*j,n=c.points,o=c.indices,p=n.length/6;n.push(e,f),n.push(k,l,m,j),n.push(e+g,f),n.push(k,l,m,j),n.push(e,f+h),n.push(k,l,m,j),n.push(e+g,f+h),n.push(k,l,m,j),o.push(p,p,p+1,p+2,p+3,p+3)}if(a.lineWidth){var q=a.points;a.points=[e,f,e+g,f,e+g,f+h,e,f+h,e,f],b.WebGLGraphics.buildLine(a,c),a.points=q}},b.WebGLGraphics.buildRoundedRectangle=function(a,c){var d=a.shape,e=d.x,f=d.y,g=d.width,h=d.height,i=d.radius,j=[];if(j.push(e,f+i),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e,f+h-i,e,f+h,e+i,f+h)),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e+g-i,f+h,e+g,f+h,e+g,f+h-i)),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e+g,f+i,e+g,f,e+g-i,f)),j=j.concat(b.WebGLGraphics.quadraticBezierCurve(e+i,f,e,f,e,f+i)),a.fill){var k=b.hex2rgb(a.fillColor),l=a.fillAlpha,m=k[0]*l,n=k[1]*l,o=k[2]*l,p=c.points,q=c.indices,r=p.length/6,s=b.PolyK.Triangulate(j),t=0;for(t=0;t<s.length;t+=3)q.push(s[t]+r),q.push(s[t]+r),q.push(s[t+1]+r),q.push(s[t+2]+r),q.push(s[t+2]+r);for(t=0;t<j.length;t++)p.push(j[t],j[++t],m,n,o,l)}if(a.lineWidth){var u=a.points;a.points=j,b.WebGLGraphics.buildLine(a,c),a.points=u}},b.WebGLGraphics.quadraticBezierCurve=function(a,b,c,d,e,f){function g(a,b,c){var d=b-a;return a+d*c}for(var h,i,j,k,l,m,n=20,o=[],p=0,q=0;n>=q;q++)p=q/n,h=g(a,c,p),i=g(b,d,p),j=g(c,e,p),k=g(d,f,p),l=g(h,j,p),m=g(i,k,p),o.push(l,m);return o},b.WebGLGraphics.buildCircle=function(a,c){var d,e,f=a.shape,g=f.x,h=f.y;a.type===b.Graphics.CIRC?(d=f.radius,e=f.radius):(d=f.width,e=f.height);var i=40,j=2*Math.PI/i,k=0;if(a.fill){var l=b.hex2rgb(a.fillColor),m=a.fillAlpha,n=l[0]*m,o=l[1]*m,p=l[2]*m,q=c.points,r=c.indices,s=q.length/6;for(r.push(s),k=0;i+1>k;k++)q.push(g,h,n,o,p,m),q.push(g+Math.sin(j*k)*d,h+Math.cos(j*k)*e,n,o,p,m),r.push(s++,s++);r.push(s-1)}if(a.lineWidth){var t=a.points;for(a.points=[],k=0;i+1>k;k++)a.points.push(g+Math.sin(j*k)*d,h+Math.cos(j*k)*e);b.WebGLGraphics.buildLine(a,c),a.points=t}},b.WebGLGraphics.buildLine=function(a,c){var d=0,e=a.points;if(0!==e.length){if(a.lineWidth%2)for(d=0;d<e.length;d++)e[d]+=.5;var f=new b.Point(e[0],e[1]),g=new b.Point(e[e.length-2],e[e.length-1]);if(f.x===g.x&&f.y===g.y){e=e.slice(),e.pop(),e.pop(),g=new b.Point(e[e.length-2],e[e.length-1]);var h=g.x+.5*(f.x-g.x),i=g.y+.5*(f.y-g.y);e.unshift(h,i),e.push(h,i)}var j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G=c.points,H=c.indices,I=e.length/2,J=e.length,K=G.length/6,L=a.lineWidth/2,M=b.hex2rgb(a.lineColor),N=a.lineAlpha,O=M[0]*N,P=M[1]*N,Q=M[2]*N;for(l=e[0],m=e[1],n=e[2],o=e[3],r=-(m-o),s=l-n,F=Math.sqrt(r*r+s*s),r/=F,s/=F,r*=L,s*=L,G.push(l-r,m-s,O,P,Q,N),G.push(l+r,m+s,O,P,Q,N),d=1;I-1>d;d++)l=e[2*(d-1)],m=e[2*(d-1)+1],n=e[2*d],o=e[2*d+1],p=e[2*(d+1)],q=e[2*(d+1)+1],r=-(m-o),s=l-n,F=Math.sqrt(r*r+s*s),r/=F,s/=F,r*=L,s*=L,t=-(o-q),u=n-p,F=Math.sqrt(t*t+u*u),t/=F,u/=F,t*=L,u*=L,x=-s+m-(-s+o),y=-r+n-(-r+l),z=(-r+l)*(-s+o)-(-r+n)*(-s+m),A=-u+q-(-u+o),B=-t+n-(-t+p),C=(-t+p)*(-u+o)-(-t+n)*(-u+q),D=x*B-A*y,Math.abs(D)<.1?(D+=10.1,G.push(n-r,o-s,O,P,Q,N),G.push(n+r,o+s,O,P,Q,N)):(j=(y*C-B*z)/D,k=(A*z-x*C)/D,E=(j-n)*(j-n)+(k-o)+(k-o),E>19600?(v=r-t,w=s-u,F=Math.sqrt(v*v+w*w),v/=F,w/=F,v*=L,w*=L,G.push(n-v,o-w),G.push(O,P,Q,N),G.push(n+v,o+w),G.push(O,P,Q,N),G.push(n-v,o-w),G.push(O,P,Q,N),J++):(G.push(j,k),G.push(O,P,Q,N),G.push(n-(j-n),o-(k-o)),G.push(O,P,Q,N)));for(l=e[2*(I-2)],m=e[2*(I-2)+1],n=e[2*(I-1)],o=e[2*(I-1)+1],r=-(m-o),s=l-n,F=Math.sqrt(r*r+s*s),r/=F,s/=F,r*=L,s*=L,G.push(n-r,o-s),G.push(O,P,Q,N),G.push(n+r,o+s),G.push(O,P,Q,N),H.push(K),d=0;J>d;d++)H.push(K++);H.push(K-1)}},b.WebGLGraphics.buildComplexPoly=function(a,c){var d=a.points.slice();if(!(d.length<6)){var e=c.indices;c.points=d,c.alpha=a.fillAlpha,c.color=b.hex2rgb(a.fillColor);for(var f,g,h=1/0,i=-1/0,j=1/0,k=-1/0,l=0;l<d.length;l+=2)f=d[l],g=d[l+1],h=h>f?f:h,i=f>i?f:i,j=j>g?g:j,k=g>k?g:k;d.push(h,j,i,j,i,k,h,k);var m=d.length/2;for(l=0;m>l;l++)e.push(l)}},b.WebGLGraphics.buildPoly=function(a,c){var d=a.points;if(!(d.length<6)){var e=c.points,f=c.indices,g=d.length/2,h=b.hex2rgb(a.fillColor),i=a.fillAlpha,j=h[0]*i,k=h[1]*i,l=h[2]*i,m=b.PolyK.Triangulate(d);if(!m)return!1;var n=e.length/6,o=0;for(o=0;o<m.length;o+=3)f.push(m[o]+n),f.push(m[o]+n),f.push(m[o+1]+n),f.push(m[o+2]+n),f.push(m[o+2]+n);for(o=0;g>o;o++)e.push(d[2*o],d[2*o+1],j,k,l,i);return!0}},b.WebGLGraphics.graphicsDataPool=[],b.WebGLGraphicsData=function(a){this.gl=a,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),this.mode=1,this.alpha=1,this.dirty=!0},b.WebGLGraphicsData.prototype.reset=function(){this.points=[],this.indices=[]},b.WebGLGraphicsData.prototype.upload=function(){var a=this.gl;this.glPoints=new b.Float32Array(this.points),a.bindBuffer(a.ARRAY_BUFFER,this.buffer),a.bufferData(a.ARRAY_BUFFER,this.glPoints,a.STATIC_DRAW),this.glIndicies=new b.Uint16Array(this.indices),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,this.glIndicies,a.STATIC_DRAW),this.dirty=!1},b.glContexts=[],b.instances=[],b.WebGLRenderer=function(a,c,d){if(d)for(var e in b.defaultRenderOptions)void 0===d[e]&&(d[e]=b.defaultRenderOptions[e]);else d=b.defaultRenderOptions;b.defaultRenderer||(b.defaultRenderer=this),this.type=b.WEBGL_RENDERER,this.resolution=d.resolution,this.transparent=d.transparent,this.autoResize=d.autoResize||!1,this.preserveDrawingBuffer=d.preserveDrawingBuffer,this.clearBeforeRender=d.clearBeforeRender,this.width=a||800,this.height=c||600,this.view=d.view||document.createElement("canvas"),this._contextOptions={alpha:this.transparent,antialias:d.antialias,premultipliedAlpha:this.transparent&&"notMultiplied"!==this.transparent,stencil:!0,preserveDrawingBuffer:d.preserveDrawingBuffer},this.projection=new b.Point,this.offset=new b.Point(0,0),this.shaderManager=new b.WebGLShaderManager,this.spriteBatch=new b.WebGLSpriteBatch,this.maskManager=new b.WebGLMaskManager,this.filterManager=new b.WebGLFilterManager,this.stencilManager=new b.WebGLStencilManager,this.blendModeManager=new b.WebGLBlendModeManager,this.renderSession={},this.renderSession.gl=this.gl,this.renderSession.drawCount=0,this.renderSession.shaderManager=this.shaderManager,this.renderSession.maskManager=this.maskManager,this.renderSession.filterManager=this.filterManager,this.renderSession.blendModeManager=this.blendModeManager,this.renderSession.spriteBatch=this.spriteBatch,this.renderSession.stencilManager=this.stencilManager,this.renderSession.renderer=this,this.renderSession.resolution=this.resolution,this.initContext(),this.mapBlendModes()
+},b.WebGLRenderer.prototype.constructor=b.WebGLRenderer,b.WebGLRenderer.prototype.initContext=function(){var a=this.view.getContext("webgl",this._contextOptions)||this.view.getContext("experimental-webgl",this._contextOptions);if(this.gl=a,!a)throw new Error("This browser does not support webGL. Try using the canvas renderer");this.glContextId=a.id=b.WebGLRenderer.glContextId++,b.glContexts[this.glContextId]=a,b.instances[this.glContextId]=this,a.disable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.enable(a.BLEND),this.shaderManager.setContext(a),this.spriteBatch.setContext(a),this.maskManager.setContext(a),this.filterManager.setContext(a),this.blendModeManager.setContext(a),this.stencilManager.setContext(a),this.renderSession.gl=this.gl,this.resize(this.width,this.height)},b.WebGLRenderer.prototype.render=function(a){if(!this.contextLost){this.__stage!==a&&(this.__stage=a),a.updateTransform();var b=this.gl;b.viewport(0,0,this.width,this.height),b.bindFramebuffer(b.FRAMEBUFFER,null),this.clearBeforeRender&&(this.transparent?b.clearColor(0,0,0,0):b.clearColor(a.backgroundColorSplit[0],a.backgroundColorSplit[1],a.backgroundColorSplit[2],1),b.clear(b.COLOR_BUFFER_BIT)),this.renderDisplayObject(a,this.projection)}},b.WebGLRenderer.prototype.renderDisplayObject=function(a,c,d,e){this.renderSession.blendModeManager.setBlendMode(b.blendModes.NORMAL),this.renderSession.drawCount=0,this.renderSession.flipY=d?-1:1,this.renderSession.projection=c,this.renderSession.offset=this.offset,this.spriteBatch.begin(this.renderSession),this.filterManager.begin(this.renderSession,d),a._renderWebGL(this.renderSession,e),this.spriteBatch.end()},b.WebGLRenderer.prototype.resize=function(a,b){this.width=a*this.resolution,this.height=b*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.gl.viewport(0,0,this.width,this.height),this.projection.x=this.width/2/this.resolution,this.projection.y=-this.height/2/this.resolution},b.WebGLRenderer.prototype.updateTexture=function(a){if(a.hasLoaded){var c=this.gl;return a._glTextures[c.id]||(a._glTextures[c.id]=c.createTexture()),c.bindTexture(c.TEXTURE_2D,a._glTextures[c.id]),c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultipliedAlpha),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,a.source),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,a.scaleMode===b.scaleModes.LINEAR?c.LINEAR:c.NEAREST),a.mipmap&&b.isPowerOfTwo(a.width,a.height)?(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,a.scaleMode===b.scaleModes.LINEAR?c.LINEAR_MIPMAP_LINEAR:c.NEAREST_MIPMAP_NEAREST),c.generateMipmap(c.TEXTURE_2D)):c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,a.scaleMode===b.scaleModes.LINEAR?c.LINEAR:c.NEAREST),a._powerOf2?(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.REPEAT),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.REPEAT)):(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE)),a._dirty[c.id]=!1,a._glTextures[c.id]}},b.WebGLRenderer.prototype.destroy=function(){b.glContexts[this.glContextId]=null,this.projection=null,this.offset=null,this.shaderManager.destroy(),this.spriteBatch.destroy(),this.maskManager.destroy(),this.filterManager.destroy(),this.shaderManager=null,this.spriteBatch=null,this.maskManager=null,this.filterManager=null,this.gl=null,this.renderSession=null,b.instances[this.glContextId]=null,b.WebGLRenderer.glContextId--},b.WebGLRenderer.prototype.mapBlendModes=function(){var a=this.gl;b.blendModesWebGL||(b.blendModesWebGL=[],b.blendModesWebGL[b.blendModes.NORMAL]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.ADD]=[a.SRC_ALPHA,a.DST_ALPHA],b.blendModesWebGL[b.blendModes.MULTIPLY]=[a.DST_COLOR,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.SCREEN]=[a.SRC_ALPHA,a.ONE],b.blendModesWebGL[b.blendModes.OVERLAY]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.DARKEN]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.LIGHTEN]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.COLOR_DODGE]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.COLOR_BURN]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.HARD_LIGHT]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.SOFT_LIGHT]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.DIFFERENCE]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.EXCLUSION]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.HUE]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.SATURATION]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.COLOR]=[a.ONE,a.ONE_MINUS_SRC_ALPHA],b.blendModesWebGL[b.blendModes.LUMINOSITY]=[a.ONE,a.ONE_MINUS_SRC_ALPHA])},b.WebGLRenderer.glContextId=0,b.WebGLBlendModeManager=function(){this.currentBlendMode=99999},b.WebGLBlendModeManager.prototype.constructor=b.WebGLBlendModeManager,b.WebGLBlendModeManager.prototype.setContext=function(a){this.gl=a},b.WebGLBlendModeManager.prototype.setBlendMode=function(a){if(this.currentBlendMode===a)return!1;this.currentBlendMode=a;var c=b.blendModesWebGL[this.currentBlendMode];return this.gl.blendFunc(c[0],c[1]),!0},b.WebGLBlendModeManager.prototype.destroy=function(){this.gl=null},b.WebGLMaskManager=function(){},b.WebGLMaskManager.prototype.constructor=b.WebGLMaskManager,b.WebGLMaskManager.prototype.setContext=function(a){this.gl=a},b.WebGLMaskManager.prototype.pushMask=function(a,c){var d=c.gl;a.dirty&&b.WebGLGraphics.updateGraphics(a,d),a._webGL[d.id].data.length&&c.stencilManager.pushStencil(a,a._webGL[d.id].data[0],c)},b.WebGLMaskManager.prototype.popMask=function(a,b){var c=this.gl;b.stencilManager.popStencil(a,a._webGL[c.id].data[0],b)},b.WebGLMaskManager.prototype.destroy=function(){this.gl=null},b.WebGLStencilManager=function(){this.stencilStack=[],this.reverse=!0,this.count=0},b.WebGLStencilManager.prototype.setContext=function(a){this.gl=a},b.WebGLStencilManager.prototype.pushStencil=function(a,b,c){var d=this.gl;this.bindGraphics(a,b,c),0===this.stencilStack.length&&(d.enable(d.STENCIL_TEST),d.clear(d.STENCIL_BUFFER_BIT),this.reverse=!0,this.count=0),this.stencilStack.push(b);var e=this.count;d.colorMask(!1,!1,!1,!1),d.stencilFunc(d.ALWAYS,0,255),d.stencilOp(d.KEEP,d.KEEP,d.INVERT),1===b.mode?(d.drawElements(d.TRIANGLE_FAN,b.indices.length-4,d.UNSIGNED_SHORT,0),this.reverse?(d.stencilFunc(d.EQUAL,255-e,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)):(d.stencilFunc(d.EQUAL,e,255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)),d.drawElements(d.TRIANGLE_FAN,4,d.UNSIGNED_SHORT,2*(b.indices.length-4)),this.reverse?d.stencilFunc(d.EQUAL,255-(e+1),255):d.stencilFunc(d.EQUAL,e+1,255),this.reverse=!this.reverse):(this.reverse?(d.stencilFunc(d.EQUAL,e,255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)):(d.stencilFunc(d.EQUAL,255-e,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)),d.drawElements(d.TRIANGLE_STRIP,b.indices.length,d.UNSIGNED_SHORT,0),this.reverse?d.stencilFunc(d.EQUAL,e+1,255):d.stencilFunc(d.EQUAL,255-(e+1),255)),d.colorMask(!0,!0,!0,!0),d.stencilOp(d.KEEP,d.KEEP,d.KEEP),this.count++},b.WebGLStencilManager.prototype.bindGraphics=function(a,c,d){this._currentGraphics=a;var e,f=this.gl,g=d.projection,h=d.offset;1===c.mode?(e=d.shaderManager.complexPrimitiveShader,d.shaderManager.setShader(e),f.uniform1f(e.flipY,d.flipY),f.uniformMatrix3fv(e.translationMatrix,!1,a.worldTransform.toArray(!0)),f.uniform2f(e.projectionVector,g.x,-g.y),f.uniform2f(e.offsetVector,-h.x,-h.y),f.uniform3fv(e.tintColor,b.hex2rgb(a.tint)),f.uniform3fv(e.color,c.color),f.uniform1f(e.alpha,a.worldAlpha*c.alpha),f.bindBuffer(f.ARRAY_BUFFER,c.buffer),f.vertexAttribPointer(e.aVertexPosition,2,f.FLOAT,!1,8,0),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c.indexBuffer)):(e=d.shaderManager.primitiveShader,d.shaderManager.setShader(e),f.uniformMatrix3fv(e.translationMatrix,!1,a.worldTransform.toArray(!0)),f.uniform1f(e.flipY,d.flipY),f.uniform2f(e.projectionVector,g.x,-g.y),f.uniform2f(e.offsetVector,-h.x,-h.y),f.uniform3fv(e.tintColor,b.hex2rgb(a.tint)),f.uniform1f(e.alpha,a.worldAlpha),f.bindBuffer(f.ARRAY_BUFFER,c.buffer),f.vertexAttribPointer(e.aVertexPosition,2,f.FLOAT,!1,24,0),f.vertexAttribPointer(e.colorAttribute,4,f.FLOAT,!1,24,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c.indexBuffer))},b.WebGLStencilManager.prototype.popStencil=function(a,b,c){var d=this.gl;if(this.stencilStack.pop(),this.count--,0===this.stencilStack.length)d.disable(d.STENCIL_TEST);else{var e=this.count;this.bindGraphics(a,b,c),d.colorMask(!1,!1,!1,!1),1===b.mode?(this.reverse=!this.reverse,this.reverse?(d.stencilFunc(d.EQUAL,255-(e+1),255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)):(d.stencilFunc(d.EQUAL,e+1,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)),d.drawElements(d.TRIANGLE_FAN,4,d.UNSIGNED_SHORT,2*(b.indices.length-4)),d.stencilFunc(d.ALWAYS,0,255),d.stencilOp(d.KEEP,d.KEEP,d.INVERT),d.drawElements(d.TRIANGLE_FAN,b.indices.length-4,d.UNSIGNED_SHORT,0),this.reverse?d.stencilFunc(d.EQUAL,e,255):d.stencilFunc(d.EQUAL,255-e,255)):(this.reverse?(d.stencilFunc(d.EQUAL,e+1,255),d.stencilOp(d.KEEP,d.KEEP,d.DECR)):(d.stencilFunc(d.EQUAL,255-(e+1),255),d.stencilOp(d.KEEP,d.KEEP,d.INCR)),d.drawElements(d.TRIANGLE_STRIP,b.indices.length,d.UNSIGNED_SHORT,0),this.reverse?d.stencilFunc(d.EQUAL,e,255):d.stencilFunc(d.EQUAL,255-e,255)),d.colorMask(!0,!0,!0,!0),d.stencilOp(d.KEEP,d.KEEP,d.KEEP)}},b.WebGLStencilManager.prototype.destroy=function(){this.stencilStack=null,this.gl=null},b.WebGLShaderManager=function(){this.maxAttibs=10,this.attribState=[],this.tempAttribState=[];for(var a=0;a<this.maxAttibs;a++)this.attribState[a]=!1;this.stack=[]},b.WebGLShaderManager.prototype.constructor=b.WebGLShaderManager,b.WebGLShaderManager.prototype.setContext=function(a){this.gl=a,this.primitiveShader=new b.PrimitiveShader(a),this.complexPrimitiveShader=new b.ComplexPrimitiveShader(a),this.defaultShader=new b.PixiShader(a),this.fastShader=new b.PixiFastShader(a),this.stripShader=new b.StripShader(a),this.setShader(this.defaultShader)},b.WebGLShaderManager.prototype.setAttribs=function(a){var b;for(b=0;b<this.tempAttribState.length;b++)this.tempAttribState[b]=!1;for(b=0;b<a.length;b++){var c=a[b];this.tempAttribState[c]=!0}var d=this.gl;for(b=0;b<this.attribState.length;b++)this.attribState[b]!==this.tempAttribState[b]&&(this.attribState[b]=this.tempAttribState[b],this.tempAttribState[b]?d.enableVertexAttribArray(b):d.disableVertexAttribArray(b))},b.WebGLShaderManager.prototype.setShader=function(a){return this._currentId===a._UID?!1:(this._currentId=a._UID,this.currentShader=a,this.gl.useProgram(a.program),this.setAttribs(a.attributes),!0)},b.WebGLShaderManager.prototype.destroy=function(){this.attribState=null,this.tempAttribState=null,this.primitiveShader.destroy(),this.complexPrimitiveShader.destroy(),this.defaultShader.destroy(),this.fastShader.destroy(),this.stripShader.destroy(),this.gl=null},b.WebGLSpriteBatch=function(){this.vertSize=5,this.size=2e3;var a=4*this.size*4*this.vertSize,c=6*this.size;this.vertices=new b.ArrayBuffer(a),this.positions=new b.Float32Array(this.vertices),this.colors=new b.Uint32Array(this.vertices),this.indices=new b.Uint16Array(c),this.lastIndexCount=0;for(var d=0,e=0;c>d;d+=6,e+=4)this.indices[d+0]=e+0,this.indices[d+1]=e+1,this.indices[d+2]=e+2,this.indices[d+3]=e+0,this.indices[d+4]=e+2,this.indices[d+5]=e+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.dirty=!0,this.textures=[],this.blendModes=[],this.shaders=[],this.sprites=[],this.defaultShader=new b.AbstractFilter(["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {","   gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"])},b.WebGLSpriteBatch.prototype.setContext=function(a){this.gl=a,this.vertexBuffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,this.indices,a.STATIC_DRAW),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bufferData(a.ARRAY_BUFFER,this.vertices,a.DYNAMIC_DRAW),this.currentBlendMode=99999;var c=new b.PixiShader(a);c.fragmentSrc=this.defaultShader.fragmentSrc,c.uniforms={},c.init(),this.defaultShader.shaders[a.id]=c},b.WebGLSpriteBatch.prototype.begin=function(a){this.renderSession=a,this.shader=this.renderSession.shaderManager.defaultShader,this.start()},b.WebGLSpriteBatch.prototype.end=function(){this.flush()},b.WebGLSpriteBatch.prototype.render=function(a,b){var c=a.texture,d=a.worldTransform;b&&(d=b),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=c.baseTexture);var e=c._uvs;if(e){var f,g,h,i,j=a.anchor.x,k=a.anchor.y;if(c.trim){var l=c.trim;g=l.x-j*l.width,f=g+c.crop.width,i=l.y-k*l.height,h=i+c.crop.height}else f=c.frame.width*(1-j),g=c.frame.width*-j,h=c.frame.height*(1-k),i=c.frame.height*-k;var m=4*this.currentBatchSize*this.vertSize,n=c.baseTexture.resolution,o=d.a/n,p=d.b/n,q=d.c/n,r=d.d/n,s=d.tx,t=d.ty,u=this.colors,v=this.positions;this.renderSession.roundPixels?(v[m]=o*g+q*i+s|0,v[m+1]=r*i+p*g+t|0,v[m+5]=o*f+q*i+s|0,v[m+6]=r*i+p*f+t|0,v[m+10]=o*f+q*h+s|0,v[m+11]=r*h+p*f+t|0,v[m+15]=o*g+q*h+s|0,v[m+16]=r*h+p*g+t|0):(v[m]=o*g+q*i+s,v[m+1]=r*i+p*g+t,v[m+5]=o*f+q*i+s,v[m+6]=r*i+p*f+t,v[m+10]=o*f+q*h+s,v[m+11]=r*h+p*f+t,v[m+15]=o*g+q*h+s,v[m+16]=r*h+p*g+t),v[m+2]=e.x0,v[m+3]=e.y0,v[m+7]=e.x1,v[m+8]=e.y1,v[m+12]=e.x2,v[m+13]=e.y2,v[m+17]=e.x3,v[m+18]=e.y3;var w=a.tint;u[m+4]=u[m+9]=u[m+14]=u[m+19]=(w>>16)+(65280&w)+((255&w)<<16)+(255*a.worldAlpha<<24),this.sprites[this.currentBatchSize++]=a}},b.WebGLSpriteBatch.prototype.renderTilingSprite=function(a){var c=a.tilingTexture;this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=c.baseTexture),a._uvs||(a._uvs=new b.TextureUvs);var d=a._uvs,e=c.baseTexture.width,f=c.baseTexture.height;a.tilePosition.x%=e*a.tileScaleOffset.x,a.tilePosition.y%=f*a.tileScaleOffset.y;var g=a.tilePosition.x/(e*a.tileScaleOffset.x),h=a.tilePosition.y/(f*a.tileScaleOffset.y),i=a.width/e/(a.tileScale.x*a.tileScaleOffset.x),j=a.height/f/(a.tileScale.y*a.tileScaleOffset.y);d.x0=0-g,d.y0=0-h,d.x1=1*i-g,d.y1=0-h,d.x2=1*i-g,d.y2=1*j-h,d.x3=0-g,d.y3=1*j-h;var k=a.tint,l=(k>>16)+(65280&k)+((255&k)<<16)+(255*a.worldAlpha<<24),m=this.positions,n=this.colors,o=a.width,p=a.height,q=a.anchor.x,r=a.anchor.y,s=o*(1-q),t=o*-q,u=p*(1-r),v=p*-r,w=4*this.currentBatchSize*this.vertSize,x=c.baseTexture.resolution,y=a.worldTransform,z=y.a/x,A=y.b/x,B=y.c/x,C=y.d/x,D=y.tx,E=y.ty;m[w++]=z*t+B*v+D,m[w++]=C*v+A*t+E,m[w++]=d.x0,m[w++]=d.y0,n[w++]=l,m[w++]=z*s+B*v+D,m[w++]=C*v+A*s+E,m[w++]=d.x1,m[w++]=d.y1,n[w++]=l,m[w++]=z*s+B*u+D,m[w++]=C*u+A*s+E,m[w++]=d.x2,m[w++]=d.y2,n[w++]=l,m[w++]=z*t+B*u+D,m[w++]=C*u+A*t+E,m[w++]=d.x3,m[w++]=d.y3,n[w++]=l,this.sprites[this.currentBatchSize++]=a},b.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var a,c=this.gl;if(this.dirty){this.dirty=!1,c.activeTexture(c.TEXTURE0),c.bindBuffer(c.ARRAY_BUFFER,this.vertexBuffer),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a=this.defaultShader.shaders[c.id];var d=4*this.vertSize;c.vertexAttribPointer(a.aVertexPosition,2,c.FLOAT,!1,d,0),c.vertexAttribPointer(a.aTextureCoord,2,c.FLOAT,!1,d,8),c.vertexAttribPointer(a.colorAttribute,4,c.UNSIGNED_BYTE,!0,d,16)}if(this.currentBatchSize>.5*this.size)c.bufferSubData(c.ARRAY_BUFFER,0,this.vertices);else{var e=this.positions.subarray(0,4*this.currentBatchSize*this.vertSize);c.bufferSubData(c.ARRAY_BUFFER,0,e)}for(var f,g,h,i,j=0,k=0,l=null,m=this.renderSession.blendModeManager.currentBlendMode,n=null,o=!1,p=!1,q=0,r=this.currentBatchSize;r>q;q++){if(i=this.sprites[q],f=i.tilingTexture?i.tilingTexture.baseTexture:i.texture.baseTexture,g=i.blendMode,h=i.shader||this.defaultShader,o=m!==g,p=n!==h,(l!==f||o||p)&&(this.renderBatch(l,j,k),k=q,j=0,l=f,o&&(m=g,this.renderSession.blendModeManager.setBlendMode(m)),p)){n=h,a=n.shaders[c.id],a||(a=new b.PixiShader(c),a.fragmentSrc=n.fragmentSrc,a.uniforms=n.uniforms,a.init(),n.shaders[c.id]=a),this.renderSession.shaderManager.setShader(a),a.dirty&&a.syncUniforms();var s=this.renderSession.projection;c.uniform2f(a.projectionVector,s.x,s.y);var t=this.renderSession.offset;c.uniform2f(a.offsetVector,t.x,t.y)}j++}this.renderBatch(l,j,k),this.currentBatchSize=0}},b.WebGLSpriteBatch.prototype.renderBatch=function(a,b,c){if(0!==b){var d=this.gl;a._dirty[d.id]?this.renderSession.renderer.updateTexture(a):d.bindTexture(d.TEXTURE_2D,a._glTextures[d.id]),d.drawElements(d.TRIANGLES,6*b,d.UNSIGNED_SHORT,6*c*2),this.renderSession.drawCount++}},b.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},b.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},b.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null,this.indices=null,this.gl.deleteBuffer(this.vertexBuffer),this.gl.deleteBuffer(this.indexBuffer),this.currentBaseTexture=null,this.gl=null},b.WebGLFastSpriteBatch=function(a){this.vertSize=10,this.maxSize=6e3,this.size=this.maxSize;var c=4*this.size*this.vertSize,d=6*this.maxSize;this.vertices=new b.Float32Array(c),this.indices=new b.Uint16Array(d),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var e=0,f=0;d>e;e+=6,f+=4)this.indices[e+0]=f+0,this.indices[e+1]=f+1,this.indices[e+2]=f+2,this.indices[e+3]=f+0,this.indices[e+4]=f+2,this.indices[e+5]=f+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.currentBlendMode=0,this.renderSession=null,this.shader=null,this.matrix=null,this.setContext(a)},b.WebGLFastSpriteBatch.prototype.constructor=b.WebGLFastSpriteBatch,b.WebGLFastSpriteBatch.prototype.setContext=function(a){this.gl=a,this.vertexBuffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,this.indices,a.STATIC_DRAW),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bufferData(a.ARRAY_BUFFER,this.vertices,a.DYNAMIC_DRAW)},b.WebGLFastSpriteBatch.prototype.begin=function(a,b){this.renderSession=b,this.shader=this.renderSession.shaderManager.fastShader,this.matrix=a.worldTransform.toArray(!0),this.start()},b.WebGLFastSpriteBatch.prototype.end=function(){this.flush()},b.WebGLFastSpriteBatch.prototype.render=function(a){var b=a.children,c=b[0];if(c.texture._uvs){this.currentBaseTexture=c.texture.baseTexture,c.blendMode!==this.renderSession.blendModeManager.currentBlendMode&&(this.flush(),this.renderSession.blendModeManager.setBlendMode(c.blendMode));for(var d=0,e=b.length;e>d;d++)this.renderSprite(b[d]);this.flush()}},b.WebGLFastSpriteBatch.prototype.renderSprite=function(a){if(a.visible&&(a.texture.baseTexture===this.currentBaseTexture||(this.flush(),this.currentBaseTexture=a.texture.baseTexture,a.texture._uvs))){var b,c,d,e,f,g,h,i,j=this.vertices;if(b=a.texture._uvs,c=a.texture.frame.width,d=a.texture.frame.height,a.texture.trim){var k=a.texture.trim;f=k.x-a.anchor.x*k.width,e=f+a.texture.crop.width,h=k.y-a.anchor.y*k.height,g=h+a.texture.crop.height}else e=a.texture.frame.width*(1-a.anchor.x),f=a.texture.frame.width*-a.anchor.x,g=a.texture.frame.height*(1-a.anchor.y),h=a.texture.frame.height*-a.anchor.y;i=4*this.currentBatchSize*this.vertSize,j[i++]=f,j[i++]=h,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x0,j[i++]=b.y1,j[i++]=a.alpha,j[i++]=e,j[i++]=h,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x1,j[i++]=b.y1,j[i++]=a.alpha,j[i++]=e,j[i++]=g,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x2,j[i++]=b.y2,j[i++]=a.alpha,j[i++]=f,j[i++]=g,j[i++]=a.position.x,j[i++]=a.position.y,j[i++]=a.scale.x,j[i++]=a.scale.y,j[i++]=a.rotation,j[i++]=b.x3,j[i++]=b.y3,j[i++]=a.alpha,this.currentBatchSize++,this.currentBatchSize>=this.size&&this.flush()}},b.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var a=this.gl;if(this.currentBaseTexture._glTextures[a.id]||this.renderSession.renderer.updateTexture(this.currentBaseTexture,a),a.bindTexture(a.TEXTURE_2D,this.currentBaseTexture._glTextures[a.id]),this.currentBatchSize>.5*this.size)a.bufferSubData(a.ARRAY_BUFFER,0,this.vertices);else{var b=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);a.bufferSubData(a.ARRAY_BUFFER,0,b)}a.drawElements(a.TRIANGLES,6*this.currentBatchSize,a.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}},b.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},b.WebGLFastSpriteBatch.prototype.start=function(){var a=this.gl;a.activeTexture(a.TEXTURE0),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var b=this.renderSession.projection;a.uniform2f(this.shader.projectionVector,b.x,b.y),a.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var c=4*this.vertSize;a.vertexAttribPointer(this.shader.aVertexPosition,2,a.FLOAT,!1,c,0),a.vertexAttribPointer(this.shader.aPositionCoord,2,a.FLOAT,!1,c,8),a.vertexAttribPointer(this.shader.aScale,2,a.FLOAT,!1,c,16),a.vertexAttribPointer(this.shader.aRotation,1,a.FLOAT,!1,c,24),a.vertexAttribPointer(this.shader.aTextureCoord,2,a.FLOAT,!1,c,28),a.vertexAttribPointer(this.shader.colorAttribute,1,a.FLOAT,!1,c,36)},b.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},b.WebGLFilterManager.prototype.constructor=b.WebGLFilterManager,b.WebGLFilterManager.prototype.setContext=function(a){this.gl=a,this.texturePool=[],this.initShaderBuffers()},b.WebGLFilterManager.prototype.begin=function(a,b){this.renderSession=a,this.defaultShader=a.shaderManager.defaultShader;var c=this.renderSession.projection;this.width=2*c.x,this.height=2*-c.y,this.buffer=b},b.WebGLFilterManager.prototype.pushFilter=function(a){var c=this.gl,d=this.renderSession.projection,e=this.renderSession.offset;a._filterArea=a.target.filterArea||a.target.getBounds(),this.filterStack.push(a);var f=a.filterPasses[0];this.offsetX+=a._filterArea.x,this.offsetY+=a._filterArea.y;var g=this.texturePool.pop();g?g.resize(this.width,this.height):g=new b.FilterTexture(this.gl,this.width,this.height),c.bindTexture(c.TEXTURE_2D,g.texture);var h=a._filterArea,i=f.padding;h.x-=i,h.y-=i,h.width+=2*i,h.height+=2*i,h.x<0&&(h.x=0),h.width>this.width&&(h.width=this.width),h.y<0&&(h.y=0),h.height>this.height&&(h.height=this.height),c.bindFramebuffer(c.FRAMEBUFFER,g.frameBuffer),c.viewport(0,0,h.width,h.height),d.x=h.width/2,d.y=-h.height/2,e.x=-h.x,e.y=-h.y,c.colorMask(!0,!0,!0,!0),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),a._glFilterTexture=g},b.WebGLFilterManager.prototype.popFilter=function(){var a=this.gl,c=this.filterStack.pop(),d=c._filterArea,e=c._glFilterTexture,f=this.renderSession.projection,g=this.renderSession.offset;if(c.filterPasses.length>1){a.viewport(0,0,d.width,d.height),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=d.height,this.vertexArray[2]=d.width,this.vertexArray[3]=d.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=d.width,this.vertexArray[7]=0,a.bufferSubData(a.ARRAY_BUFFER,0,this.vertexArray),a.bindBuffer(a.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=d.width/this.width,this.uvArray[5]=d.height/this.height,this.uvArray[6]=d.width/this.width,this.uvArray[7]=d.height/this.height,a.bufferSubData(a.ARRAY_BUFFER,0,this.uvArray);var h=e,i=this.texturePool.pop();i||(i=new b.FilterTexture(this.gl,this.width,this.height)),i.resize(this.width,this.height),a.bindFramebuffer(a.FRAMEBUFFER,i.frameBuffer),a.clear(a.COLOR_BUFFER_BIT),a.disable(a.BLEND);for(var j=0;j<c.filterPasses.length-1;j++){var k=c.filterPasses[j];a.bindFramebuffer(a.FRAMEBUFFER,i.frameBuffer),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,h.texture),this.applyFilterPass(k,d,d.width,d.height);var l=h;h=i,i=l}a.enable(a.BLEND),e=h,this.texturePool.push(i)}var m=c.filterPasses[c.filterPasses.length-1];this.offsetX-=d.x,this.offsetY-=d.y;var n=this.width,o=this.height,p=0,q=0,r=this.buffer;if(0===this.filterStack.length)a.colorMask(!0,!0,!0,!0);else{var s=this.filterStack[this.filterStack.length-1];d=s._filterArea,n=d.width,o=d.height,p=d.x,q=d.y,r=s._glFilterTexture.frameBuffer}f.x=n/2,f.y=-o/2,g.x=p,g.y=q,d=c._filterArea;var t=d.x-p,u=d.y-q;a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=t,this.vertexArray[1]=u+d.height,this.vertexArray[2]=t+d.width,this.vertexArray[3]=u+d.height,this.vertexArray[4]=t,this.vertexArray[5]=u,this.vertexArray[6]=t+d.width,this.vertexArray[7]=u,a.bufferSubData(a.ARRAY_BUFFER,0,this.vertexArray),a.bindBuffer(a.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=d.width/this.width,this.uvArray[5]=d.height/this.height,this.uvArray[6]=d.width/this.width,this.uvArray[7]=d.height/this.height,a.bufferSubData(a.ARRAY_BUFFER,0,this.uvArray),a.viewport(0,0,n*this.renderSession.resolution,o*this.renderSession.resolution),a.bindFramebuffer(a.FRAMEBUFFER,r),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,e.texture),this.applyFilterPass(m,d,n,o),this.texturePool.push(e),c._glFilterTexture=null},b.WebGLFilterManager.prototype.applyFilterPass=function(a,c,d,e){var f=this.gl,g=a.shaders[f.id];g||(g=new b.PixiShader(f),g.fragmentSrc=a.fragmentSrc,g.uniforms=a.uniforms,g.init(),a.shaders[f.id]=g),this.renderSession.shaderManager.setShader(g),f.uniform2f(g.projectionVector,d/2,-e/2),f.uniform2f(g.offsetVector,0,0),a.uniforms.dimensions&&(a.uniforms.dimensions.value[0]=this.width,a.uniforms.dimensions.value[1]=this.height,a.uniforms.dimensions.value[2]=this.vertexArray[0],a.uniforms.dimensions.value[3]=this.vertexArray[5]),g.syncUniforms(),f.bindBuffer(f.ARRAY_BUFFER,this.vertexBuffer),f.vertexAttribPointer(g.aVertexPosition,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ARRAY_BUFFER,this.uvBuffer),f.vertexAttribPointer(g.aTextureCoord,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ARRAY_BUFFER,this.colorBuffer),f.vertexAttribPointer(g.colorAttribute,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,this.indexBuffer),f.drawElements(f.TRIANGLES,6,f.UNSIGNED_SHORT,0),this.renderSession.drawCount++},b.WebGLFilterManager.prototype.initShaderBuffers=function(){var a=this.gl;this.vertexBuffer=a.createBuffer(),this.uvBuffer=a.createBuffer(),this.colorBuffer=a.createBuffer(),this.indexBuffer=a.createBuffer(),this.vertexArray=new b.Float32Array([0,0,1,0,0,1,1,1]),a.bindBuffer(a.ARRAY_BUFFER,this.vertexBuffer),a.bufferData(a.ARRAY_BUFFER,this.vertexArray,a.STATIC_DRAW),this.uvArray=new b.Float32Array([0,0,1,0,0,1,1,1]),a.bindBuffer(a.ARRAY_BUFFER,this.uvBuffer),a.bufferData(a.ARRAY_BUFFER,this.uvArray,a.STATIC_DRAW),this.colorArray=new b.Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),a.bindBuffer(a.ARRAY_BUFFER,this.colorBuffer),a.bufferData(a.ARRAY_BUFFER,this.colorArray,a.STATIC_DRAW),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,this.indexBuffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),a.STATIC_DRAW)},b.WebGLFilterManager.prototype.destroy=function(){var a=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var b=0;b<this.texturePool.length;b++)this.texturePool[b].destroy();this.texturePool=null,a.deleteBuffer(this.vertexBuffer),a.deleteBuffer(this.uvBuffer),a.deleteBuffer(this.colorBuffer),a.deleteBuffer(this.indexBuffer)},b.FilterTexture=function(a,c,d,e){this.gl=a,this.frameBuffer=a.createFramebuffer(),this.texture=a.createTexture(),e=e||b.scaleModes.DEFAULT,a.bindTexture(a.TEXTURE_2D,this.texture),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,e===b.scaleModes.LINEAR?a.LINEAR:a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,e===b.scaleModes.LINEAR?a.LINEAR:a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.bindFramebuffer(a.FRAMEBUFFER,this.frameBuffer),a.bindFramebuffer(a.FRAMEBUFFER,this.frameBuffer),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,this.texture,0),this.renderBuffer=a.createRenderbuffer(),a.bindRenderbuffer(a.RENDERBUFFER,this.renderBuffer),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,this.renderBuffer),this.resize(c,d)},b.FilterTexture.prototype.constructor=b.FilterTexture,b.FilterTexture.prototype.clear=function(){var a=this.gl;a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT)},b.FilterTexture.prototype.resize=function(a,b){if(this.width!==a||this.height!==b){this.width=a,this.height=b;var c=this.gl;c.bindTexture(c.TEXTURE_2D,this.texture),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,a,b,0,c.RGBA,c.UNSIGNED_BYTE,null),c.bindRenderbuffer(c.RENDERBUFFER,this.renderBuffer),c.renderbufferStorage(c.RENDERBUFFER,c.DEPTH_STENCIL,a,b)}},b.FilterTexture.prototype.destroy=function(){var a=this.gl;a.deleteFramebuffer(this.frameBuffer),a.deleteTexture(this.texture),this.frameBuffer=null,this.texture=null},b.CanvasBuffer=function(a,b){this.width=a,this.height=b,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.canvas.width=a,this.canvas.height=b},b.CanvasBuffer.prototype.constructor=b.CanvasBuffer,b.CanvasBuffer.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.width,this.height)},b.CanvasBuffer.prototype.resize=function(a,b){this.width=this.canvas.width=a,this.height=this.canvas.height=b},b.CanvasMaskManager=function(){},b.CanvasMaskManager.prototype.constructor=b.CanvasMaskManager,b.CanvasMaskManager.prototype.pushMask=function(a,c){var d=c.context;d.save();var e=a.alpha,f=a.worldTransform,g=c.resolution;d.setTransform(f.a*g,f.b*g,f.c*g,f.d*g,f.tx*g,f.ty*g),b.CanvasGraphics.renderGraphicsMask(a,d),d.clip(),a.worldAlpha=e},b.CanvasMaskManager.prototype.popMask=function(a){a.context.restore()},b.CanvasTinter=function(){},b.CanvasTinter.getTintedTexture=function(a,c){var d=a.tintedTexture||document.createElement("canvas");return b.CanvasTinter.tintMethod(a.texture,c,d),d},b.CanvasTinter.tintWithMultiply=function(a,b,c){var d=c.getContext("2d"),e=a.crop;(c.width!==e.width||c.height!==e.height)&&(c.width=e.width,c.height=e.height),d.clearRect(0,0,e.width,e.height),d.fillStyle="#"+("00000"+(0|b).toString(16)).substr(-6),d.fillRect(0,0,e.width,e.height),d.globalCompositeOperation="multiply",d.drawImage(a.baseTexture.source,e.x,e.y,e.width,e.height,0,0,e.width,e.height),d.globalCompositeOperation="destination-atop",d.drawImage(a.baseTexture.source,e.x,e.y,e.width,e.height,0,0,e.width,e.height)},b.CanvasTinter.tintWithPerPixel=function(a,c,d){var e=d.getContext("2d"),f=a.crop;d.width=f.width,d.height=f.height,e.globalCompositeOperation="copy",e.drawImage(a.baseTexture.source,f.x,f.y,f.width,f.height,0,0,f.width,f.height);for(var g=b.hex2rgb(c),h=g[0],i=g[1],j=g[2],k=e.getImageData(0,0,f.width,f.height),l=k.data,m=0;m<l.length;m+=4)if(l[m+0]*=h,l[m+1]*=i,l[m+2]*=j,!b.CanvasTinter.canHandleAlpha){var n=l[m+3];l[m+0]/=255/n,l[m+1]/=255/n,l[m+2]/=255/n}e.putImageData(k,0,0)},b.CanvasTinter.checkInverseAlpha=function(){var a=new b.CanvasBuffer(2,1);a.context.fillStyle="rgba(10, 20, 30, 0.5)",a.context.fillRect(0,0,1,1);var c=a.context.getImageData(0,0,1,1);if(null===c)return!1;a.context.putImageData(c,1,0);var d=a.context.getImageData(1,0,1,1);return d.data[0]===c.data[0]&&d.data[1]===c.data[1]&&d.data[2]===c.data[2]&&d.data[3]===c.data[3]},b.CanvasTinter.canHandleAlpha=b.CanvasTinter.checkInverseAlpha(),b.CanvasTinter.canUseMultiply=b.canUseNewCanvasBlendModes(),b.CanvasTinter.tintMethod=b.CanvasTinter.canUseMultiply?b.CanvasTinter.tintWithMultiply:b.CanvasTinter.tintWithPerPixel,b.CanvasRenderer=function(a,c,d){if(d)for(var e in b.defaultRenderOptions)void 0===d[e]&&(d[e]=b.defaultRenderOptions[e]);else d=b.defaultRenderOptions;b.defaultRenderer||(b.defaultRenderer=this),this.type=b.CANVAS_RENDERER,this.resolution=d.resolution,this.clearBeforeRender=d.clearBeforeRender,this.transparent=d.transparent,this.autoResize=d.autoResize||!1,this.width=a||800,this.height=c||600,this.width*=this.resolution,this.height*=this.resolution,this.view=d.view||document.createElement("canvas"),this.context=this.view.getContext("2d",{alpha:this.transparent}),this.refresh=!0,this.view.width=this.width*this.resolution,this.view.height=this.height*this.resolution,this.count=0,this.maskManager=new b.CanvasMaskManager,this.renderSession={context:this.context,maskManager:this.maskManager,scaleMode:null,smoothProperty:null,roundPixels:!1},this.mapBlendModes(),this.resize(a,c),"imageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="imageSmoothingEnabled":"webkitImageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="webkitImageSmoothingEnabled":"mozImageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="mozImageSmoothingEnabled":"oImageSmoothingEnabled"in this.context?this.renderSession.smoothProperty="oImageSmoothingEnabled":"msImageSmoothingEnabled"in this.context&&(this.renderSession.smoothProperty="msImageSmoothingEnabled")
+},b.CanvasRenderer.prototype.constructor=b.CanvasRenderer,b.CanvasRenderer.prototype.render=function(a){a.updateTransform(),this.context.setTransform(1,0,0,1,0,0),this.context.globalAlpha=1,this.renderSession.currentBlendMode=b.blendModes.NORMAL,this.context.globalCompositeOperation=b.blendModesCanvas[b.blendModes.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(this.context.fillStyle="black",this.context.clear()),this.clearBeforeRender&&(this.transparent?this.context.clearRect(0,0,this.width,this.height):(this.context.fillStyle=a.backgroundColorString,this.context.fillRect(0,0,this.width,this.height))),this.renderDisplayObject(a)},b.CanvasRenderer.prototype.destroy=function(a){void 0===a&&(a=!0),a&&this.view.parent&&this.view.parent.removeChild(this.view),this.view=null,this.context=null,this.maskManager=null,this.renderSession=null},b.CanvasRenderer.prototype.resize=function(a,b){this.width=a*this.resolution,this.height=b*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px")},b.CanvasRenderer.prototype.renderDisplayObject=function(a,b,c){this.renderSession.context=b||this.context,this.renderSession.resolution=this.resolution,a._renderCanvas(this.renderSession,c)},b.CanvasRenderer.prototype.mapBlendModes=function(){b.blendModesCanvas||(b.blendModesCanvas=[],b.canUseNewCanvasBlendModes()?(b.blendModesCanvas[b.blendModes.NORMAL]="source-over",b.blendModesCanvas[b.blendModes.ADD]="lighter",b.blendModesCanvas[b.blendModes.MULTIPLY]="multiply",b.blendModesCanvas[b.blendModes.SCREEN]="screen",b.blendModesCanvas[b.blendModes.OVERLAY]="overlay",b.blendModesCanvas[b.blendModes.DARKEN]="darken",b.blendModesCanvas[b.blendModes.LIGHTEN]="lighten",b.blendModesCanvas[b.blendModes.COLOR_DODGE]="color-dodge",b.blendModesCanvas[b.blendModes.COLOR_BURN]="color-burn",b.blendModesCanvas[b.blendModes.HARD_LIGHT]="hard-light",b.blendModesCanvas[b.blendModes.SOFT_LIGHT]="soft-light",b.blendModesCanvas[b.blendModes.DIFFERENCE]="difference",b.blendModesCanvas[b.blendModes.EXCLUSION]="exclusion",b.blendModesCanvas[b.blendModes.HUE]="hue",b.blendModesCanvas[b.blendModes.SATURATION]="saturation",b.blendModesCanvas[b.blendModes.COLOR]="color",b.blendModesCanvas[b.blendModes.LUMINOSITY]="luminosity"):(b.blendModesCanvas[b.blendModes.NORMAL]="source-over",b.blendModesCanvas[b.blendModes.ADD]="lighter",b.blendModesCanvas[b.blendModes.MULTIPLY]="source-over",b.blendModesCanvas[b.blendModes.SCREEN]="source-over",b.blendModesCanvas[b.blendModes.OVERLAY]="source-over",b.blendModesCanvas[b.blendModes.DARKEN]="source-over",b.blendModesCanvas[b.blendModes.LIGHTEN]="source-over",b.blendModesCanvas[b.blendModes.COLOR_DODGE]="source-over",b.blendModesCanvas[b.blendModes.COLOR_BURN]="source-over",b.blendModesCanvas[b.blendModes.HARD_LIGHT]="source-over",b.blendModesCanvas[b.blendModes.SOFT_LIGHT]="source-over",b.blendModesCanvas[b.blendModes.DIFFERENCE]="source-over",b.blendModesCanvas[b.blendModes.EXCLUSION]="source-over",b.blendModesCanvas[b.blendModes.HUE]="source-over",b.blendModesCanvas[b.blendModes.SATURATION]="source-over",b.blendModesCanvas[b.blendModes.COLOR]="source-over",b.blendModesCanvas[b.blendModes.LUMINOSITY]="source-over"))},b.CanvasGraphics=function(){},b.CanvasGraphics.renderGraphics=function(a,c){var d=a.worldAlpha;a.dirty&&(this.updateGraphicsTint(a),a.dirty=!1);for(var e=0;e<a.graphicsData.length;e++){var f=a.graphicsData[e],g=f.shape,h=f._fillTint,i=f._lineTint;if(c.lineWidth=f.lineWidth,f.type===b.Graphics.POLY){c.beginPath();var j=g.points;c.moveTo(j[0],j[1]);for(var k=1;k<j.length/2;k++)c.lineTo(j[2*k],j[2*k+1]);g.closed&&c.lineTo(j[0],j[1]),j[0]===j[j.length-2]&&j[1]===j[j.length-1]&&c.closePath(),f.fill&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke())}else if(f.type===b.Graphics.RECT)(f.fillColor||0===f.fillColor)&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fillRect(g.x,g.y,g.width,g.height)),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.strokeRect(g.x,g.y,g.width,g.height));else if(f.type===b.Graphics.CIRC)c.beginPath(),c.arc(g.x,g.y,g.radius,0,2*Math.PI),c.closePath(),f.fill&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke());else if(f.type===b.Graphics.ELIP){var l=2*g.width,m=2*g.height,n=g.x-l/2,o=g.y-m/2;c.beginPath();var p=.5522848,q=l/2*p,r=m/2*p,s=n+l,t=o+m,u=n+l/2,v=o+m/2;c.moveTo(n,v),c.bezierCurveTo(n,v-r,u-q,o,u,o),c.bezierCurveTo(u+q,o,s,v-r,s,v),c.bezierCurveTo(s,v+r,u+q,t,u,t),c.bezierCurveTo(u-q,t,n,v+r,n,v),c.closePath(),f.fill&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke())}else if(f.type===b.Graphics.RREC){var w=g.x,x=g.y,y=g.width,z=g.height,A=g.radius,B=Math.min(y,z)/2|0;A=A>B?B:A,c.beginPath(),c.moveTo(w,x+A),c.lineTo(w,x+z-A),c.quadraticCurveTo(w,x+z,w+A,x+z),c.lineTo(w+y-A,x+z),c.quadraticCurveTo(w+y,x+z,w+y,x+z-A),c.lineTo(w+y,x+A),c.quadraticCurveTo(w+y,x,w+y-A,x),c.lineTo(w+A,x),c.quadraticCurveTo(w,x,w,x+A),c.closePath(),(f.fillColor||0===f.fillColor)&&(c.globalAlpha=f.fillAlpha*d,c.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),c.fill()),f.lineWidth&&(c.globalAlpha=f.lineAlpha*d,c.strokeStyle="#"+("00000"+(0|i).toString(16)).substr(-6),c.stroke())}}},b.CanvasGraphics.renderGraphicsMask=function(a,c){var d=a.graphicsData.length;if(0!==d){c.beginPath();for(var e=0;d>e;e++){var f=a.graphicsData[e],g=f.shape;if(f.type===b.Graphics.POLY){var h=g.points;c.moveTo(h[0],h[1]);for(var i=1;i<h.length/2;i++)c.lineTo(h[2*i],h[2*i+1]);h[0]===h[h.length-2]&&h[1]===h[h.length-1]&&c.closePath()}else if(f.type===b.Graphics.RECT)c.rect(g.x,g.y,g.width,g.height),c.closePath();else if(f.type===b.Graphics.CIRC)c.arc(g.x,g.y,g.radius,0,2*Math.PI),c.closePath();else if(f.type===b.Graphics.ELIP){var j=2*g.width,k=2*g.height,l=g.x-j/2,m=g.y-k/2,n=.5522848,o=j/2*n,p=k/2*n,q=l+j,r=m+k,s=l+j/2,t=m+k/2;c.moveTo(l,t),c.bezierCurveTo(l,t-p,s-o,m,s,m),c.bezierCurveTo(s+o,m,q,t-p,q,t),c.bezierCurveTo(q,t+p,s+o,r,s,r),c.bezierCurveTo(s-o,r,l,t+p,l,t),c.closePath()}else if(f.type===b.Graphics.RREC){var u=g.x,v=g.y,w=g.width,x=g.height,y=g.radius,z=Math.min(w,x)/2|0;y=y>z?z:y,c.moveTo(u,v+y),c.lineTo(u,v+x-y),c.quadraticCurveTo(u,v+x,u+y,v+x),c.lineTo(u+w-y,v+x),c.quadraticCurveTo(u+w,v+x,u+w,v+x-y),c.lineTo(u+w,v+y),c.quadraticCurveTo(u+w,v,u+w-y,v),c.lineTo(u+y,v),c.quadraticCurveTo(u,v,u,v+y),c.closePath()}}}},b.CanvasGraphics.updateGraphicsTint=function(a){if(16777215!==a.tint)for(var b=(a.tint>>16&255)/255,c=(a.tint>>8&255)/255,d=(255&a.tint)/255,e=0;e<a.graphicsData.length;e++){var f=a.graphicsData[e],g=0|f.fillColor,h=0|f.lineColor;f._fillTint=((g>>16&255)/255*b*255<<16)+((g>>8&255)/255*c*255<<8)+(255&g)/255*d*255,f._lineTint=((h>>16&255)/255*b*255<<16)+((h>>8&255)/255*c*255<<8)+(255&h)/255*d*255}},b.BaseTextureCache={},b.BaseTextureCacheIdGenerator=0,b.BaseTexture=function(a,c){this.resolution=1,this.width=100,this.height=100,this.scaleMode=c||b.scaleModes.DEFAULT,this.hasLoaded=!1,this.source=a,this._UID=b._UID++,this.premultipliedAlpha=!0,this._glTextures=[],this.mipmap=!1,this._dirty=[!0,!0,!0,!0],a&&((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height&&(this.hasLoaded=!0,this.width=this.source.naturalWidth||this.source.width,this.height=this.source.naturalHeight||this.source.height,this.dirty()),this.imageUrl=null,this._powerOf2=!1)},b.BaseTexture.prototype.constructor=b.BaseTexture,b.BaseTexture.prototype.forceLoaded=function(a,b){this.hasLoaded=!0,this.width=a,this.height=b,this.dirty()},b.BaseTexture.prototype.destroy=function(){this.imageUrl?(delete b.BaseTextureCache[this.imageUrl],delete b.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")):this.source&&this.source._pixiId&&delete b.BaseTextureCache[this.source._pixiId],this.source=null,this.unloadFromGPU()},b.BaseTexture.prototype.updateSourceImage=function(a){this.hasLoaded=!1,this.source.src=null,this.source.src=a},b.BaseTexture.prototype.dirty=function(){for(var a=0;a<this._glTextures.length;a++)this._dirty[a]=!0},b.BaseTexture.prototype.unloadFromGPU=function(){this.dirty();for(var a=this._glTextures.length-1;a>=0;a--){var c=this._glTextures[a],d=b.glContexts[a];d&&c&&d.deleteTexture(c)}this._glTextures.length=0,this.dirty()},b.BaseTexture.fromImage=function(a,c,d){var e=b.BaseTextureCache[a];if(void 0===c&&-1===a.indexOf("data:")&&(c=!0),!e){var f=new Image;c&&(f.crossOrigin=""),f.src=a,e=new b.BaseTexture(f,d),e.imageUrl=a,b.BaseTextureCache[a]=e,-1!==a.indexOf(b.RETINA_PREFIX+".")&&(e.resolution=2)}return e},b.BaseTexture.fromCanvas=function(a,c){a._pixiId||(a._pixiId="canvas_"+b.TextureCacheIdGenerator++),0===a.width&&(a.width=1),0===a.height&&(a.height=1);var d=b.BaseTextureCache[a._pixiId];return d||(d=new b.BaseTexture(a,c),b.BaseTextureCache[a._pixiId]=d),d},b.TextureCache={},b.FrameCache={},b.TextureSilentFail=!1,b.TextureCacheIdGenerator=0,b.Texture=function(a,c,d,e){this.noFrame=!1,c||(this.noFrame=!0,c=new b.Rectangle(0,0,1,1)),a instanceof b.Texture&&(a=a.baseTexture),this.baseTexture=a,this.frame=c,this.trim=e,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=d||new b.Rectangle(0,0,1,1),a.hasLoaded&&(this.noFrame&&(c=new b.Rectangle(0,0,a.width,a.height)),this.setFrame(c))},b.Texture.prototype.constructor=b.Texture,b.Texture.prototype.onBaseTextureLoaded=function(){var a=this.baseTexture;this.noFrame&&(this.frame=new b.Rectangle(0,0,a.width,a.height)),this.setFrame(this.frame)},b.Texture.prototype.destroy=function(a){a&&this.baseTexture.destroy(),this.valid=!1},b.Texture.prototype.setFrame=function(a){if(this.noFrame=!1,this.frame=a,this.width=a.width,this.height=a.height,this.crop.x=a.x,this.crop.y=a.y,this.crop.width=a.width,this.crop.height=a.height,!this.trim&&(a.x+a.width>this.baseTexture.width||a.y+a.height>this.baseTexture.height)){if(!b.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);return void(this.valid=!1)}this.valid=a&&a.width&&a.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs()},b.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new b.TextureUvs);var a=this.crop,c=this.baseTexture.width,d=this.baseTexture.height;this._uvs.x0=a.x/c,this._uvs.y0=a.y/d,this._uvs.x1=(a.x+a.width)/c,this._uvs.y1=a.y/d,this._uvs.x2=(a.x+a.width)/c,this._uvs.y2=(a.y+a.height)/d,this._uvs.x3=a.x/c,this._uvs.y3=(a.y+a.height)/d},b.Texture.fromImage=function(a,c,d){var e=b.TextureCache[a];return e||(e=new b.Texture(b.BaseTexture.fromImage(a,c,d)),b.TextureCache[a]=e),e},b.Texture.fromFrame=function(a){var c=b.TextureCache[a];if(!c)throw new Error('The frameId "'+a+'" does not exist in the texture cache ');return c},b.Texture.fromCanvas=function(a,c){var d=b.BaseTexture.fromCanvas(a,c);return new b.Texture(d)},b.Texture.addTextureToCache=function(a,c){b.TextureCache[c]=a},b.Texture.removeTextureFromCache=function(a){var c=b.TextureCache[a];return delete b.TextureCache[a],delete b.BaseTextureCache[a],c},b.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},b.RenderTexture=function(a,c,d,e,f){if(this.width=a||100,this.height=c||100,this.resolution=f||1,this.frame=new b.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=new b.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.baseTexture=new b.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=e||b.scaleModes.DEFAULT,this.baseTexture.hasLoaded=!0,b.Texture.call(this,this.baseTexture,new b.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution)),this.renderer=d||b.defaultRenderer,this.renderer.type===b.WEBGL_RENDERER){var g=this.renderer.gl;this.baseTexture._dirty[g.id]=!1,this.textureBuffer=new b.FilterTexture(g,this.width,this.height,this.baseTexture.scaleMode),this.baseTexture._glTextures[g.id]=this.textureBuffer.texture,this.render=this.renderWebGL,this.projection=new b.Point(.5*this.width,.5*-this.height)}else this.render=this.renderCanvas,this.textureBuffer=new b.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new Phaser.Matrix,this._updateUvs()},b.RenderTexture.prototype=Object.create(b.Texture.prototype),b.RenderTexture.prototype.constructor=b.RenderTexture,b.RenderTexture.prototype.resize=function(a,c,d){(a!==this.width||c!==this.height)&&(this.valid=a>0&&c>0,this.width=a,this.height=c,this.frame.width=this.crop.width=a*this.resolution,this.frame.height=this.crop.height=c*this.resolution,d&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===b.WEBGL_RENDERER&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},b.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===b.WEBGL_RENDERER&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},b.RenderTexture.prototype.renderWebGL=function(a,b,c){if(this.valid&&0!==a.alpha){var d=a.worldTransform;d.identity(),d.translate(0,2*this.projection.y),b&&d.append(b),d.scale(1,-1);for(var e=0;e<a.children.length;e++)a.children[e].updateTransform();var f=this.renderer.gl;f.viewport(0,0,this.width*this.resolution,this.height*this.resolution),f.bindFramebuffer(f.FRAMEBUFFER,this.textureBuffer.frameBuffer),c&&this.textureBuffer.clear(),this.renderer.spriteBatch.dirty=!0,this.renderer.renderDisplayObject(a,this.projection,this.textureBuffer.frameBuffer,b),this.renderer.spriteBatch.dirty=!0}},b.RenderTexture.prototype.renderCanvas=function(a,b,c){if(this.valid&&0!==a.alpha){for(var d=0;d<a.children.length;d++)a.children[d].updateTransform();c&&this.textureBuffer.clear();var e=this.renderer.resolution;this.renderer.resolution=this.resolution,this.renderer.renderDisplayObject(a,this.textureBuffer.context,b),this.renderer.resolution=e}},b.RenderTexture.prototype.getImage=function(){var a=new Image;return a.src=this.getBase64(),a},b.RenderTexture.prototype.getBase64=function(){return this.getCanvas().toDataURL()},b.RenderTexture.prototype.getCanvas=function(){if(this.renderer.type===b.WEBGL_RENDERER){var a=this.renderer.gl,c=this.textureBuffer.width,d=this.textureBuffer.height,e=new Uint8Array(4*c*d);a.bindFramebuffer(a.FRAMEBUFFER,this.textureBuffer.frameBuffer),a.readPixels(0,0,c,d,a.RGBA,a.UNSIGNED_BYTE,e),a.bindFramebuffer(a.FRAMEBUFFER,null);var f=new b.CanvasBuffer(c,d),g=f.context.getImageData(0,0,c,d);return g.data.set(e),f.context.putImageData(g,0,0),f.canvas}return this.textureBuffer.canvas},b.AbstractFilter=function(a,b){this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.uniforms=b||{},this.fragmentSrc=a||[]},b.AbstractFilter.prototype.constructor=b.AbstractFilter,b.AbstractFilter.prototype.syncUniforms=function(){for(var a=0,b=this.shaders.length;b>a;a++)this.shaders[a].dirty=!0},b.Strip=function(a){b.DisplayObjectContainer.call(this),this.texture=a,this.uvs=new b.Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new b.Float32Array([0,0,100,0,100,100,0,100]),this.colors=new b.Float32Array([1,1,1,1]),this.indices=new b.Uint16Array([0,1,2,3]),this.dirty=!0,this.blendMode=b.blendModes.NORMAL,this.canvasPadding=0,this.drawMode=b.Strip.DrawModes.TRIANGLE_STRIP},b.Strip.prototype=Object.create(b.DisplayObjectContainer.prototype),b.Strip.prototype.constructor=b.Strip,b.Strip.prototype._renderWebGL=function(a){!this.visible||this.alpha<=0||(a.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(a),a.shaderManager.setShader(a.shaderManager.stripShader),this._renderStrip(a),a.spriteBatch.start())},b.Strip.prototype._initWebGL=function(a){var b=a.gl;this._vertexBuffer=b.createBuffer(),this._indexBuffer=b.createBuffer(),this._uvBuffer=b.createBuffer(),this._colorBuffer=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,this._vertexBuffer),b.bufferData(b.ARRAY_BUFFER,this.vertices,b.DYNAMIC_DRAW),b.bindBuffer(b.ARRAY_BUFFER,this._uvBuffer),b.bufferData(b.ARRAY_BUFFER,this.uvs,b.STATIC_DRAW),b.bindBuffer(b.ARRAY_BUFFER,this._colorBuffer),b.bufferData(b.ARRAY_BUFFER,this.colors,b.STATIC_DRAW),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,this._indexBuffer),b.bufferData(b.ELEMENT_ARRAY_BUFFER,this.indices,b.STATIC_DRAW)},b.Strip.prototype._renderStrip=function(a){var c=a.gl,d=a.projection,e=a.offset,f=a.shaderManager.stripShader,g=this.drawMode===b.Strip.DrawModes.TRIANGLE_STRIP?c.TRIANGLE_STRIP:c.TRIANGLES;a.blendModeManager.setBlendMode(this.blendMode),c.uniformMatrix3fv(f.translationMatrix,!1,this.worldTransform.toArray(!0)),c.uniform2f(f.projectionVector,d.x,-d.y),c.uniform2f(f.offsetVector,-e.x,-e.y),c.uniform1f(f.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,c.bindBuffer(c.ARRAY_BUFFER,this._vertexBuffer),c.bufferData(c.ARRAY_BUFFER,this.vertices,c.STATIC_DRAW),c.vertexAttribPointer(f.aVertexPosition,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this._uvBuffer),c.bufferData(c.ARRAY_BUFFER,this.uvs,c.STATIC_DRAW),c.vertexAttribPointer(f.aTextureCoord,2,c.FLOAT,!1,0,0),c.activeTexture(c.TEXTURE0),this.texture.baseTexture._dirty[c.id]?a.renderer.updateTexture(this.texture.baseTexture):c.bindTexture(c.TEXTURE_2D,this.texture.baseTexture._glTextures[c.id]),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this._indexBuffer),c.bufferData(c.ELEMENT_ARRAY_BUFFER,this.indices,c.STATIC_DRAW)):(c.bindBuffer(c.ARRAY_BUFFER,this._vertexBuffer),c.bufferSubData(c.ARRAY_BUFFER,0,this.vertices),c.vertexAttribPointer(f.aVertexPosition,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this._uvBuffer),c.vertexAttribPointer(f.aTextureCoord,2,c.FLOAT,!1,0,0),c.activeTexture(c.TEXTURE0),this.texture.baseTexture._dirty[c.id]?a.renderer.updateTexture(this.texture.baseTexture):c.bindTexture(c.TEXTURE_2D,this.texture.baseTexture._glTextures[c.id]),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),c.drawElements(g,this.indices.length,c.UNSIGNED_SHORT,0)},b.Strip.prototype._renderCanvas=function(a){var c=a.context,d=this.worldTransform;a.roundPixels?c.setTransform(d.a,d.b,d.c,d.d,0|d.tx,0|d.ty):c.setTransform(d.a,d.b,d.c,d.d,d.tx,d.ty),this.drawMode===b.Strip.DrawModes.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(c):this._renderCanvasTriangles(c)},b.Strip.prototype._renderCanvasTriangleStrip=function(a){var b=this.vertices,c=this.uvs,d=b.length/2;this.count++;for(var e=0;d-2>e;e++){var f=2*e;this._renderCanvasDrawTriangle(a,b,c,f,f+2,f+4)}},b.Strip.prototype._renderCanvasTriangles=function(a){var b=this.vertices,c=this.uvs,d=this.indices,e=d.length;this.count++;for(var f=0;e>f;f+=3){var g=2*d[f],h=2*d[f+1],i=2*d[f+2];this._renderCanvasDrawTriangle(a,b,c,g,h,i)}},b.Strip.prototype._renderCanvasDrawTriangle=function(a,b,c,d,e,f){var g=this.texture.baseTexture.source,h=this.texture.width,i=this.texture.height,j=b[d],k=b[e],l=b[f],m=b[d+1],n=b[e+1],o=b[f+1],p=c[d]*h,q=c[e]*h,r=c[f]*h,s=c[d+1]*i,t=c[e+1]*i,u=c[f+1]*i;if(this.canvasPadding>0){var v=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,x=(j+k+l)/3,y=(m+n+o)/3,z=j-x,A=m-y,B=Math.sqrt(z*z+A*A);j=x+z/B*(B+v),m=y+A/B*(B+w),z=k-x,A=n-y,B=Math.sqrt(z*z+A*A),k=x+z/B*(B+v),n=y+A/B*(B+w),z=l-x,A=o-y,B=Math.sqrt(z*z+A*A),l=x+z/B*(B+v),o=y+A/B*(B+w)}a.save(),a.beginPath(),a.moveTo(j,m),a.lineTo(k,n),a.lineTo(l,o),a.closePath(),a.clip();var C=p*t+s*r+q*u-t*r-s*q-p*u,D=j*t+s*l+k*u-t*l-s*k-j*u,E=p*k+j*r+q*l-k*r-j*q-p*l,F=p*t*l+s*k*r+j*q*u-j*t*r-s*q*l-p*k*u,G=m*t+s*o+n*u-t*o-s*n-m*u,H=p*n+m*r+q*o-n*r-m*q-p*o,I=p*t*o+s*n*r+m*q*u-m*t*r-s*q*o-p*n*u;a.transform(D/C,G/C,E/C,H/C,F/C,I/C),a.drawImage(g,0,0),a.restore()},b.Strip.prototype.renderStripFlat=function(a){var b=this.context,c=a.vertices,d=c.length/2;this.count++,b.beginPath();for(var e=1;d-2>e;e++){var f=2*e,g=c[f],h=c[f+2],i=c[f+4],j=c[f+1],k=c[f+3],l=c[f+5];b.moveTo(g,j),b.lineTo(h,k),b.lineTo(i,l)}b.fillStyle="#FF0000",b.fill(),b.closePath()},b.Strip.prototype.onTextureUpdate=function(){this.updateFrame=!0},b.Strip.prototype.getBounds=function(a){for(var c=a||this.worldTransform,d=c.a,e=c.b,f=c.c,g=c.d,h=c.tx,i=c.ty,j=-1/0,k=-1/0,l=1/0,m=1/0,n=this.vertices,o=0,p=n.length;p>o;o+=2){var q=n[o],r=n[o+1],s=d*q+f*r+h,t=g*r+e*q+i;l=l>s?s:l,m=m>t?t:m,j=s>j?s:j,k=t>k?t:k}if(l===-1/0||1/0===k)return b.EmptyRectangle;var u=this._bounds;return u.x=l,u.width=j-l,u.y=m,u.height=k-m,this._currentBounds=u,u},b.Strip.DrawModes={TRIANGLE_STRIP:0,TRIANGLES:1},b.Rope=function(a,c){b.Strip.call(this,a),this.points=c,this.vertices=new b.Float32Array(4*c.length),this.uvs=new b.Float32Array(4*c.length),this.colors=new b.Float32Array(2*c.length),this.indices=new b.Uint16Array(2*c.length),this.refresh()},b.Rope.prototype=Object.create(b.Strip.prototype),b.Rope.prototype.constructor=b.Rope,b.Rope.prototype.refresh=function(){var a=this.points;if(!(a.length<1)){var b=this.uvs,c=a[0],d=this.indices,e=this.colors;this.count-=.2,b[0]=0,b[1]=0,b[2]=0,b[3]=1,e[0]=1,e[1]=1,d[0]=0,d[1]=1;for(var f,g,h,i=a.length,j=1;i>j;j++)f=a[j],g=4*j,h=j/(i-1),j%2?(b[g]=h,b[g+1]=0,b[g+2]=h,b[g+3]=1):(b[g]=h,b[g+1]=0,b[g+2]=h,b[g+3]=1),g=2*j,e[g]=1,e[g+1]=1,g=2*j,d[g]=g,d[g+1]=g+1,c=f}},b.Rope.prototype.updateTransform=function(){var a=this.points;if(!(a.length<1)){var c,d=a[0],e={x:0,y:0};this.count-=.2;for(var f,g,h,i,j,k=this.vertices,l=a.length,m=0;l>m;m++)f=a[m],g=4*m,c=m<a.length-1?a[m+1]:f,e.y=-(c.x-d.x),e.x=c.y-d.y,h=10*(1-m/(l-1)),h>1&&(h=1),i=Math.sqrt(e.x*e.x+e.y*e.y),j=this.texture.height/2,e.x/=i,e.y/=i,e.x*=j,e.y*=j,k[g]=f.x+e.x,k[g+1]=f.y+e.y,k[g+2]=f.x-e.x,k[g+3]=f.y-e.y,d=f;b.DisplayObjectContainer.prototype.updateTransform.call(this)}},b.Rope.prototype.setTexture=function(a){this.texture=a},b.TilingSprite=function(a,c,d){b.Sprite.call(this,a),this._width=c||128,this._height=d||128,this.tileScale=new b.Point(1,1),this.tileScaleOffset=new b.Point(1,1),this.tilePosition=new b.Point,this.renderable=!0,this.tint=16777215,this.textureDebug=!1,this.blendMode=b.blendModes.NORMAL,this.canvasBuffer=null,this.tilingTexture=null,this.tilePattern=null,this.refreshTexture=!0,this.frameWidth=0,this.frameHeight=0},b.TilingSprite.prototype=Object.create(b.Sprite.prototype),b.TilingSprite.prototype.constructor=b.TilingSprite,b.TilingSprite.prototype.setTexture=function(a){this.texture!==a&&(this.texture=a,this.refreshTexture=!0,this.cachedTint=16777215)},b.TilingSprite.prototype._renderWebGL=function(a){if(this.visible!==!1&&0!==this.alpha){if(this._mask&&(a.spriteBatch.stop(),a.maskManager.pushMask(this.mask,a),a.spriteBatch.start()),this._filters&&(a.spriteBatch.flush(),a.filterManager.pushFilter(this._filterBlock)),this.refreshTexture){if(this.generateTilingTexture(!0),!this.tilingTexture)return;this.tilingTexture.needsUpdate&&(a.renderer.updateTexture(this.tilingTexture.baseTexture),this.tilingTexture.needsUpdate=!1)}a.spriteBatch.renderTilingSprite(this);for(var b=0;b<this.children.length;b++)this.children[b]._renderWebGL(a);a.spriteBatch.stop(),this._filters&&a.filterManager.popFilter(),this._mask&&a.maskManager.popMask(this._mask,a),a.spriteBatch.start()}},b.TilingSprite.prototype._renderCanvas=function(a){if(this.visible!==!1&&0!==this.alpha){var c=a.context;this._mask&&a.maskManager.pushMask(this._mask,a),c.globalAlpha=this.worldAlpha;var d=this.worldTransform,e=a.resolution;if(c.setTransform(d.a*e,d.b*e,d.c*e,d.d*e,d.tx*e,d.ty*e),this.refreshTexture){if(this.generateTilingTexture(!1),!this.tilingTexture)return;this.tilePattern=c.createPattern(this.tilingTexture.baseTexture.source,"repeat")}var f=a.currentBlendMode;this.blendMode!==a.currentBlendMode&&(a.currentBlendMode=this.blendMode,c.globalCompositeOperation=b.blendModesCanvas[a.currentBlendMode]);var g=this.tilePosition,h=this.tileScale;g.x%=this.tilingTexture.baseTexture.width,g.y%=this.tilingTexture.baseTexture.height,c.scale(h.x,h.y),c.translate(g.x+this.anchor.x*-this._width,g.y+this.anchor.y*-this._height),c.fillStyle=this.tilePattern;var i=-g.x,j=-g.y,k=this._width/h.x,l=this._height/h.y;a.roundPixels,c.fillRect(i,j,k,l),c.scale(1/h.x,1/h.y),c.translate(-g.x+this.anchor.x*this._width,-g.y+this.anchor.y*this._height),this._mask&&a.maskManager.popMask(a);for(var m=0;m<this.children.length;m++)this.children[m]._renderCanvas(a);f!==this.blendMode&&(a.currentBlendMode=f,c.globalCompositeOperation=b.blendModesCanvas[f])}},b.TilingSprite.prototype.onTextureUpdate=function(){},b.TilingSprite.prototype.generateTilingTexture=function(a){if(this.texture.baseTexture.hasLoaded){var c=this.texture,d=c.frame,e=this._frame.sourceSizeW,f=this._frame.sourceSizeH,g=0,h=0;this._frame.trimmed&&(g=this._frame.spriteSourceSizeX,h=this._frame.spriteSourceSizeY),a&&(e=b.getNextPowerOfTwo(e),f=b.getNextPowerOfTwo(f)),this.canvasBuffer?(this.canvasBuffer.resize(e,f),this.tilingTexture.baseTexture.width=e,this.tilingTexture.baseTexture.height=f,this.tilingTexture.needsUpdate=!0):(this.canvasBuffer=new b.CanvasBuffer(e,f),this.tilingTexture=b.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture=b.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture.isTiling=!0,this.tilingTexture.needsUpdate=!0),this.textureDebug&&(this.canvasBuffer.context.strokeStyle="#00ff00",this.canvasBuffer.context.strokeRect(0,0,e,f));var i=c.crop.width,j=c.crop.height;(i!==e||j!==f)&&(i=e,j=f),this.canvasBuffer.context.drawImage(c.baseTexture.source,c.crop.x,c.crop.y,c.crop.width,c.crop.height,g,h,i,j),this.tileScaleOffset.x=d.width/e,this.tileScaleOffset.y=d.height/f,this.refreshTexture=!1,this.tilingTexture.baseTexture._powerOf2=!0}},b.TilingSprite.prototype.getBounds=function(){var a=this._width,b=this._height,c=a*(1-this.anchor.x),d=a*-this.anchor.x,e=b*(1-this.anchor.y),f=b*-this.anchor.y,g=this.worldTransform,h=g.a,i=g.b,j=g.c,k=g.d,l=g.tx,m=g.ty,n=h*d+j*f+l,o=k*f+i*d+m,p=h*c+j*f+l,q=k*f+i*c+m,r=h*c+j*e+l,s=k*e+i*c+m,t=h*d+j*e+l,u=k*e+i*d+m,v=-1/0,w=-1/0,x=1/0,y=1/0;x=x>n?n:x,x=x>p?p:x,x=x>r?r:x,x=x>t?t:x,y=y>o?o:y,y=y>q?q:y,y=y>s?s:y,y=y>u?u:y,v=n>v?n:v,v=p>v?p:v,v=r>v?r:v,v=t>v?t:v,w=o>w?o:w,w=q>w?q:w,w=s>w?s:w,w=u>w?u:w;var z=this._bounds;return z.x=x,z.width=v-x,z.y=y,z.height=w-y,this._currentBounds=z,z},b.TilingSprite.prototype.destroy=function(){b.Sprite.prototype.destroy.call(this),this.tileScale=null,this.tileScaleOffset=null,this.tilePosition=null,this.tilingTexture&&(this.tilingTexture.destroy(!0),this.tilingTexture=null)},Object.defineProperty(b.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(a){this._width=a}}),Object.defineProperty(b.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(a){this._height=a}}),"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=b),exports.PIXI=b):"undefined"!=typeof define&&define.amd?define("PIXI",function(){return a.PIXI=b}()):a.PIXI=b,b}.call(this),function(){function a(a,b){this._scaleFactor=a,this._deltaMode=b,this.originalEvent=null}var b=this,c=c||{VERSION:"2.4.2",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,blendModes:{NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{}};if(Math.trunc||(Math.trunc=function(a){return 0>a?Math.ceil(a):Math.floor(a)}),Function.prototype.bind||(Function.prototype.bind=function(){var a=Array.prototype.slice;return function(b){function c(){var f=e.concat(a.call(arguments));d.apply(this instanceof c?this:b,f)}var d=this,e=a.call(arguments,1);if("function"!=typeof d)throw new TypeError;return c.prototype=function f(a){return a&&(f.prototype=a),this instanceof f?void 0:new f}(d.prototype),c}}()),Array.isArray||(Array.isArray=function(a){return"[object Array]"==Object.prototype.toString.call(a)}),Array.prototype.forEach||(Array.prototype.forEach=function(a){"use strict";if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=arguments.length>=2?arguments[1]:void 0,e=0;c>e;e++)e in b&&a.call(d,b[e],e,b)}),"function"!=typeof window.Uint32Array&&"object"!=typeof window.Uint32Array){var d=function(a){var b=new Array;window[a]=function(a){if("number"==typeof a){Array.call(this,a),this.length=a;for(var b=0;b<this.length;b++)this[b]=0}else{Array.call(this,a.length),this.length=a.length;for(var b=0;b<this.length;b++)this[b]=a[b]}},window[a].prototype=b,window[a].constructor=window[a]};d("Uint32Array"),d("Int16Array")}window.console||(window.console={},window.console.log=window.console.assert=function(){},window.console.warn=window.console.assert=function(){}),c.Utils={getProperty:function(a,b){for(var c=b.split("."),d=c.pop(),e=c.length,f=1,g=c[0];e>f&&(a=a[g]);)g=c[f],f++;return a?a[d]:null},setProperty:function(a,b,c){for(var d=b.split("."),e=d.pop(),f=d.length,g=1,h=d[0];f>g&&(a=a[h]);)h=d[g],g++;return a&&(a[e]=c),a},chanceRoll:function(a){return void 0===a&&(a=50),a>0&&100*Math.random()<=a},randomChoice:function(a,b){return Math.random()<.5?a:b},parseDimension:function(a,b){var c=0,d=0;return"string"==typeof a?"%"===a.substr(-1)?(c=parseInt(a,10)/100,d=0===b?window.innerWidth*c:window.innerHeight*c):d=parseInt(a,10):d=a,d},pad:function(a,b,c,d){if(void 0===b)var b=0;if(void 0===c)var c=" ";if(void 0===d)var d=3;var e=0;if(b+1>=a.length)switch(d){case 1:a=new Array(b+1-a.length).join(c)+a;break;case 3:var f=Math.ceil((e=b-a.length)/2),g=e-f;a=new Array(g+1).join(c)+a+new Array(f+1).join(c);break;default:a+=new Array(b+1-a.length).join(c)}return a},isPlainObject:function(a){if("object"!=typeof a||a.nodeType||a===a.window)return!1;try{if(a.constructor&&!{}.hasOwnProperty.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},extend:function(){var a,b,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;for("boolean"==typeof h&&(k=h,h=arguments[1]||{},i=2),j===i&&(h=this,--i);j>i;i++)if(null!=(a=arguments[i]))for(b in a)d=h[b],e=a[b],h!==e&&(k&&e&&(c.Utils.isPlainObject(e)||(f=Array.isArray(e)))?(f?(f=!1,g=d&&Array.isArray(d)?d:[]):g=d&&c.Utils.isPlainObject(d)?d:{},h[b]=c.Utils.extend(k,g,e)):void 0!==e&&(h[b]=e));return h},mixinPrototype:function(a,b,c){void 0===c&&(c=!1);for(var d=Object.keys(b),e=0;e<d.length;e++){var f=d[e],g=b[f];!c&&f in a||(!g||"function"!=typeof g.get&&"function"!=typeof g.set?a[f]=g:"function"==typeof g.clone?a[f]=g.clone():Object.defineProperty(a,f,g))}},mixin:function(a,b){if(!a||"object"!=typeof a)return b;for(var d in a){var e=a[d];if(!e.childNodes&&!e.cloneNode){var f=typeof a[d];b[d]=a[d]&&"object"===f?typeof b[d]===f?c.Utils.mixin(a[d],b[d]):c.Utils.mixin(a[d],new e.constructor):a[d]
+}}return b}},c.Circle=function(a,b,d){a=a||0,b=b||0,d=d||0,this.x=a,this.y=b,this._diameter=d,this._radius=0,d>0&&(this._radius=.5*d),this.type=c.CIRCLE},c.Circle.prototype={circumference:function(){return 2*Math.PI*this._radius},random:function(a){void 0===a&&(a=new c.Point);var b=2*Math.PI*Math.random(),d=Math.random()+Math.random(),e=d>1?2-d:d,f=e*Math.cos(b),g=e*Math.sin(b);return a.x=this.x+f*this.radius,a.y=this.y+g*this.radius,a},getBounds:function(){return new c.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(a,b,c){return this.x=a,this.y=b,this._diameter=c,this._radius=.5*c,this},copyFrom:function(a){return this.setTo(a.x,a.y,a.diameter)},copyTo:function(a){return a.x=this.x,a.y=this.y,a.diameter=this._diameter,a},distance:function(a,b){var d=c.Math.distance(this.x,this.y,a.x,a.y);return b?Math.round(d):d},clone:function(a){return void 0===a||null===a?a=new c.Circle(this.x,this.y,this.diameter):a.setTo(this.x,this.y,this.diameter),a},contains:function(a,b){return c.Circle.contains(this,a,b)},circumferencePoint:function(a,b,d){return c.Circle.circumferencePoint(this,a,b,d)},offset:function(a,b){return this.x+=a,this.y+=b,this},offsetPoint:function(a){return this.offset(a.x,a.y)},toString:function(){return"[{Phaser.Circle (x="+this.x+" y="+this.y+" diameter="+this.diameter+" radius="+this.radius+")}]"}},c.Circle.prototype.constructor=c.Circle,Object.defineProperty(c.Circle.prototype,"diameter",{get:function(){return this._diameter},set:function(a){a>0&&(this._diameter=a,this._radius=.5*a)}}),Object.defineProperty(c.Circle.prototype,"radius",{get:function(){return this._radius},set:function(a){a>0&&(this._radius=a,this._diameter=2*a)}}),Object.defineProperty(c.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(a){a>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-a}}),Object.defineProperty(c.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(a){a<this.x?(this._radius=0,this._diameter=0):this.radius=a-this.x}}),Object.defineProperty(c.Circle.prototype,"top",{get:function(){return this.y-this._radius},set:function(a){a>this.y?(this._radius=0,this._diameter=0):this.radius=this.y-a}}),Object.defineProperty(c.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(a){a<this.y?(this._radius=0,this._diameter=0):this.radius=a-this.y}}),Object.defineProperty(c.Circle.prototype,"area",{get:function(){return this._radius>0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(c.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(a){a===!0&&this.setTo(0,0,0)}}),c.Circle.contains=function(a,b,c){if(a.radius>0&&b>=a.left&&b<=a.right&&c>=a.top&&c<=a.bottom){var d=(a.x-b)*(a.x-b),e=(a.y-c)*(a.y-c);return d+e<=a.radius*a.radius}return!1},c.Circle.equals=function(a,b){return a.x==b.x&&a.y==b.y&&a.diameter==b.diameter},c.Circle.intersects=function(a,b){return c.Math.distance(a.x,a.y,b.x,b.y)<=a.radius+b.radius},c.Circle.circumferencePoint=function(a,b,d,e){return void 0===d&&(d=!1),void 0===e&&(e=new c.Point),d===!0&&(b=c.Math.degToRad(b)),e.x=a.x+a.radius*Math.cos(b),e.y=a.y+a.radius*Math.sin(b),e},c.Circle.intersectsRectangle=function(a,b){var c=Math.abs(a.x-b.x-b.halfWidth),d=b.halfWidth+a.radius;if(c>d)return!1;var e=Math.abs(a.y-b.y-b.halfHeight),f=b.halfHeight+a.radius;if(e>f)return!1;if(c<=b.halfWidth||e<=b.halfHeight)return!0;var g=c-b.halfWidth,h=e-b.halfHeight,i=g*g,j=h*h,k=a.radius*a.radius;return k>=i+j},PIXI.Circle=c.Circle,c.Ellipse=function(a,b,d,e){a=a||0,b=b||0,d=d||0,e=e||0,this.x=a,this.y=b,this.width=d,this.height=e,this.type=c.ELLIPSE},c.Ellipse.prototype={setTo:function(a,b,c,d){return this.x=a,this.y=b,this.width=c,this.height=d,this},getBounds:function(){return new c.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(a){return this.setTo(a.x,a.y,a.width,a.height)},copyTo:function(a){return a.x=this.x,a.y=this.y,a.width=this.width,a.height=this.height,a},clone:function(a){return void 0===a||null===a?a=new c.Ellipse(this.x,this.y,this.width,this.height):a.setTo(this.x,this.y,this.width,this.height),a},contains:function(a,b){return c.Ellipse.contains(this,a,b)},random:function(a){void 0===a&&(a=new c.Point);var b=Math.random()*Math.PI*2,d=Math.random();return a.x=Math.sqrt(d)*Math.cos(b),a.y=Math.sqrt(d)*Math.sin(b),a.x=this.x+a.x*this.width/2,a.y=this.y+a.y*this.height/2,a},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},c.Ellipse.prototype.constructor=c.Ellipse,Object.defineProperty(c.Ellipse.prototype,"left",{get:function(){return this.x},set:function(a){this.x=a}}),Object.defineProperty(c.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(a){this.width=a<this.x?0:a-this.x}}),Object.defineProperty(c.Ellipse.prototype,"top",{get:function(){return this.y},set:function(a){this.y=a}}),Object.defineProperty(c.Ellipse.prototype,"bottom",{get:function(){return this.y+this.height},set:function(a){this.height=a<this.y?0:a-this.y}}),Object.defineProperty(c.Ellipse.prototype,"empty",{get:function(){return 0===this.width||0===this.height},set:function(a){a===!0&&this.setTo(0,0,0,0)}}),c.Ellipse.contains=function(a,b,c){if(a.width<=0||a.height<=0)return!1;var d=(b-a.x)/a.width-.5,e=(c-a.y)/a.height-.5;return d*=d,e*=e,.25>d+e},PIXI.Ellipse=c.Ellipse,c.Line=function(a,b,d,e){a=a||0,b=b||0,d=d||0,e=e||0,this.start=new c.Point(a,b),this.end=new c.Point(d,e),this.type=c.LINE},c.Line.prototype={setTo:function(a,b,c,d){return this.start.setTo(a,b),this.end.setTo(c,d),this},fromSprite:function(a,b,c){return void 0===c&&(c=!1),c?this.setTo(a.center.x,a.center.y,b.center.x,b.center.y):this.setTo(a.x,a.y,b.x,b.y)},fromAngle:function(a,b,c,d){return this.start.setTo(a,b),this.end.setTo(a+Math.cos(c)*d,b+Math.sin(c)*d),this},rotate:function(a,b){var c=this.start.x,d=this.start.y;return this.start.rotate(this.end.x,this.end.y,a,b,this.length),this.end.rotate(c,d,a,b,this.length),this},intersects:function(a,b,d){return c.Line.intersectsPoints(this.start,this.end,a.start,a.end,b,d)},reflect:function(a){return c.Line.reflect(this,a)},pointOnLine:function(a,b){return(a-this.start.x)*(this.end.y-this.start.y)===(this.end.x-this.start.x)*(b-this.start.y)},pointOnSegment:function(a,b){var c=Math.min(this.start.x,this.end.x),d=Math.max(this.start.x,this.end.x),e=Math.min(this.start.y,this.end.y),f=Math.max(this.start.y,this.end.y);return this.pointOnLine(a,b)&&a>=c&&d>=a&&b>=e&&f>=b},random:function(a){void 0===a&&(a=new c.Point);var b=Math.random();return a.x=this.start.x+b*(this.end.x-this.start.x),a.y=this.start.y+b*(this.end.y-this.start.y),a},coordinatesOnLine:function(a,b){void 0===a&&(a=1),void 0===b&&(b=[]);var c=Math.round(this.start.x),d=Math.round(this.start.y),e=Math.round(this.end.x),f=Math.round(this.end.y),g=Math.abs(e-c),h=Math.abs(f-d),i=e>c?1:-1,j=f>d?1:-1,k=g-h;b.push([c,d]);for(var l=1;c!=e||d!=f;){var m=k<<1;m>-h&&(k-=h,c+=i),g>m&&(k+=g,d+=j),l%a===0&&b.push([c,d]),l++}return b},clone:function(a){return void 0===a||null===a?a=new c.Line(this.start.x,this.start.y,this.end.x,this.end.y):a.setTo(this.start.x,this.start.y,this.end.x,this.end.y),a}},Object.defineProperty(c.Line.prototype,"length",{get:function(){return Math.sqrt((this.end.x-this.start.x)*(this.end.x-this.start.x)+(this.end.y-this.start.y)*(this.end.y-this.start.y))}}),Object.defineProperty(c.Line.prototype,"angle",{get:function(){return Math.atan2(this.end.y-this.start.y,this.end.x-this.start.x)}}),Object.defineProperty(c.Line.prototype,"slope",{get:function(){return(this.end.y-this.start.y)/(this.end.x-this.start.x)}}),Object.defineProperty(c.Line.prototype,"perpSlope",{get:function(){return-((this.end.x-this.start.x)/(this.end.y-this.start.y))}}),Object.defineProperty(c.Line.prototype,"x",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(c.Line.prototype,"y",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(c.Line.prototype,"left",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(c.Line.prototype,"right",{get:function(){return Math.max(this.start.x,this.end.x)}}),Object.defineProperty(c.Line.prototype,"top",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(c.Line.prototype,"bottom",{get:function(){return Math.max(this.start.y,this.end.y)}}),Object.defineProperty(c.Line.prototype,"width",{get:function(){return Math.abs(this.start.x-this.end.x)}}),Object.defineProperty(c.Line.prototype,"height",{get:function(){return Math.abs(this.start.y-this.end.y)}}),Object.defineProperty(c.Line.prototype,"normalX",{get:function(){return Math.cos(this.angle-1.5707963267948966)}}),Object.defineProperty(c.Line.prototype,"normalY",{get:function(){return Math.sin(this.angle-1.5707963267948966)}}),Object.defineProperty(c.Line.prototype,"normalAngle",{get:function(){return c.Math.wrap(this.angle-1.5707963267948966,-Math.PI,Math.PI)}}),c.Line.intersectsPoints=function(a,b,d,e,f,g){void 0===f&&(f=!0),void 0===g&&(g=new c.Point);var h=b.y-a.y,i=e.y-d.y,j=a.x-b.x,k=d.x-e.x,l=b.x*a.y-a.x*b.y,m=e.x*d.y-d.x*e.y,n=h*k-i*j;if(0===n)return null;if(g.x=(j*m-k*l)/n,g.y=(i*l-h*m)/n,f){var o=(e.y-d.y)*(b.x-a.x)-(e.x-d.x)*(b.y-a.y),p=((e.x-d.x)*(a.y-d.y)-(e.y-d.y)*(a.x-d.x))/o,q=((b.x-a.x)*(a.y-d.y)-(b.y-a.y)*(a.x-d.x))/o;return p>=0&&1>=p&&q>=0&&1>=q?g:null}return g},c.Line.intersects=function(a,b,d,e){return c.Line.intersectsPoints(a.start,a.end,b.start,b.end,d,e)},c.Line.reflect=function(a,b){return 2*b.normalAngle-3.141592653589793-a.angle},c.Matrix=function(a,b,d,e,f,g){a=a||1,b=b||0,d=d||0,e=e||1,f=f||0,g=g||0,this.a=a,this.b=b,this.c=d,this.d=e,this.tx=f,this.ty=g,this.type=c.MATRIX},c.Matrix.prototype={fromArray:function(a){return this.setTo(a[0],a[1],a[3],a[4],a[2],a[5])},setTo:function(a,b,c,d,e,f){return this.a=a,this.b=b,this.c=c,this.d=d,this.tx=e,this.ty=f,this},clone:function(a){return void 0===a||null===a?a=new c.Matrix(this.a,this.b,this.c,this.d,this.tx,this.ty):(a.a=this.a,a.b=this.b,a.c=this.c,a.d=this.d,a.tx=this.tx,a.ty=this.ty),a},copyTo:function(a){return a.copyFrom(this),a},copyFrom:function(a){return this.a=a.a,this.b=a.b,this.c=a.c,this.d=a.d,this.tx=a.tx,this.ty=a.ty,this},toArray:function(a,b){return void 0===b&&(b=new PIXI.Float32Array(9)),a?(b[0]=this.a,b[1]=this.b,b[2]=0,b[3]=this.c,b[4]=this.d,b[5]=0,b[6]=this.tx,b[7]=this.ty,b[8]=1):(b[0]=this.a,b[1]=this.c,b[2]=this.tx,b[3]=this.b,b[4]=this.d,b[5]=this.ty,b[6]=0,b[7]=0,b[8]=1),b},apply:function(a,b){return void 0===b&&(b=new c.Point),b.x=this.a*a.x+this.c*a.y+this.tx,b.y=this.b*a.x+this.d*a.y+this.ty,b},applyInverse:function(a,b){void 0===b&&(b=new c.Point);var d=1/(this.a*this.d+this.c*-this.b),e=a.x,f=a.y;return b.x=this.d*d*e+-this.c*d*f+(this.ty*this.c-this.tx*this.d)*d,b.y=this.a*d*f+-this.b*d*e+(-this.ty*this.a+this.tx*this.b)*d,b},translate:function(a,b){return this.tx+=a,this.ty+=b,this},scale:function(a,b){return this.a*=a,this.d*=b,this.c*=a,this.b*=b,this.tx*=a,this.ty*=b,this},rotate:function(a){var b=Math.cos(a),c=Math.sin(a),d=this.a,e=this.c,f=this.tx;return this.a=d*b-this.b*c,this.b=d*c+this.b*b,this.c=e*b-this.d*c,this.d=e*c+this.d*b,this.tx=f*b-this.ty*c,this.ty=f*c+this.ty*b,this},append:function(a){var b=this.a,c=this.b,d=this.c,e=this.d;return this.a=a.a*b+a.b*d,this.b=a.a*c+a.b*e,this.c=a.c*b+a.d*d,this.d=a.c*c+a.d*e,this.tx=a.tx*b+a.ty*d+this.tx,this.ty=a.tx*c+a.ty*e+this.ty,this},identity:function(){return this.setTo(1,0,0,1,0,0)}},c.identityMatrix=new c.Matrix,PIXI.Matrix=c.Matrix,PIXI.identityMatrix=c.identityMatrix,c.Point=function(a,b){a=a||0,b=b||0,this.x=a,this.y=b,this.type=c.POINT},c.Point.prototype={copyFrom:function(a){return this.setTo(a.x,a.y)},invert:function(){return this.setTo(this.y,this.x)},setTo:function(a,b){return this.x=a||0,this.y=b||(0!==b?this.x:0),this},set:function(a,b){return this.x=a||0,this.y=b||(0!==b?this.x:0),this},add:function(a,b){return this.x+=a,this.y+=b,this},subtract:function(a,b){return this.x-=a,this.y-=b,this},multiply:function(a,b){return this.x*=a,this.y*=b,this},divide:function(a,b){return this.x/=a,this.y/=b,this},clampX:function(a,b){return this.x=c.Math.clamp(this.x,a,b),this},clampY:function(a,b){return this.y=c.Math.clamp(this.y,a,b),this},clamp:function(a,b){return this.x=c.Math.clamp(this.x,a,b),this.y=c.Math.clamp(this.y,a,b),this},clone:function(a){return void 0===a||null===a?a=new c.Point(this.x,this.y):a.setTo(this.x,this.y),a},copyTo:function(a){return a.x=this.x,a.y=this.y,a},distance:function(a,b){return c.Point.distance(this,a,b)},equals:function(a){return a.x===this.x&&a.y===this.y},angle:function(a,b){return void 0===b&&(b=!1),b?c.Math.radToDeg(Math.atan2(a.y-this.y,a.x-this.x)):Math.atan2(a.y-this.y,a.x-this.x)},rotate:function(a,b,d,e,f){return c.Point.rotate(this,a,b,d,e,f)},getMagnitude:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},getMagnitudeSq:function(){return this.x*this.x+this.y*this.y},setMagnitude:function(a){return this.normalize().multiply(a,a)},normalize:function(){if(!this.isZero()){var a=this.getMagnitude();this.x/=a,this.y/=a}return this},isZero:function(){return 0===this.x&&0===this.y},dot:function(a){return this.x*a.x+this.y*a.y},cross:function(a){return this.x*a.y-this.y*a.x},perp:function(){return this.setTo(-this.y,this.x)},rperp:function(){return this.setTo(this.y,-this.x)},normalRightHand:function(){return this.setTo(-1*this.y,this.x)},floor:function(){return this.setTo(Math.floor(this.x),Math.floor(this.y))},ceil:function(){return this.setTo(Math.ceil(this.x),Math.ceil(this.y))},toString:function(){return"[{Point (x="+this.x+" y="+this.y+")}]"}},c.Point.prototype.constructor=c.Point,c.Point.add=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x+b.x,d.y=a.y+b.y,d},c.Point.subtract=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x-b.x,d.y=a.y-b.y,d},c.Point.multiply=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x*b.x,d.y=a.y*b.y,d},c.Point.divide=function(a,b,d){return void 0===d&&(d=new c.Point),d.x=a.x/b.x,d.y=a.y/b.y,d},c.Point.equals=function(a,b){return a.x===b.x&&a.y===b.y},c.Point.angle=function(a,b){return Math.atan2(a.y-b.y,a.x-b.x)},c.Point.negative=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(-a.x,-a.y)},c.Point.multiplyAdd=function(a,b,d,e){return void 0===e&&(e=new c.Point),e.setTo(a.x+b.x*d,a.y+b.y*d)},c.Point.interpolate=function(a,b,d,e){return void 0===e&&(e=new c.Point),e.setTo(a.x+(b.x-a.x)*d,a.y+(b.y-a.y)*d)},c.Point.perp=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(-a.y,a.x)},c.Point.rperp=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(a.y,-a.x)},c.Point.distance=function(a,b,d){var e=c.Math.distance(a.x,a.y,b.x,b.y);return d?Math.round(e):e},c.Point.project=function(a,b,d){void 0===d&&(d=new c.Point);var e=a.dot(b)/b.getMagnitudeSq();return 0!==e&&d.setTo(e*b.x,e*b.y),d},c.Point.projectUnit=function(a,b,d){void 0===d&&(d=new c.Point);var e=a.dot(b);return 0!==e&&d.setTo(e*b.x,e*b.y),d},c.Point.normalRightHand=function(a,b){return void 0===b&&(b=new c.Point),b.setTo(-1*a.y,a.x)},c.Point.normalize=function(a,b){void 0===b&&(b=new c.Point);var d=a.getMagnitude();return 0!==d&&b.setTo(a.x/d,a.y/d),b},c.Point.rotate=function(a,b,d,e,f,g){void 0===f&&(f=!1),void 0===g&&(g=null),f&&(e=c.Math.degToRad(e)),null===g&&(g=Math.sqrt((b-a.x)*(b-a.x)+(d-a.y)*(d-a.y)));var h=e+Math.atan2(a.y-d,a.x-b);return a.x=b+g*Math.cos(h),a.y=d+g*Math.sin(h),a},c.Point.centroid=function(a,b){if(void 0===b&&(b=new c.Point),"[object Array]"!==Object.prototype.toString.call(a))throw new Error("Phaser.Point. Parameter 'points' must be an array");var d=a.length;if(1>d)throw new Error("Phaser.Point. Parameter 'points' array must not be empty");if(1===d)return b.copyFrom(a[0]),b;for(var e=0;d>e;e++)c.Point.add(b,a[e],b);return b.divide(d,d),b},c.Point.parse=function(a,b,d){b=b||"x",d=d||"y";var e=new c.Point;return a[b]&&(e.x=parseInt(a[b],10)),a[d]&&(e.y=parseInt(a[d],10)),e},PIXI.Point=c.Point,c.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.type=c.POLYGON},c.Polygon.prototype={toNumberArray:function(a){void 0===a&&(a=[]);for(var b=0;b<this._points.length;b++)"number"==typeof this._points[b]?(a.push(this._points[b]),a.push(this._points[b+1]),b++):(a.push(this._points[b].x),a.push(this._points[b].y));return a},flatten:function(){return this._points=this.toNumberArray(),this},clone:function(a){var b=this._points.slice();return void 0===a||null===a?a=new c.Polygon(b):a.setTo(b),a},contains:function(a,b){for(var c=this._points.length,d=!1,e=-1,f=c-1;++e<c;f=e){var g=this._points[e].x,h=this._points[e].y,i=this._points[f].x,j=this._points[f].y;(b>=h&&j>b||b>=j&&h>b)&&(i-g)*(b-h)/(j-h)+g>a&&(d=!d)}return d},setTo:function(a){if(this.area=0,this._points=[],arguments.length>0){Array.isArray(a)||(a=Array.prototype.slice.call(arguments));for(var b=Number.MAX_VALUE,c=0,d=a.length;d>c;c++){if("number"==typeof a[c]){var e=new PIXI.Point(a[c],a[c+1]);c++}else var e=new PIXI.Point(a[c].x,a[c].y);this._points.push(e),e.y<b&&(b=e.y)}this.calculateArea(b)}return this},calculateArea:function(a){for(var b,c,d,e,f=0,g=this._points.length;g>f;f++)b=this._points[f],c=f===g-1?this._points[0]:this._points[f+1],d=(b.y-a+(c.y-a))/2,e=b.x-c.x,this.area+=d*e;return this.area}},c.Polygon.prototype.constructor=c.Polygon,Object.defineProperty(c.Polygon.prototype,"points",{get:function(){return this._points},set:function(a){null!=a?this.setTo(a):this.setTo()}}),PIXI.Polygon=c.Polygon,c.Rectangle=function(a,b,d,e){a=a||0,b=b||0,d=d||0,e=e||0,this.x=a,this.y=b,this.width=d,this.height=e,this.type=c.RECTANGLE},c.Rectangle.prototype={offset:function(a,b){return this.x+=a,this.y+=b,this},offsetPoint:function(a){return this.offset(a.x,a.y)},setTo:function(a,b,c,d){return this.x=a,this.y=b,this.width=c,this.height=d,this},scale:function(a,b){return void 0===b&&(b=a),this.width*=a,this.height*=b,this},centerOn:function(a,b){return this.centerX=a,this.centerY=b,this},floor:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y)},floorAll:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.width=Math.floor(this.width),this.height=Math.floor(this.height)},ceil:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y)},ceilAll:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.width=Math.ceil(this.width),this.height=Math.ceil(this.height)},copyFrom:function(a){return this.setTo(a.x,a.y,a.width,a.height)},copyTo:function(a){return a.x=this.x,a.y=this.y,a.width=this.width,a.height=this.height,a},inflate:function(a,b){return c.Rectangle.inflate(this,a,b)},size:function(a){return c.Rectangle.size(this,a)},resize:function(a,b){return this.width=a,this.height=b,this},clone:function(a){return c.Rectangle.clone(this,a)},contains:function(a,b){return c.Rectangle.contains(this,a,b)},containsRect:function(a){return c.Rectangle.containsRect(a,this)},equals:function(a){return c.Rectangle.equals(this,a)},intersection:function(a,b){return c.Rectangle.intersection(this,a,b)},intersects:function(a){return c.Rectangle.intersects(this,a)},intersectsRaw:function(a,b,d,e,f){return c.Rectangle.intersectsRaw(this,a,b,d,e,f)},union:function(a,b){return c.Rectangle.union(this,a,b)},random:function(a){return void 0===a&&(a=new c.Point),a.x=this.randomX,a.y=this.randomY,a},toString:function(){return"[{Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+" empty="+this.empty+")}]"}},Object.defineProperty(c.Rectangle.prototype,"halfWidth",{get:function(){return Math.round(this.width/2)}}),Object.defineProperty(c.Rectangle.prototype,"halfHeight",{get:function(){return Math.round(this.height/2)}}),Object.defineProperty(c.Rectangle.prototype,"bottom",{get:function(){return this.y+this.height},set:function(a){this.height=a<=this.y?0:a-this.y}}),Object.defineProperty(c.Rectangle.prototype,"bottomLeft",{get:function(){return new c.Point(this.x,this.bottom)},set:function(a){this.x=a.x,this.bottom=a.y}}),Object.defineProperty(c.Rectangle.prototype,"bottomRight",{get:function(){return new c.Point(this.right,this.bottom)},set:function(a){this.right=a.x,this.bottom=a.y}}),Object.defineProperty(c.Rectangle.prototype,"left",{get:function(){return this.x},set:function(a){this.width=a>=this.right?0:this.right-a,this.x=a}}),Object.defineProperty(c.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(a){this.width=a<=this.x?0:a-this.x}}),Object.defineProperty(c.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(c.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(c.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(a){this.x=a-this.halfWidth}}),Object.defineProperty(c.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(a){this.y=a-this.halfHeight}}),Object.defineProperty(c.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(c.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(c.Rectangle.prototype,"top",{get:function(){return this.y},set:function(a){a>=this.bottom?(this.height=0,this.y=a):this.height=this.bottom-a}}),Object.defineProperty(c.Rectangle.prototype,"topLeft",{get:function(){return new c.Point(this.x,this.y)},set:function(a){this.x=a.x,this.y=a.y}}),Object.defineProperty(c.Rectangle.prototype,"topRight",{get:function(){return new c.Point(this.x+this.width,this.y)},set:function(a){this.right=a.x,this.y=a.y}}),Object.defineProperty(c.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(a){a===!0&&this.setTo(0,0,0,0)}}),c.Rectangle.prototype.constructor=c.Rectangle,c.Rectangle.inflate=function(a,b,c){return a.x-=b,a.width+=2*b,a.y-=c,a.height+=2*c,a},c.Rectangle.inflatePoint=function(a,b){return c.Rectangle.inflate(a,b.x,b.y)},c.Rectangle.size=function(a,b){return void 0===b||null===b?b=new c.Point(a.width,a.height):b.setTo(a.width,a.height),b},c.Rectangle.clone=function(a,b){return void 0===b||null===b?b=new c.Rectangle(a.x,a.y,a.width,a.height):b.setTo(a.x,a.y,a.width,a.height),b},c.Rectangle.contains=function(a,b,c){return a.width<=0||a.height<=0?!1:b>=a.x&&b<a.right&&c>=a.y&&c<a.bottom},c.Rectangle.containsRaw=function(a,b,c,d,e,f){return e>=a&&a+c>e&&f>=b&&b+d>f},c.Rectangle.containsPoint=function(a,b){return c.Rectangle.contains(a,b.x,b.y)},c.Rectangle.containsRect=function(a,b){return a.volume>b.volume?!1:a.x>=b.x&&a.y>=b.y&&a.right<b.right&&a.bottom<b.bottom},c.Rectangle.equals=function(a,b){return a.x==b.x&&a.y==b.y&&a.width==b.width&&a.height==b.height},c.Rectangle.sameDimensions=function(a,b){return a.width===b.width&&a.height===b.height},c.Rectangle.intersection=function(a,b,d){return void 0===d&&(d=new c.Rectangle),c.Rectangle.intersects(a,b)&&(d.x=Math.max(a.x,b.x),d.y=Math.max(a.y,b.y),d.width=Math.min(a.right,b.right)-d.x,d.height=Math.min(a.bottom,b.bottom)-d.y),d},c.Rectangle.intersects=function(a,b){return a.width<=0||a.height<=0||b.width<=0||b.height<=0?!1:!(a.right<b.x||a.bottom<b.y||a.x>b.right||a.y>b.bottom)},c.Rectangle.intersectsRaw=function(a,b,c,d,e,f){return void 0===f&&(f=0),!(b>a.right+f||c<a.left-f||d>a.bottom+f||e<a.top-f)},c.Rectangle.union=function(a,b,d){return void 0===d&&(d=new c.Rectangle),d.setTo(Math.min(a.x,b.x),Math.min(a.y,b.y),Math.max(a.right,b.right)-Math.min(a.left,b.left),Math.max(a.bottom,b.bottom)-Math.min(a.top,b.top))},c.Rectangle.aabb=function(a,b){void 0===b&&(b=new c.Rectangle);var d=Number.MIN_VALUE,e=Number.MAX_VALUE,f=Number.MIN_VALUE,g=Number.MAX_VALUE;return a.forEach(function(a){a.x>d&&(d=a.x),a.x<e&&(e=a.x),a.y>f&&(f=a.y),a.y<g&&(g=a.y)}),b.setTo(e,g,d-e,f-g),b},PIXI.Rectangle=c.Rectangle,PIXI.EmptyRectangle=new c.Rectangle(0,0,0,0),c.RoundedRectangle=function(a,b,d,e,f){void 0===a&&(a=0),void 0===b&&(b=0),void 0===d&&(d=0),void 0===e&&(e=0),void 0===f&&(f=20),this.x=a,this.y=b,this.width=d,this.height=e,this.radius=f||20,this.type=c.ROUNDEDRECTANGLE},c.RoundedRectangle.prototype={clone:function(){return new c.RoundedRectangle(this.x,this.y,this.width,this.height,this.radius)},contains:function(a,b){if(this.width<=0||this.height<=0)return!1;var c=this.x;if(a>=c&&a<=c+this.width){var d=this.y;if(b>=d&&b<=d+this.height)return!0}return!1}},c.RoundedRectangle.prototype.constructor=c.RoundedRectangle,PIXI.RoundedRectangle=c.RoundedRectangle,c.Camera=function(a,b,d,e,f,g){this.game=a,this.world=a.world,this.id=0,this.view=new c.Rectangle(d,e,f,g),this.bounds=new c.Rectangle(d,e,f,g),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this._targetPosition=new c.Point,this._edge=0,this._position=new c.Point},c.Camera.FOLLOW_LOCKON=0,c.Camera.FOLLOW_PLATFORMER=1,c.Camera.FOLLOW_TOPDOWN=2,c.Camera.FOLLOW_TOPDOWN_TIGHT=3,c.Camera.prototype={preUpdate:function(){this.totalInView=0},follow:function(a,b){void 0===b&&(b=c.Camera.FOLLOW_LOCKON),this.target=a;var d;switch(b){case c.Camera.FOLLOW_PLATFORMER:var e=this.width/8,f=this.height/3;this.deadzone=new c.Rectangle((this.width-e)/2,(this.height-f)/2-.25*f,e,f);break;case c.Camera.FOLLOW_TOPDOWN:d=Math.max(this.width,this.height)/4,this.deadzone=new c.Rectangle((this.width-d)/2,(this.height-d)/2,d,d);break;case c.Camera.FOLLOW_TOPDOWN_TIGHT:d=Math.max(this.width,this.height)/8,this.deadzone=new c.Rectangle((this.width-d)/2,(this.height-d)/2,d,d);break;case c.Camera.FOLLOW_LOCKON:this.deadzone=null;break;default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(a){this.setPosition(Math.round(a.x-this.view.halfWidth),Math.round(a.y-this.view.halfHeight))},focusOnXY:function(a,b){this.setPosition(Math.round(a-this.view.halfWidth),Math.round(b-this.view.halfHeight))},update:function(){this.target&&this.updateTarget(),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateTarget:function(){this._targetPosition.copyFrom(this.target),this.target.parent&&this._targetPosition.multiply(this.target.parent.worldTransform.a,this.target.parent.worldTransform.d),this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edge<this.deadzone.left?this.view.x=this._targetPosition.x-this.deadzone.left:this._edge>this.deadzone.right&&(this.view.x=this._targetPosition.x-this.deadzone.right),this._edge=this._targetPosition.y-this.view.y,this._edge<this.deadzone.top?this.view.y=this._targetPosition.y-this.deadzone.top:this._edge>this.deadzone.bottom&&(this.view.y=this._targetPosition.y-this.deadzone.bottom)):(this.view.x=this._targetPosition.x-this.view.halfWidth,this.view.y=this._targetPosition.y-this.view.halfHeight)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1,this.view.x<=this.bounds.x&&(this.atLimit.x=!0,this.view.x=this.bounds.x),this.view.right>=this.bounds.right&&(this.atLimit.x=!0,this.view.x=this.bounds.right-this.width),this.view.y<=this.bounds.top&&(this.atLimit.y=!0,this.view.y=this.bounds.top),this.view.bottom>=this.bounds.bottom&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom-this.height)},setPosition:function(a,b){this.view.x=a,this.view.y=b,this.bounds&&this.checkBounds()},setSize:function(a,b){this.view.width=a,this.view.height=b},reset:function(){this.target=null,this.view.x=0,this.view.y=0}},c.Camera.prototype.constructor=c.Camera,Object.defineProperty(c.Camera.prototype,"x",{get:function(){return this.view.x},set:function(a){this.view.x=a,this.bounds&&this.checkBounds()}}),Object.defineProperty(c.Camera.prototype,"y",{get:function(){return this.view.y},set:function(a){this.view.y=a,this.bounds&&this.checkBounds()}}),Object.defineProperty(c.Camera.prototype,"position",{get:function(){return this._position.set(this.view.centerX,this.view.centerY),this._position},set:function(a){"undefined"!=typeof a.x&&(this.view.x=a.x),"undefined"!=typeof a.y&&(this.view.y=a.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(c.Camera.prototype,"width",{get:function(){return this.view.width},set:function(a){this.view.width=a}}),Object.defineProperty(c.Camera.prototype,"height",{get:function(){return this.view.height},set:function(a){this.view.height=a}}),c.Create=function(a){this.game=a,this.bmd=a.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context,this.palettes=[{0:"#000",1:"#9D9D9D",2:"#FFF",3:"#BE2633",4:"#E06F8B",5:"#493C2B",6:"#A46422",7:"#EB8931",8:"#F7E26B",9:"#2F484E",A:"#44891A",B:"#A3CE27",C:"#1B2632",D:"#005784",E:"#31A2F2",F:"#B2DCEF"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"},{0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"},{0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}]},c.Create.PALETTE_ARNE=0,c.Create.PALETTE_JMP=1,c.Create.PALETTE_CGA=2,c.Create.PALETTE_C64=3,c.Create.PALETTE_JAPANESE_MACHINE=4,c.Create.prototype={texture:function(a,b,c,d,e){void 0===c&&(c=8),void 0===d&&(d=c),void 0===e&&(e=0);var f=b[0].length*c,g=b.length*d;this.bmd.resize(f,g),this.bmd.clear();for(var h=0;h<b.length;h++)for(var i=b[h],j=0;j<i.length;j++){var k=i[j];"."!==k&&" "!==k&&(this.ctx.fillStyle=this.palettes[e][k],this.ctx.fillRect(j*c,h*d,c,d))}return this.bmd.generateTexture(a)},grid:function(a,b,c,d,e,f){this.bmd.resize(b,c),this.ctx.fillStyle=f;for(var g=0;c>g;g+=e)this.ctx.fillRect(0,g,b,1);for(var h=0;b>h;h+=d)this.ctx.fillRect(h,0,1,c);return this.bmd.generateTexture(a)}},c.Create.prototype.constructor=c.Create,c.State=function(){this.game=null,this.key="",this.add=null,this.make=null,this.camera=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.sound=null,this.scale=null,this.stage=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},c.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},c.State.prototype.constructor=c.State,c.StateManager=function(a,b){this.game=a,this.states={},this._pendingState=null,"undefined"!=typeof b&&null!==b&&(this._pendingState=b),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new c.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},c.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(a,b,d){void 0===d&&(d=!1);
+var e;return b instanceof c.State?e=b:"object"==typeof b?(e=b,e.game=this.game):"function"==typeof b&&(e=new b(this.game)),this.states[a]=e,d&&(this.game.isBooted?this.start(a):this._pendingState=a),e},remove:function(a){this.current===a&&(this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[a]},start:function(a,b,c){void 0===b&&(b=!0),void 0===c&&(c=!1),this.checkState(a)&&(this._pendingState=a,this._clearWorld=b,this._clearCache=c,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(a,b){void 0===a&&(a=!0),void 0===b&&(b=!1),this._pendingState=this.current,this._clearWorld=a,this._clearCache=b,arguments.length>2&&(this._args=Array.prototype.splice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var a=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,a),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache===!0&&this.game.cache.destroy()))},checkState:function(a){if(this.states[a]){var b=!1;return(this.states[a].preload||this.states[a].create||this.states[a].update||this.states[a].render)&&(b=!0),b===!1?(console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render"),!1):!0}return console.warn("Phaser.StateManager - No state found with the key: "+a),!1},link:function(a){this.states[a].game=this.game,this.states[a].add=this.game.add,this.states[a].make=this.game.make,this.states[a].camera=this.game.camera,this.states[a].cache=this.game.cache,this.states[a].input=this.game.input,this.states[a].load=this.game.load,this.states[a].math=this.game.math,this.states[a].sound=this.game.sound,this.states[a].scale=this.game.scale,this.states[a].state=this,this.states[a].stage=this.game.stage,this.states[a].time=this.game.time,this.states[a].tweens=this.game.tweens,this.states[a].world=this.game.world,this.states[a].particles=this.game.particles,this.states[a].rnd=this.game.rnd,this.states[a].physics=this.game.physics,this.states[a].key=a},unlink:function(a){this.states[a]&&(this.states[a].game=null,this.states[a].add=null,this.states[a].make=null,this.states[a].camera=null,this.states[a].cache=null,this.states[a].input=null,this.states[a].load=null,this.states[a].math=null,this.states[a].sound=null,this.states[a].scale=null,this.states[a].state=null,this.states[a].stage=null,this.states[a].time=null,this.states[a].tweens=null,this.states[a].world=null,this.states[a].particles=null,this.states[a].rnd=null,this.states[a].physics=null)},setCurrentState:function(a){this.callbackContext=this.states[a],this.link(a),this.onInitCallback=this.states[a].init||this.dummy,this.onPreloadCallback=this.states[a].preload||null,this.onLoadRenderCallback=this.states[a].loadRender||null,this.onLoadUpdateCallback=this.states[a].loadUpdate||null,this.onCreateCallback=this.states[a].create||null,this.onUpdateCallback=this.states[a].update||null,this.onPreRenderCallback=this.states[a].preRender||null,this.onRenderCallback=this.states[a].render||null,this.onResizeCallback=this.states[a].resize||null,this.onPausedCallback=this.states[a].paused||null,this.onResumedCallback=this.states[a].resumed||null,this.onPauseUpdateCallback=this.states[a].pauseUpdate||null,this.onShutDownCallback=this.states[a].shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=a,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),a===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){this._created===!1&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(a){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,a)},resize:function(a,b){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,a,b)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===c.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this.clearCurrentState(),this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.game=null,this.states={},this._pendingState=null,this.current=""}},c.StateManager.prototype.constructor=c.StateManager,Object.defineProperty(c.StateManager.prototype,"created",{get:function(){return this._created}}),c.Signal=function(){},c.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!0,validateListener:function(a,b){if("function"!=typeof a)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",b))},_registerListener:function(a,b,d,e,f){var g,h=this._indexOfListener(a,d);if(-1!==h){if(g=this._bindings[h],g.isOnce()!==b)throw new Error("You cannot add"+(b?"":"Once")+"() then add"+(b?"Once":"")+"() the same listener without removing the relationship first.")}else g=new c.SignalBinding(this,a,b,d,e,f),this._addBinding(g);return this.memorize&&this._prevParams&&g.execute(this._prevParams),g},_addBinding:function(a){this._bindings||(this._bindings=[]);var b=this._bindings.length;do b--;while(this._bindings[b]&&a._priority<=this._bindings[b]._priority);this._bindings.splice(b+1,0,a)},_indexOfListener:function(a,b){if(!this._bindings)return-1;void 0===b&&(b=null);for(var c,d=this._bindings.length;d--;)if(c=this._bindings[d],c._listener===a&&c.context===b)return d;return-1},has:function(a,b){return-1!==this._indexOfListener(a,b)},add:function(a,b,c){this.validateListener(a,"add");var d=[];if(arguments.length>3)for(var e=3;e<arguments.length;e++)d.push(arguments[e]);return this._registerListener(a,!1,b,c,d)},addOnce:function(a,b,c){this.validateListener(a,"addOnce");var d=[];if(arguments.length>3)for(var e=3;e<arguments.length;e++)d.push(arguments[e]);return this._registerListener(a,!0,b,c,d)},remove:function(a,b){this.validateListener(a,"remove");var c=this._indexOfListener(a,b);return-1!==c&&(this._bindings[c]._destroy(),this._bindings.splice(c,1)),a},removeAll:function(a){if(void 0===a&&(a=null),this._bindings){for(var b=this._bindings.length;b--;)a?this._bindings[b].context===a&&(this._bindings[b]._destroy(),this._bindings.splice(b,1)):this._bindings[b]._destroy();a||(this._bindings.length=0)}},getNumListeners:function(){return this._bindings?this._bindings.length:0},halt:function(){this._shouldPropagate=!1},dispatch:function(){if(this.active&&this._bindings){var a,b=Array.prototype.slice.call(arguments),c=this._bindings.length;if(this.memorize&&(this._prevParams=b),c){a=this._bindings.slice(),this._shouldPropagate=!0;do c--;while(a[c]&&this._shouldPropagate&&a[c].execute(b)!==!1)}}},forget:function(){this._prevParams&&(this._prevParams=null)},dispose:function(){this.removeAll(),this._bindings=null,this._prevParams&&(this._prevParams=null)},toString:function(){return"[Phaser.Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}},Object.defineProperty(c.Signal.prototype,"boundDispatch",{get:function(){var a=this;return this._boundDispatch||(this._boundDispatch=function(){return a.dispatch.apply(a,arguments)})}}),c.Signal.prototype.constructor=c.Signal,c.SignalBinding=function(a,b,c,d,e,f){this._listener=b,c&&(this._isOnce=!0),null!=d&&(this.context=d),this._signal=a,e&&(this._priority=e),f&&f.length&&(this._args=f)},c.SignalBinding.prototype={context:null,_isOnce:!1,_priority:0,_args:null,callCount:0,active:!0,params:null,execute:function(a){var b,c;return this.active&&this._listener&&(c=this.params?this.params.concat(a):a,this._args&&(c=c.concat(this._args)),b=this._listener.apply(this.context,c),this.callCount++,this._isOnce&&this.detach()),b},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},isOnce:function(){return this._isOnce},getListener:function(){return this._listener},getSignal:function(){return this._signal},_destroy:function(){delete this._signal,delete this._listener,delete this.context},toString:function(){return"[Phaser.SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}},c.SignalBinding.prototype.constructor=c.SignalBinding,c.Filter=function(a,b,d){this.game=a,this.type=c.WEBGL_FILTER,this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.prevPoint=new c.Point;var e=new Date;if(this.uniforms={resolution:{type:"2f",value:{x:256,y:256}},time:{type:"1f",value:0},mouse:{type:"2f",value:{x:0,y:0}},date:{type:"4fv",value:[e.getFullYear(),e.getMonth(),e.getDate(),60*e.getHours()*60+60*e.getMinutes()+e.getSeconds()]},sampleRate:{type:"1f",value:44100},iChannel0:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel1:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel2:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel3:{type:"sampler2D",value:null,textureData:{repeat:!0}}},b)for(var f in b)this.uniforms[f]=b[f];this.fragmentSrc=d||""},c.Filter.prototype={init:function(){},setResolution:function(a,b){this.uniforms.resolution.value.x=a,this.uniforms.resolution.value.y=b},update:function(a){if("undefined"!=typeof a){var b=a.x/this.game.width,c=1-a.y/this.game.height;(b!==this.prevPoint.x||c!==this.prevPoint.y)&&(this.uniforms.mouse.value.x=b.toFixed(2),this.uniforms.mouse.value.y=c.toFixed(2),this.prevPoint.set(b,c))}this.uniforms.time.value=this.game.time.totalElapsedSeconds()},destroy:function(){this.game=null}},c.Filter.prototype.constructor=c.Filter,Object.defineProperty(c.Filter.prototype,"width",{get:function(){return this.uniforms.resolution.value.x},set:function(a){this.uniforms.resolution.value.x=a}}),Object.defineProperty(c.Filter.prototype,"height",{get:function(){return this.uniforms.resolution.value.y},set:function(a){this.uniforms.resolution.value.y=a}}),c.Plugin=function(a,b){void 0===b&&(b=null),this.game=a,this.parent=b,this.active=!1,this.visible=!1,this.hasPreUpdate=!1,this.hasUpdate=!1,this.hasPostUpdate=!1,this.hasRender=!1,this.hasPostRender=!1},c.Plugin.prototype={preUpdate:function(){},update:function(){},render:function(){},postRender:function(){},destroy:function(){this.game=null,this.parent=null,this.active=!1,this.visible=!1}},c.Plugin.prototype.constructor=c.Plugin,c.PluginManager=function(a){this.game=a,this.plugins=[],this._len=0,this._i=0},c.PluginManager.prototype={add:function(a){var b=Array.prototype.splice.call(arguments,1),c=!1;return"function"==typeof a?a=new a(this.game,this):(a.game=this.game,a.parent=this),"function"==typeof a.preUpdate&&(a.hasPreUpdate=!0,c=!0),"function"==typeof a.update&&(a.hasUpdate=!0,c=!0),"function"==typeof a.postUpdate&&(a.hasPostUpdate=!0,c=!0),"function"==typeof a.render&&(a.hasRender=!0,c=!0),"function"==typeof a.postRender&&(a.hasPostRender=!0,c=!0),c?((a.hasPreUpdate||a.hasUpdate||a.hasPostUpdate)&&(a.active=!0),(a.hasRender||a.hasPostRender)&&(a.visible=!0),this._len=this.plugins.push(a),"function"==typeof a.init&&a.init.apply(a,b),a):null},remove:function(a){for(this._i=this._len;this._i--;)if(this.plugins[this._i]===a)return a.destroy(),this.plugins.splice(this._i,1),void this._len--},removeAll:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].destroy();this.plugins.length=0,this._len=0},preUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPreUpdate&&this.plugins[this._i].preUpdate()},update:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasUpdate&&this.plugins[this._i].update()},postUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPostUpdate&&this.plugins[this._i].postUpdate()},render:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasRender&&this.plugins[this._i].render()},postRender:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasPostRender&&this.plugins[this._i].postRender()},destroy:function(){this.removeAll(),this.game=null}},c.PluginManager.prototype.constructor=c.PluginManager,c.Stage=function(a){this.game=a,PIXI.Stage.call(this,0),this.name="_stage_root",this.disableVisibilityChange=!1,this.exists=!0,this.currentRenderOrderID=0,this._hiddenVar="hidden",this._onChange=null,this._backgroundColor=0,a.config&&this.parseConfig(a.config)},c.Stage.prototype=Object.create(PIXI.Stage.prototype),c.Stage.prototype.constructor=c.Stage,c.Stage.prototype.parseConfig=function(a){a.disableVisibilityChange&&(this.disableVisibilityChange=a.disableVisibilityChange),a.backgroundColor&&(this.backgroundColor=a.backgroundColor)},c.Stage.prototype.boot=function(){c.DOM.getOffset(this.game.canvas,this.offset),c.Canvas.setUserSelect(this.game.canvas,"none"),c.Canvas.setTouchAction(this.game.canvas,"none"),this.checkVisibility()},c.Stage.prototype.preUpdate=function(){this.currentRenderOrderID=0;for(var a=0;a<this.children.length;a++)this.children[a].preUpdate()},c.Stage.prototype.update=function(){for(var a=this.children.length;a--;)this.children[a].update()},c.Stage.prototype.postUpdate=function(){if(this.game.world.camera.target){this.game.world.camera.target.postUpdate(),this.game.world.camera.update();for(var a=this.children.length;a--;)this.children[a]!==this.game.world.camera.target&&this.children[a].postUpdate()}else{this.game.world.camera.update();for(var a=this.children.length;a--;)this.children[a].postUpdate()}},c.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var a=0;a<this.children.length;a++)this.children[a].updateTransform()},c.Stage.prototype.checkVisibility=function(){this._hiddenVar=void 0!==document.webkitHidden?"webkitvisibilitychange":void 0!==document.mozHidden?"mozvisibilitychange":void 0!==document.msHidden?"msvisibilitychange":void 0!==document.hidden?"visibilitychange":null;var a=this;this._onChange=function(b){return a.visibilityChange(b)},this._hiddenVar&&document.addEventListener(this._hiddenVar,this._onChange,!1),window.onblur=this._onChange,window.onfocus=this._onChange,window.onpagehide=this._onChange,window.onpageshow=this._onChange,this.game.device.cocoonJSApp&&(CocoonJS.App.onSuspended.addEventListener(function(){c.Stage.prototype.visibilityChange.call(a,{type:"pause"})}),CocoonJS.App.onActivated.addEventListener(function(){c.Stage.prototype.visibilityChange.call(a,{type:"resume"})}))},c.Stage.prototype.visibilityChange=function(a){return"pagehide"===a.type||"blur"===a.type||"pageshow"===a.type||"focus"===a.type?void("pagehide"===a.type||"blur"===a.type?this.game.focusLoss(a):("pageshow"===a.type||"focus"===a.type)&&this.game.focusGain(a)):void(this.disableVisibilityChange||(document.hidden||document.mozHidden||document.msHidden||document.webkitHidden||"pause"===a.type?this.game.gamePaused(a):this.game.gameResumed(a)))},c.Stage.prototype.setBackgroundColor=function(a){var b=c.Color.valueToColor(a);this._backgroundColor=c.Color.getColor(b.r,b.g,b.b),this.backgroundColorSplit=[b.r/255,b.g/255,b.b/255],this.backgroundColorString=c.Color.RGBtoString(b.r,b.g,b.b,255,"#")},c.Stage.prototype.destroy=function(){this._hiddenVar&&document.removeEventListener(this._hiddenVar,this._onChange,!1),window.onpagehide=null,window.onpageshow=null,window.onblur=null,window.onfocus=null},Object.defineProperty(c.Stage.prototype,"backgroundColor",{get:function(){return this._backgroundColor},set:function(a){this.game.transparent||this.setBackgroundColor(a)}}),Object.defineProperty(c.Stage.prototype,"smoothed",{get:function(){return PIXI.scaleModes.DEFAULT===PIXI.scaleModes.LINEAR},set:function(a){PIXI.scaleModes.DEFAULT=a?PIXI.scaleModes.LINEAR:PIXI.scaleModes.NEAREST}}),c.Group=function(a,b,d,e,f,g){void 0===e&&(e=!1),void 0===f&&(f=!1),void 0===g&&(g=c.Physics.ARCADE),this.game=a,void 0===b&&(b=a.world),this.name=d||"group",this.z=0,PIXI.DisplayObjectContainer.call(this),e?(this.game.stage.addChild(this),this.z=this.game.stage.children.length):b&&(b.addChild(this),this.z=b.children.length),this.type=c.GROUP,this.physicsType=c.GROUP,this.alive=!0,this.exists=!0,this.ignoreDestroy=!1,this.pendingDestroy=!1,this.classType=c.Sprite,this.cursor=null,this.enableBody=f,this.enableBodyDebug=!1,this.physicsBodyType=g,this.physicsSortDirection=null,this.onDestroy=new c.Signal,this.cursorIndex=0,this.fixedToCamera=!1,this.cameraOffset=new c.Point,this.hash=[],this._sortProperty="z"},c.Group.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),c.Group.prototype.constructor=c.Group,c.Group.RETURN_NONE=0,c.Group.RETURN_TOTAL=1,c.Group.RETURN_CHILD=2,c.Group.SORT_ASCENDING=-1,c.Group.SORT_DESCENDING=1,c.Group.prototype.add=function(a,b){return void 0===b&&(b=!1),a.parent!==this&&(this.addChild(a),a.z=this.children.length,this.enableBody&&null===a.body?this.game.physics.enable(a,this.physicsBodyType):a.body&&this.addToHash(a),!b&&a.events&&a.events.onAddedToGroup$dispatch(a,this),null===this.cursor&&(this.cursor=a)),a},c.Group.prototype.addToHash=function(a){if(a.parent===this){var b=this.hash.indexOf(a);if(-1===b)return this.hash.push(a),!0}return!1},c.Group.prototype.removeFromHash=function(a){if(a){var b=this.hash.indexOf(a);if(-1!==b)return this.hash.splice(b,1),!0}return!1},c.Group.prototype.addMultiple=function(a,b){if(a instanceof c.Group)a.moveAll(this,b);else if(Array.isArray(a))for(var d=0;d<a.length;d++)this.add(a[d],b);return a},c.Group.prototype.addAt=function(a,b,c){return void 0===c&&(c=!1),a.parent!==this&&(this.addChildAt(a,b),this.updateZ(),this.enableBody&&null===a.body?this.game.physics.enable(a,this.physicsBodyType):a.body&&this.addToHash(a),!c&&a.events&&a.events.onAddedToGroup$dispatch(a,this),null===this.cursor&&(this.cursor=a)),a},c.Group.prototype.getAt=function(a){return 0>a||a>=this.children.length?-1:this.getChildAt(a)},c.Group.prototype.create=function(a,b,c,d,e){void 0===e&&(e=!0);var f=new this.classType(this.game,a,b,c,d);return f.exists=e,f.visible=e,f.alive=e,this.addChild(f),f.z=this.children.length,this.enableBody&&this.game.physics.enable(f,this.physicsBodyType,this.enableBodyDebug),f.events&&f.events.onAddedToGroup$dispatch(f,this),null===this.cursor&&(this.cursor=f),f},c.Group.prototype.createMultiple=function(a,b,c,d){void 0===d&&(d=!1);for(var e=0;a>e;e++)this.create(0,0,b,c,d)},c.Group.prototype.updateZ=function(){for(var a=this.children.length;a--;)this.children[a].z=a},c.Group.prototype.resetCursor=function(a){return void 0===a&&(a=0),a>this.children.length-1&&(a=0),this.cursor?(this.cursorIndex=a,this.cursor=this.children[this.cursorIndex],this.cursor):void 0},c.Group.prototype.next=function(){return this.cursor?(this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor):void 0},c.Group.prototype.previous=function(){return this.cursor?(0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor):void 0},c.Group.prototype.swap=function(a,b){this.swapChildren(a,b),this.updateZ()},c.Group.prototype.bringToTop=function(a){return a.parent===this&&this.getIndex(a)<this.children.length&&(this.remove(a,!1,!0),this.add(a,!0)),a},c.Group.prototype.sendToBack=function(a){return a.parent===this&&this.getIndex(a)>0&&(this.remove(a,!1,!0),this.addAt(a,0,!0)),a},c.Group.prototype.moveUp=function(a){if(a.parent===this&&this.getIndex(a)<this.children.length-1){var b=this.getIndex(a),c=this.getAt(b+1);c&&this.swap(a,c)}return a},c.Group.prototype.moveDown=function(a){if(a.parent===this&&this.getIndex(a)>0){var b=this.getIndex(a),c=this.getAt(b-1);c&&this.swap(a,c)}return a},c.Group.prototype.xy=function(a,b,c){return 0>a||a>this.children.length?-1:(this.getChildAt(a).x=b,void(this.getChildAt(a).y=c))},c.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},c.Group.prototype.getIndex=function(a){return this.children.indexOf(a)},c.Group.prototype.replace=function(a,b){var d=this.getIndex(a);return-1!==d?(b.parent&&(b.parent instanceof c.Group?b.parent.remove(b):b.parent.removeChild(b)),this.remove(a),this.addAt(b,d),a):void 0},c.Group.prototype.hasProperty=function(a,b){var c=b.length;return 1===c&&b[0]in a?!0:2===c&&b[0]in a&&b[1]in a[b[0]]?!0:3===c&&b[0]in a&&b[1]in a[b[0]]&&b[2]in a[b[0]][b[1]]?!0:4===c&&b[0]in a&&b[1]in a[b[0]]&&b[2]in a[b[0]][b[1]]&&b[3]in a[b[0]][b[1]][b[2]]?!0:!1},c.Group.prototype.setProperty=function(a,b,c,d,e){if(void 0===e&&(e=!1),d=d||0,!this.hasProperty(a,b)&&(!e||d>0))return!1;var f=b.length;return 1===f?0===d?a[b[0]]=c:1==d?a[b[0]]+=c:2==d?a[b[0]]-=c:3==d?a[b[0]]*=c:4==d&&(a[b[0]]/=c):2===f?0===d?a[b[0]][b[1]]=c:1==d?a[b[0]][b[1]]+=c:2==d?a[b[0]][b[1]]-=c:3==d?a[b[0]][b[1]]*=c:4==d&&(a[b[0]][b[1]]/=c):3===f?0===d?a[b[0]][b[1]][b[2]]=c:1==d?a[b[0]][b[1]][b[2]]+=c:2==d?a[b[0]][b[1]][b[2]]-=c:3==d?a[b[0]][b[1]][b[2]]*=c:4==d&&(a[b[0]][b[1]][b[2]]/=c):4===f&&(0===d?a[b[0]][b[1]][b[2]][b[3]]=c:1==d?a[b[0]][b[1]][b[2]][b[3]]+=c:2==d?a[b[0]][b[1]][b[2]][b[3]]-=c:3==d?a[b[0]][b[1]][b[2]][b[3]]*=c:4==d&&(a[b[0]][b[1]][b[2]][b[3]]/=c)),!0},c.Group.prototype.checkProperty=function(a,b,d,e){return void 0===e&&(e=!1),!c.Utils.getProperty(a,b)&&e?!1:c.Utils.getProperty(a,b)!==d?!1:!0},c.Group.prototype.set=function(a,b,c,d,e,f,g){return void 0===g&&(g=!1),b=b.split("."),void 0===d&&(d=!1),void 0===e&&(e=!1),(d===!1||d&&a.alive)&&(e===!1||e&&a.visible)?this.setProperty(a,b,c,f,g):void 0},c.Group.prototype.setAll=function(a,b,c,d,e,f){void 0===c&&(c=!1),void 0===d&&(d=!1),void 0===f&&(f=!1),a=a.split("."),e=e||0;for(var g=0;g<this.children.length;g++)(!c||c&&this.children[g].alive)&&(!d||d&&this.children[g].visible)&&this.setProperty(this.children[g],a,b,e,f)},c.Group.prototype.setAllChildren=function(a,b,d,e,f,g){void 0===d&&(d=!1),void 0===e&&(e=!1),void 0===g&&(g=!1),f=f||0;for(var h=0;h<this.children.length;h++)(!d||d&&this.children[h].alive)&&(!e||e&&this.children[h].visible)&&(this.children[h]instanceof c.Group?this.children[h].setAllChildren(a,b,d,e,f,g):this.setProperty(this.children[h],a.split("."),b,f,g))},c.Group.prototype.checkAll=function(a,b,c,d,e){void 0===c&&(c=!1),void 0===d&&(d=!1),void 0===e&&(e=!1);for(var f=0;f<this.children.length;f++)if((!c||c&&this.children[f].alive)&&(!d||d&&this.children[f].visible)&&!this.checkProperty(this.children[f],a,b,e))return!1;return!0},c.Group.prototype.addAll=function(a,b,c,d){this.setAll(a,b,c,d,1)},c.Group.prototype.subAll=function(a,b,c,d){this.setAll(a,b,c,d,2)},c.Group.prototype.multiplyAll=function(a,b,c,d){this.setAll(a,b,c,d,3)},c.Group.prototype.divideAll=function(a,b,c,d){this.setAll(a,b,c,d,4)},c.Group.prototype.callAllExists=function(a,b){var c;if(arguments.length>2){c=[];for(var d=2;d<arguments.length;d++)c.push(arguments[d])}for(var d=0;d<this.children.length;d++)this.children[d].exists===b&&this.children[d][a]&&this.children[d][a].apply(this.children[d],c)},c.Group.prototype.callbackFromArray=function(a,b,c){if(1==c){if(a[b[0]])return a[b[0]]}else if(2==c){if(a[b[0]][b[1]])return a[b[0]][b[1]]}else if(3==c){if(a[b[0]][b[1]][b[2]])return a[b[0]][b[1]][b[2]]}else if(4==c){if(a[b[0]][b[1]][b[2]][b[3]])return a[b[0]][b[1]][b[2]][b[3]]}else if(a[b])return a[b];return!1},c.Group.prototype.callAll=function(a,b){if(void 0!==a){a=a.split(".");var c=a.length;if(void 0===b||null===b||""===b)b=null;else if("string"==typeof b){b=b.split(".");var d=b.length}var e;if(arguments.length>2){e=[];for(var f=2;f<arguments.length;f++)e.push(arguments[f])}for(var g=null,h=null,f=0;f<this.children.length;f++)g=this.callbackFromArray(this.children[f],a,c),b&&g?(h=this.callbackFromArray(this.children[f],b,d),g&&g.apply(h,e)):g&&g.apply(this.children[f],e)}},c.Group.prototype.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;for(var a=this.children.length;a--;)this.children[a].preUpdate();return!0},c.Group.prototype.update=function(){for(var a=this.children.length;a--;)this.children[a].update()},c.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=this.game.camera.view.x+this.cameraOffset.x,this.y=this.game.camera.view.y+this.cameraOffset.y);for(var a=this.children.length;a--;)this.children[a].postUpdate()},c.Group.prototype.filter=function(a,b){for(var d=-1,e=this.children.length,f=[];++d<e;){var g=this.children[d];(!b||b&&g.exists)&&a(g,d,this.children)&&f.push(g)}return new c.ArraySet(f)},c.Group.prototype.forEach=function(a,b,c){if(void 0===c&&(c=!1),arguments.length<=3)for(var d=0;d<this.children.length;d++)(!c||c&&this.children[d].exists)&&a.call(b,this.children[d]);else{for(var e=[null],d=3;d<arguments.length;d++)e.push(arguments[d]);for(var d=0;d<this.children.length;d++)(!c||c&&this.children[d].exists)&&(e[0]=this.children[d],a.apply(b,e))}},c.Group.prototype.forEachExists=function(a,b){var d;if(arguments.length>2){d=[null];for(var e=2;e<arguments.length;e++)d.push(arguments[e])}this.iterate("exists",!0,c.Group.RETURN_TOTAL,a,b,d)},c.Group.prototype.forEachAlive=function(a,b){var d;if(arguments.length>2){d=[null];for(var e=2;e<arguments.length;e++)d.push(arguments[e])}this.iterate("alive",!0,c.Group.RETURN_TOTAL,a,b,d)},c.Group.prototype.forEachDead=function(a,b){var d;if(arguments.length>2){d=[null];for(var e=2;e<arguments.length;e++)d.push(arguments[e])}this.iterate("alive",!1,c.Group.RETURN_TOTAL,a,b,d)},c.Group.prototype.sort=function(a,b){this.children.length<2||(void 0===a&&(a="z"),void 0===b&&(b=c.Group.SORT_ASCENDING),this._sortProperty=a,this.children.sort(b===c.Group.SORT_ASCENDING?this.ascendingSortHandler.bind(this):this.descendingSortHandler.bind(this)),this.updateZ())},c.Group.prototype.customSort=function(a,b){this.children.length<2||(this.children.sort(a.bind(b)),this.updateZ())},c.Group.prototype.ascendingSortHandler=function(a,b){return a[this._sortProperty]<b[this._sortProperty]?-1:a[this._sortProperty]>b[this._sortProperty]?1:a.z<b.z?-1:1},c.Group.prototype.descendingSortHandler=function(a,b){return a[this._sortProperty]<b[this._sortProperty]?1:a[this._sortProperty]>b[this._sortProperty]?-1:0},c.Group.prototype.iterate=function(a,b,d,e,f,g){if(d===c.Group.RETURN_TOTAL&&0===this.children.length)return 0;for(var h=0,i=0;i<this.children.length;i++)if(this.children[i][a]===b&&(h++,e&&(g?(g[0]=this.children[i],e.apply(f,g)):e.call(f,this.children[i])),d===c.Group.RETURN_CHILD))return this.children[i];return d===c.Group.RETURN_TOTAL?h:null},c.Group.prototype.getFirstExists=function(a){return"boolean"!=typeof a&&(a=!0),this.iterate("exists",a,c.Group.RETURN_CHILD)},c.Group.prototype.getFirstAlive=function(){return this.iterate("alive",!0,c.Group.RETURN_CHILD)},c.Group.prototype.getFirstDead=function(){return this.iterate("alive",!1,c.Group.RETURN_CHILD)},c.Group.prototype.getTop=function(){return this.children.length>0?this.children[this.children.length-1]:void 0},c.Group.prototype.getBottom=function(){return this.children.length>0?this.children[0]:void 0},c.Group.prototype.countLiving=function(){return this.iterate("alive",!0,c.Group.RETURN_TOTAL)},c.Group.prototype.countDead=function(){return this.iterate("alive",!1,c.Group.RETURN_TOTAL)},c.Group.prototype.getRandom=function(a,b){return 0===this.children.length?null:(a=a||0,b=b||this.children.length,c.ArrayUtils.getRandomItem(this.children,a,b))},c.Group.prototype.remove=function(a,b,c){if(void 0===b&&(b=!1),void 0===c&&(c=!1),0===this.children.length||-1===this.children.indexOf(a))return!1;c||!a.events||a.destroyPhase||a.events.onRemovedFromGroup$dispatch(a,this);var d=this.removeChild(a);return this.removeFromHash(a),this.updateZ(),this.cursor===a&&this.next(),b&&d&&d.destroy(!0),!0},c.Group.prototype.moveAll=function(a,b){if(void 0===b&&(b=!1),this.children.length>0&&a instanceof c.Group){do a.add(this.children[0],b);while(this.children.length>0);this.hash=[],this.cursor=null}return a},c.Group.prototype.removeAll=function(a,b){if(void 0===a&&(a=!1),void 0===b&&(b=!1),0!==this.children.length){do{!b&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var c=this.removeChild(this.children[0]);this.removeFromHash(c),a&&c&&c.destroy(!0)}while(this.children.length>0);this.hash=[],this.cursor=null}},c.Group.prototype.removeBetween=function(a,b,c,d){if(void 0===b&&(b=this.children.length-1),void 0===c&&(c=!1),void 0===d&&(d=!1),0!==this.children.length){if(a>b||0>a||b>this.children.length)return!1;for(var e=b;e>=a;){!d&&this.children[e].events&&this.children[e].events.onRemovedFromGroup$dispatch(this.children[e],this);var f=this.removeChild(this.children[e]);this.removeFromHash(f),c&&f&&f.destroy(!0),this.cursor===this.children[e]&&(this.cursor=null),e--}this.updateZ()}},c.Group.prototype.destroy=function(a,b){null===this.game||this.ignoreDestroy||(void 0===a&&(a=!0),void 0===b&&(b=!1),this.onDestroy.dispatch(this,a,b),this.removeAll(a),this.cursor=null,this.filters=null,this.pendingDestroy=!1,b||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(c.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,c.Group.RETURN_TOTAL)}}),Object.defineProperty(c.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(c.Group.prototype,"angle",{get:function(){return c.Math.radToDeg(this.rotation)},set:function(a){this.rotation=c.Math.degToRad(a)}}),c.World=function(a){c.Group.call(this,a,null,"__world",!1),this.bounds=new c.Rectangle(0,0,a.width,a.height),this.camera=null,this._definedSize=!1,this._width=a.width,this._height=a.height,this.game.state.onStateChange.add(this.stateChange,this)
+},c.World.prototype=Object.create(c.Group.prototype),c.World.prototype.constructor=c.World,c.World.prototype.boot=function(){this.camera=new c.Camera(this.game,0,0,0,this.game.width,this.game.height),this.camera.displayObject=this,this.camera.scale=this.scale,this.game.camera=this.camera,this.game.stage.addChild(this)},c.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},c.World.prototype.setBounds=function(a,b,c,d){this._definedSize=!0,this._width=c,this._height=d,this.bounds.setTo(a,b,c,d),this.x=a,this.y=b,this.camera.bounds&&this.camera.bounds.setTo(a,b,Math.max(c,this.game.width),Math.max(d,this.game.height)),this.game.physics.setBoundsToWorld()},c.World.prototype.resize=function(a,b){this._definedSize&&(a<this._width&&(a=this._width),b<this._height&&(b=this._height)),this.bounds.width=a,this.bounds.height=b,this.game.camera.setBoundsToWorld(),this.game.physics.setBoundsToWorld()},c.World.prototype.shutdown=function(){this.destroy(!0,!0)},c.World.prototype.wrap=function(a,b,c,d,e){void 0===b&&(b=0),void 0===c&&(c=!1),void 0===d&&(d=!0),void 0===e&&(e=!0),c?(a.getBounds(),d&&(a.x+a._currentBounds.width<this.bounds.x?a.x=this.bounds.right:a.x>this.bounds.right&&(a.x=this.bounds.left)),e&&(a.y+a._currentBounds.height<this.bounds.top?a.y=this.bounds.bottom:a.y>this.bounds.bottom&&(a.y=this.bounds.top))):(d&&a.x+b<this.bounds.x?a.x=this.bounds.right+b:d&&a.x-b>this.bounds.right&&(a.x=this.bounds.left-b),e&&a.y+b<this.bounds.top?a.y=this.bounds.bottom+b:e&&a.y-b>this.bounds.bottom&&(a.y=this.bounds.top-b))},Object.defineProperty(c.World.prototype,"width",{get:function(){return this.bounds.width},set:function(a){a<this.game.width&&(a=this.game.width),this.bounds.width=a,this._width=a,this._definedSize=!0}}),Object.defineProperty(c.World.prototype,"height",{get:function(){return this.bounds.height},set:function(a){a<this.game.height&&(a=this.game.height),this.bounds.height=a,this._height=a,this._definedSize=!0}}),Object.defineProperty(c.World.prototype,"centerX",{get:function(){return this.bounds.halfWidth}}),Object.defineProperty(c.World.prototype,"centerY",{get:function(){return this.bounds.halfHeight}}),Object.defineProperty(c.World.prototype,"randomX",{get:function(){return this.bounds.x<0?this.game.rnd.between(this.bounds.x,this.bounds.width-Math.abs(this.bounds.x)):this.game.rnd.between(this.bounds.x,this.bounds.width)}}),Object.defineProperty(c.World.prototype,"randomY",{get:function(){return this.bounds.y<0?this.game.rnd.between(this.bounds.y,this.bounds.height-Math.abs(this.bounds.y)):this.game.rnd.between(this.bounds.y,this.bounds.height)}}),c.FlexGrid=function(a,b,d){this.game=a.game,this.manager=a,this.width=b,this.height=d,this.boundsCustom=new c.Rectangle(0,0,b,d),this.boundsFluid=new c.Rectangle(0,0,b,d),this.boundsFull=new c.Rectangle(0,0,b,d),this.boundsNone=new c.Rectangle(0,0,b,d),this.positionCustom=new c.Point(0,0),this.positionFluid=new c.Point(0,0),this.positionFull=new c.Point(0,0),this.positionNone=new c.Point(0,0),this.scaleCustom=new c.Point(1,1),this.scaleFluid=new c.Point(1,1),this.scaleFluidInversed=new c.Point(1,1),this.scaleFull=new c.Point(1,1),this.scaleNone=new c.Point(1,1),this.customWidth=0,this.customHeight=0,this.customOffsetX=0,this.customOffsetY=0,this.ratioH=b/d,this.ratioV=d/b,this.multiplier=0,this.layers=[]},c.FlexGrid.prototype={setSize:function(a,b){this.width=a,this.height=b,this.ratioH=a/b,this.ratioV=b/a,this.scaleNone=new c.Point(1,1),this.boundsNone.width=this.width,this.boundsNone.height=this.height,this.refresh()},createCustomLayer:function(a,b,d,e){void 0===e&&(e=!0),this.customWidth=a,this.customHeight=b,this.boundsCustom.width=a,this.boundsCustom.height=b;var f=new c.FlexLayer(this,this.positionCustom,this.boundsCustom,this.scaleCustom);return e&&this.game.world.add(f),this.layers.push(f),"undefined"!=typeof d&&null!==typeof d&&f.addMultiple(d),f},createFluidLayer:function(a,b){void 0===b&&(b=!0);var d=new c.FlexLayer(this,this.positionFluid,this.boundsFluid,this.scaleFluid);return b&&this.game.world.add(d),this.layers.push(d),"undefined"!=typeof a&&null!==typeof a&&d.addMultiple(a),d},createFullLayer:function(a){var b=new c.FlexLayer(this,this.positionFull,this.boundsFull,this.scaleFluid);return this.game.world.add(b),this.layers.push(b),"undefined"!=typeof a&&b.addMultiple(a),b},createFixedLayer:function(a){var b=new c.FlexLayer(this,this.positionNone,this.boundsNone,this.scaleNone);return this.game.world.add(b),this.layers.push(b),"undefined"!=typeof a&&b.addMultiple(a),b},reset:function(){for(var a=this.layers.length;a--;)this.layers[a].persist||(this.layers[a].position=null,this.layers[a].scale=null,this.layers.slice(a,1))},onResize:function(a,b){this.ratioH=a/b,this.ratioV=b/a,this.refresh(a,b)},refresh:function(){this.multiplier=Math.min(this.manager.height/this.height,this.manager.width/this.width),this.boundsFluid.width=Math.round(this.width*this.multiplier),this.boundsFluid.height=Math.round(this.height*this.multiplier),this.scaleFluid.set(this.boundsFluid.width/this.width,this.boundsFluid.height/this.height),this.scaleFluidInversed.set(this.width/this.boundsFluid.width,this.height/this.boundsFluid.height),this.scaleFull.set(this.boundsFull.width/this.width,this.boundsFull.height/this.height),this.boundsFull.width=Math.round(this.manager.width*this.scaleFluidInversed.x),this.boundsFull.height=Math.round(this.manager.height*this.scaleFluidInversed.y),this.boundsFluid.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.boundsNone.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.positionFluid.set(this.boundsFluid.x,this.boundsFluid.y),this.positionNone.set(this.boundsNone.x,this.boundsNone.y)},fitSprite:function(a){this.manager.scaleSprite(a),a.x=this.manager.bounds.centerX,a.y=this.manager.bounds.centerY},debug:function(){this.game.debug.text(this.boundsFluid.width+" x "+this.boundsFluid.height,this.boundsFluid.x+4,this.boundsFluid.y+16),this.game.debug.geom(this.boundsFluid,"rgba(255,0,0,0.9",!1)}},c.FlexGrid.prototype.constructor=c.FlexGrid,c.FlexLayer=function(a,b,d,e){c.Group.call(this,a.game,null,"__flexLayer"+a.game.rnd.uuid(),!1),this.manager=a.manager,this.grid=a,this.persist=!1,this.position=b,this.bounds=d,this.scale=e,this.topLeft=d.topLeft,this.topMiddle=new c.Point(d.halfWidth,0),this.topRight=d.topRight,this.bottomLeft=d.bottomLeft,this.bottomMiddle=new c.Point(d.halfWidth,d.bottom),this.bottomRight=d.bottomRight},c.FlexLayer.prototype=Object.create(c.Group.prototype),c.FlexLayer.prototype.constructor=c.FlexLayer,c.FlexLayer.prototype.resize=function(){},c.FlexLayer.prototype.debug=function(){this.game.debug.text(this.bounds.width+" x "+this.bounds.height,this.bounds.x+4,this.bounds.y+16),this.game.debug.geom(this.bounds,"rgba(0,0,255,0.9",!1),this.game.debug.geom(this.topLeft,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topMiddle,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topRight,"rgba(255,255,255,0.9")},c.ScaleManager=function(a,b,d){this.game=a,this.dom=c.DOM,this.grid=null,this.width=0,this.height=0,this.minWidth=null,this.maxWidth=null,this.minHeight=null,this.maxHeight=null,this.offset=new c.Point,this.forceLandscape=!1,this.forcePortrait=!1,this.incorrectOrientation=!1,this._pageAlignHorizontally=!1,this._pageAlignVertically=!1,this.onOrientationChange=new c.Signal,this.enterIncorrectOrientation=new c.Signal,this.leaveIncorrectOrientation=new c.Signal,this.fullScreenTarget=null,this._createdFullScreenTarget=null,this.onFullScreenInit=new c.Signal,this.onFullScreenChange=new c.Signal,this.onFullScreenError=new c.Signal,this.screenOrientation=this.dom.getScreenOrientation(),this.scaleFactor=new c.Point(1,1),this.scaleFactorInversed=new c.Point(1,1),this.margin={left:0,top:0,right:0,bottom:0,x:0,y:0},this.bounds=new c.Rectangle,this.aspectRatio=0,this.sourceAspectRatio=0,this.event=null,this.windowConstraints={right:"layout",bottom:""},this.compatibility={supportsFullScreen:!1,orientationFallback:null,noMargins:!1,scrollTo:null,forceMinimumDocumentHeight:!1,canExpandParent:!0,clickTrampoline:""},this._scaleMode=c.ScaleManager.NO_SCALE,this._fullScreenScaleMode=c.ScaleManager.NO_SCALE,this.parentIsWindow=!1,this.parentNode=null,this.parentScaleFactor=new c.Point(1,1),this.trackParentInterval=2e3,this.onSizeChange=new c.Signal,this.onResize=null,this.onResizeContext=null,this._pendingScaleMode=null,this._fullScreenRestore=null,this._gameSize=new c.Rectangle,this._userScaleFactor=new c.Point(1,1),this._userScaleTrim=new c.Point(0,0),this._lastUpdate=0,this._updateThrottle=0,this._updateThrottleReset=100,this._parentBounds=new c.Rectangle,this._tempBounds=new c.Rectangle,this._lastReportedCanvasSize=new c.Rectangle,this._lastReportedGameSize=new c.Rectangle,this._booted=!1,a.config&&this.parseConfig(a.config),this.setupScale(b,d)},c.ScaleManager.EXACT_FIT=0,c.ScaleManager.NO_SCALE=1,c.ScaleManager.SHOW_ALL=2,c.ScaleManager.RESIZE=3,c.ScaleManager.USER_SCALE=4,c.ScaleManager.prototype={boot:function(){var a=this.compatibility;a.supportsFullScreen=this.game.device.fullscreen&&!this.game.device.cocoonJS,this.game.device.iPad||this.game.device.webApp||this.game.device.desktop||(a.scrollTo=this.game.device.android&&!this.game.device.chrome?new c.Point(0,1):new c.Point(0,0)),this.game.device.desktop?(a.orientationFallback="screen",a.clickTrampoline="when-not-mouse"):(a.orientationFallback="",a.clickTrampoline="");var b=this;this._orientationChange=function(a){return b.orientationChange(a)},this._windowResize=function(a){return b.windowResize(a)},window.addEventListener("orientationchange",this._orientationChange,!1),window.addEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(this._fullScreenChange=function(a){return b.fullScreenChange(a)},this._fullScreenError=function(a){return b.fullScreenError(a)},document.addEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.addEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.addEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.addEventListener("fullscreenchange",this._fullScreenChange,!1),document.addEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.addEventListener("mozfullscreenerror",this._fullScreenError,!1),document.addEventListener("MSFullscreenError",this._fullScreenError,!1),document.addEventListener("fullscreenerror",this._fullScreenError,!1)),this.game.onResume.add(this._gameResumed,this),this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.setGameSize(this.game.width,this.game.height),this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.grid=new c.FlexGrid(this,this.width,this.height),this._booted=!0,this._pendingScaleMode&&(this.scaleMode=this._pendingScaleMode,this._pendingScaleMode=null)},parseConfig:function(a){a.scaleMode&&(this._booted?this.scaleMode=a.scaleMode:this._pendingScaleMode=a.scaleMode),a.fullScreenScaleMode&&(this.fullScreenScaleMode=a.fullScreenScaleMode),a.fullScreenTarget&&(this.fullScreenTarget=a.fullScreenTarget)},setupScale:function(a,b){var d,e=new c.Rectangle;""!==this.game.parent&&("string"==typeof this.game.parent?d=document.getElementById(this.game.parent):this.game.parent&&1===this.game.parent.nodeType&&(d=this.game.parent)),d?(this.parentNode=d,this.parentIsWindow=!1,this.getParentBounds(this._parentBounds),e.width=this._parentBounds.width,e.height=this._parentBounds.height,this.offset.set(this._parentBounds.x,this._parentBounds.y)):(this.parentNode=null,this.parentIsWindow=!0,e.width=this.dom.visualBounds.width,e.height=this.dom.visualBounds.height,this.offset.set(0,0));var f=0,g=0;"number"==typeof a?f=a:(this.parentScaleFactor.x=parseInt(a,10)/100,f=e.width*this.parentScaleFactor.x),"number"==typeof b?g=b:(this.parentScaleFactor.y=parseInt(b,10)/100,g=e.height*this.parentScaleFactor.y),this._gameSize.setTo(0,0,f,g),this.updateDimensions(f,g,!1)},_gameResumed:function(){this.queueUpdate(!0)},setGameSize:function(a,b){this._gameSize.setTo(0,0,a,b),this.currentScaleMode!==c.ScaleManager.RESIZE&&this.updateDimensions(a,b,!0),this.queueUpdate(!0)},setUserScale:function(a,b,c,d){this._userScaleFactor.setTo(a,b),this._userScaleTrim.setTo(0|c,0|d),this.queueUpdate(!0)},setResizeCallback:function(a,b){this.onResize=a,this.onResizeContext=b},signalSizeChange:function(){if(!c.Rectangle.sameDimensions(this,this._lastReportedCanvasSize)||!c.Rectangle.sameDimensions(this.game,this._lastReportedGameSize)){var a=this.width,b=this.height;this._lastReportedCanvasSize.setTo(0,0,a,b),this._lastReportedGameSize.setTo(0,0,this.game.width,this.game.height),this.grid.onResize(a,b),this.onSizeChange.dispatch(this,a,b),this.currentScaleMode===c.ScaleManager.RESIZE&&(this.game.state.resize(a,b),this.game.load.resize(a,b))}},setMinMax:function(a,b,c,d){this.minWidth=a,this.minHeight=b,"undefined"!=typeof c&&(this.maxWidth=c),"undefined"!=typeof d&&(this.maxHeight=d)},preUpdate:function(){if(!(this.game.time.time<this._lastUpdate+this._updateThrottle)){var a=this._updateThrottle;this._updateThrottleReset=a>=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var b=this._parentBounds.width,d=this._parentBounds.height,e=this.getParentBounds(this._parentBounds),f=e.width!==b||e.height!==d,g=this.updateOrientationState();(f||g)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,e),this.updateLayout(),this.signalSizeChange());var h=2*this._updateThrottle;this._updateThrottle<a&&(h=Math.min(a,this._updateThrottleReset)),this._updateThrottle=c.Math.clamp(h,25,this.trackParentInterval),this._lastUpdate=this.game.time.time}},pauseUpdate:function(){this.preUpdate(),this._updateThrottle=this.trackParentInterval},updateDimensions:function(a,b,c){this.width=a*this.parentScaleFactor.x,this.height=b*this.parentScaleFactor.y,this.game.width=this.width,this.game.height=this.height,this.sourceAspectRatio=this.width/this.height,this.updateScalingAndBounds(),c&&(this.game.renderer.resize(this.width,this.height),this.game.camera.setSize(this.width,this.height),this.game.world.resize(this.width,this.height))},updateScalingAndBounds:function(){this.scaleFactor.x=this.game.width/this.width,this.scaleFactor.y=this.game.height/this.height,this.scaleFactorInversed.x=this.width/this.game.width,this.scaleFactorInversed.y=this.height/this.game.height,this.aspectRatio=this.width/this.height,this.game.canvas&&this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.game.input&&this.game.input.scale&&this.game.input.scale.setTo(this.scaleFactor.x,this.scaleFactor.y)},forceOrientation:function(a,b){void 0===b&&(b=!1),this.forceLandscape=a,this.forcePortrait=b,this.queueUpdate(!0)},classifyOrientation:function(a){return"portrait-primary"===a||"portrait-secondary"===a?"portrait":"landscape-primary"===a||"landscape-secondary"===a?"landscape":null},updateOrientationState:function(){var a=this.screenOrientation,b=this.incorrectOrientation;this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.incorrectOrientation=this.forceLandscape&&!this.isLandscape||this.forcePortrait&&!this.isPortrait;var c=a!==this.screenOrientation,d=b!==this.incorrectOrientation;return d&&(this.incorrectOrientation?this.enterIncorrectOrientation.dispatch():this.leaveIncorrectOrientation.dispatch()),(c||d)&&this.onOrientationChange.dispatch(this,a,b),c||d},orientationChange:function(a){this.event=a,this.queueUpdate(!0)},windowResize:function(a){this.event=a,this.queueUpdate(!0)},scrollTop:function(){var a=this.compatibility.scrollTo;a&&window.scrollTo(a.x,a.y)},refresh:function(){this.scrollTop(),this.queueUpdate(!0)},updateLayout:function(){var a=this.currentScaleMode;if(a===c.ScaleManager.RESIZE)return void this.reflowGame();if(this.scrollTop(),this.compatibility.forceMinimumDocumentHeight&&(document.documentElement.style.minHeight=window.innerHeight+"px"),this.incorrectOrientation?this.setMaximum():a===c.ScaleManager.EXACT_FIT?this.setExactFit():a===c.ScaleManager.SHOW_ALL?!this.isFullScreen&&this.boundingParent&&this.compatibility.canExpandParent?(this.setShowAll(!0),this.resetCanvas(),this.setShowAll()):this.setShowAll():a===c.ScaleManager.NO_SCALE?(this.width=this.game.width,this.height=this.game.height):a===c.ScaleManager.USER_SCALE&&(this.width=this.game.width*this._userScaleFactor.x-this._userScaleTrim.x,this.height=this.game.height*this._userScaleFactor.y-this._userScaleTrim.y),!this.compatibility.canExpandParent&&(a===c.ScaleManager.SHOW_ALL||a===c.ScaleManager.USER_SCALE)){var b=this.getParentBounds(this._tempBounds);this.width=Math.min(this.width,b.width),this.height=Math.min(this.height,b.height)}this.width=0|this.width,this.height=0|this.height,this.reflowCanvas()},getParentBounds:function(a){var b=a||new c.Rectangle,d=this.boundingParent,e=this.dom.visualBounds,f=this.dom.layoutBounds;if(d){var g=d.getBoundingClientRect();b.setTo(g.left,g.top,g.width,g.height);var h=this.windowConstraints;if(h.right){var i="layout"===h.right?f:e;b.right=Math.min(b.right,i.width)}if(h.bottom){var i="layout"===h.bottom?f:e;b.bottom=Math.min(b.bottom,i.height)}}else b.setTo(0,0,e.width,e.height);return b.setTo(Math.round(b.x),Math.round(b.y),Math.round(b.width),Math.round(b.height)),b},alignCanvas:function(a,b){var c=this.getParentBounds(this._tempBounds),d=this.game.canvas,e=this.margin;if(a){e.left=e.right=0;var f=d.getBoundingClientRect();if(this.width<c.width&&!this.incorrectOrientation){var g=f.left-c.x,h=c.width/2-this.width/2;h=Math.max(h,0);var i=h-g;e.left=Math.round(i)}d.style.marginLeft=e.left+"px",0!==e.left&&(e.right=-(c.width-f.width-e.left),d.style.marginRight=e.right+"px")}if(b){e.top=e.bottom=0;var f=d.getBoundingClientRect();if(this.height<c.height&&!this.incorrectOrientation){var g=f.top-c.y,h=c.height/2-this.height/2;h=Math.max(h,0);var i=h-g;e.top=Math.round(i)}d.style.marginTop=e.top+"px",0!==e.top&&(e.bottom=-(c.height-f.height-e.top),d.style.marginBottom=e.bottom+"px")}e.x=e.left,e.y=e.top},reflowGame:function(){this.resetCanvas("","");var a=this.getParentBounds(this._tempBounds);this.updateDimensions(a.width,a.height,!0)},reflowCanvas:function(){this.incorrectOrientation||(this.width=c.Math.clamp(this.width,this.minWidth||0,this.maxWidth||this.width),this.height=c.Math.clamp(this.height,this.minHeight||0,this.maxHeight||this.height)),this.resetCanvas(),this.compatibility.noMargins||(this.isFullScreen&&this._createdFullScreenTarget?this.alignCanvas(!0,!0):this.alignCanvas(this.pageAlignHorizontally,this.pageAlignVertically)),this.updateScalingAndBounds()},resetCanvas:function(a,b){void 0===a&&(a=this.width+"px"),void 0===b&&(b=this.height+"px");var c=this.game.canvas;this.compatibility.noMargins||(c.style.marginLeft="",c.style.marginTop="",c.style.marginRight="",c.style.marginBottom=""),c.style.width=a,c.style.height=b},queueUpdate:function(a){a&&(this._parentBounds.width=0,this._parentBounds.height=0),this._updateThrottle=this._updateThrottleReset},reset:function(a){a&&this.grid.reset()},setMaximum:function(){this.width=this.dom.visualBounds.width,this.height=this.dom.visualBounds.height},setShowAll:function(a){var b,c=this.getParentBounds(this._tempBounds),d=c.width,e=c.height;b=a?Math.max(e/this.game.height,d/this.game.width):Math.min(e/this.game.height,d/this.game.width),this.width=Math.round(this.game.width*b),this.height=Math.round(this.game.height*b)},setExactFit:function(){var a=this.getParentBounds(this._tempBounds);this.width=a.width,this.height=a.height,this.isFullScreen||(this.maxWidth&&(this.width=Math.min(this.width,this.maxWidth)),this.maxHeight&&(this.height=Math.min(this.height,this.maxHeight)))},createFullScreenTarget:function(){var a=document.createElement("div");return a.style.margin="0",a.style.padding="0",a.style.background="#000",a},startFullScreen:function(a,b){if(this.isFullScreen)return!1;if(!this.compatibility.supportsFullScreen){var d=this;return void setTimeout(function(){d.fullScreenError()},10)}if("when-not-mouse"===this.compatibility.clickTrampoline){var e=this.game.input;if(e.activePointer&&e.activePointer!==e.mousePointer&&(b||b!==!1))return void e.activePointer.addClickTrampoline("startFullScreen",this.startFullScreen,this,[a,!1])}"undefined"!=typeof a&&this.game.renderType===c.CANVAS&&(this.game.stage.smoothed=a);var f=this.fullScreenTarget;f||(this.cleanupCreatedTarget(),this._createdFullScreenTarget=this.createFullScreenTarget(),f=this._createdFullScreenTarget);var g={targetElement:f};if(this.onFullScreenInit.dispatch(this,g),this._createdFullScreenTarget){var h=this.game.canvas,i=h.parentNode;i.insertBefore(f,h),f.appendChild(h)}return this.game.device.fullscreenKeyboard?f[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT):f[this.game.device.requestFullscreen](),!0},stopFullScreen:function(){return this.isFullScreen&&this.compatibility.supportsFullScreen?(document[this.game.device.cancelFullscreen](),!0):!1},cleanupCreatedTarget:function(){var a=this._createdFullScreenTarget;if(a&&a.parentNode){var b=a.parentNode;b.insertBefore(this.game.canvas,a),b.removeChild(a)}this._createdFullScreenTarget=null},prepScreenMode:function(a){var b=!!this._createdFullScreenTarget,d=this._createdFullScreenTarget||this.fullScreenTarget;a?(b||this.fullScreenScaleMode===c.ScaleManager.EXACT_FIT)&&d!==this.game.canvas&&(this._fullScreenRestore={targetWidth:d.style.width,targetHeight:d.style.height},d.style.width="100%",d.style.height="100%"):(this._fullScreenRestore&&(d.style.width=this._fullScreenRestore.targetWidth,d.style.height=this._fullScreenRestore.targetHeight,this._fullScreenRestore=null),this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.resetCanvas())},fullScreenChange:function(a){this.event=a,this.isFullScreen?(this.prepScreenMode(!0),this.updateLayout(),this.queueUpdate(!0),this.enterFullScreen.dispatch(this.width,this.height)):(this.prepScreenMode(!1),this.cleanupCreatedTarget(),this.updateLayout(),this.queueUpdate(!0),this.leaveFullScreen.dispatch(this.width,this.height)),this.onFullScreenChange.dispatch(this)},fullScreenError:function(a){this.event=a,this.cleanupCreatedTarget(),console.warn("Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API"),this.onFullScreenError.dispatch(this)},scaleSprite:function(a,b,c,d){if(void 0===b&&(b=this.width),void 0===c&&(c=this.height),void 0===d&&(d=!1),!a||!a.scale)return a;if(a.scale.x=1,a.scale.y=1,a.width<=0||a.height<=0||0>=b||0>=c)return a;var e=b,f=a.height*b/a.width,g=a.width*c/a.height,h=c,i=g>b;return i=i?d:!d,i?(a.width=Math.floor(e),a.height=Math.floor(f)):(a.width=Math.floor(g),a.height=Math.floor(h)),a},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},c.ScaleManager.prototype.constructor=c.ScaleManager,Object.defineProperty(c.ScaleManager.prototype,"boundingParent",{get:function(){if(this.parentIsWindow||this.isFullScreen&&!this._createdFullScreenTarget)return null;var a=this.game.canvas&&this.game.canvas.parentNode;return a||null}}),Object.defineProperty(c.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(a){return a!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=a),this._scaleMode}}),Object.defineProperty(c.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(a){return a!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=a,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=a),this._fullScreenScaleMode}}),Object.defineProperty(c.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(c.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(a){a!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=a,this.queueUpdate(!0))}}),Object.defineProperty(c.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(a){a!==this._pageAlignVertically&&(this._pageAlignVertically=a,this.queueUpdate(!0))}}),Object.defineProperty(c.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(c.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(c.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(c.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(c.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),c.Game=function(a,b,d,e,f,g,h,i){return this.id=c.GAMES.push(this)-1,this.config=null,this.physicsConfig=i,this.parent="",this.width=800,this.height=600,this.resolution=1,this._width=800,this._height=600,this.transparent=!1,this.antialias=!0,this.preserveDrawingBuffer=!1,this.renderer=null,this.renderType=c.AUTO,this.state=null,this.isBooted=!1,this.isRunning=!1,this.raf=null,this.add=null,this.make=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.net=null,this.scale=null,this.sound=null,this.stage=null,this.time=null,this.tweens=null,this.world=null,this.physics=null,this.plugins=null,this.rnd=null,this.device=c.Device,this.camera=null,this.canvas=null,this.context=null,this.debug=null,this.particles=null,this.create=null,this.lockRender=!1,this.stepping=!1,this.pendingStep=!1,this.stepCount=0,this.onPause=null,this.onResume=null,this.onBlur=null,this.onFocus=null,this._paused=!1,this._codePaused=!1,this.currentUpdateID=0,this.updatesThisFrame=1,this._deltaTime=0,this._lastCount=0,this._spiraling=0,this._kickstart=!0,this.fpsProblemNotifier=new c.Signal,this.forceSingleUpdate=!1,this._nextFpsNotification=0,1===arguments.length&&"object"==typeof arguments[0]?this.parseConfig(arguments[0]):(this.config={enableDebug:!0},"undefined"!=typeof a&&(this._width=a),"undefined"!=typeof b&&(this._height=b),"undefined"!=typeof d&&(this.renderType=d),"undefined"!=typeof e&&(this.parent=e),"undefined"!=typeof g&&(this.transparent=g),"undefined"!=typeof h&&(this.antialias=h),this.rnd=new c.RandomDataGenerator([(Date.now()*Math.random()).toString()]),this.state=new c.StateManager(this,f)),this.device.whenReady(this.boot,this),this},c.Game.prototype={parseConfig:function(a){this.config=a,void 0===a.enableDebug&&(this.config.enableDebug=!0),a.width&&(this._width=a.width),a.height&&(this._height=a.height),a.renderer&&(this.renderType=a.renderer),a.parent&&(this.parent=a.parent),a.transparent&&(this.transparent=a.transparent),a.antialias&&(this.antialias=a.antialias),a.resolution&&(this.resolution=a.resolution),a.preserveDrawingBuffer&&(this.preserveDrawingBuffer=a.preserveDrawingBuffer),a.physicsConfig&&(this.physicsConfig=a.physicsConfig);var b=[(Date.now()*Math.random()).toString()];a.seed&&(b=a.seed),this.rnd=new c.RandomDataGenerator(b);var d=null;a.state&&(d=a.state),this.state=new c.StateManager(this,d)},boot:function(){this.isBooted||(this.onPause=new c.Signal,this.onResume=new c.Signal,this.onBlur=new c.Signal,this.onFocus=new c.Signal,this.isBooted=!0,this.math=c.Math,this.scale=new c.ScaleManager(this,this._width,this._height),this.stage=new c.Stage(this),this.setUpRenderer(),this.world=new c.World(this),this.add=new c.GameObjectFactory(this),this.make=new c.GameObjectCreator(this),this.cache=new c.Cache(this),this.load=new c.Loader(this),this.time=new c.Time(this),this.tweens=new c.TweenManager(this),this.input=new c.Input(this),this.sound=new c.SoundManager(this),this.physics=new c.Physics(this,this.physicsConfig),this.particles=new c.Particles(this),this.create=new c.Create(this),this.plugins=new c.PluginManager(this),this.net=new c.Net(this),this.time.boot(),this.stage.boot(),this.world.boot(),this.scale.boot(),this.input.boot(),this.sound.boot(),this.state.boot(),this.config.enableDebug?(this.debug=new c.Utils.Debug(this),this.debug.boot()):this.debug={preUpdate:function(){},update:function(){},reset:function(){}},this.showDebugHeader(),this.isRunning=!0,this.raf=this.config&&this.config.forceSetTimeOut?new c.RequestAnimationFrame(this,this.config.forceSetTimeOut):new c.RequestAnimationFrame(this,!1),this._kickstart=!0,window.focus&&(!window.PhaserGlobal||window.PhaserGlobal&&!window.PhaserGlobal.stopFocus)&&window.focus(),this.raf.start())},showDebugHeader:function(){if(!window.PhaserGlobal||!window.PhaserGlobal.hideBanner){var a=c.VERSION,b="Canvas",d="HTML Audio",e=1;if(this.renderType===c.WEBGL?(b="WebGL",e++):this.renderType==c.HEADLESS&&(b="Headless"),this.device.webAudio&&(d="WebAudio",e++),this.device.chrome){for(var f=["%c %c %c Phaser v"+a+" | Pixi.js "+PIXI.VERSION+" | "+b+" | "+d+"  %c %c %c http://phaser.io %c♥%c♥%c♥","background: #9854d8","background: #6c2ca7","color: #ffffff; background: #450f78;","background: #6c2ca7","background: #9854d8","background: #ffffff"],g=0;3>g;g++)f.push(e>g?"color: #ff2424; background: #fff":"color: #959595; background: #fff");console.log.apply(console,f)}else window.console&&console.log("Phaser v"+a+" | Pixi.js "+PIXI.VERSION+" | "+b+" | "+d+" | http://phaser.io")}},setUpRenderer:function(){if(this.canvas=this.config.canvasID?c.Canvas.create(this.width,this.height,this.config.canvasID):c.Canvas.create(this.width,this.height),this.config.canvasStyle?this.canvas.style=this.config.canvasStyle:this.canvas.style["-webkit-full-screen"]="width: 100%; height: 100%",this.device.cocoonJS&&(this.canvas.screencanvas=this.renderType===c.CANVAS?!0:!1),this.renderType===c.HEADLESS||this.renderType===c.CANVAS||this.renderType===c.AUTO&&this.device.webGL===!1){if(!this.device.canvas)throw new Error("Phaser.Game - cannot create Canvas or WebGL context, aborting.");this.renderType===c.AUTO&&(this.renderType=c.CANVAS),this.renderer=new PIXI.CanvasRenderer(this.width,this.height,{view:this.canvas,transparent:this.transparent,resolution:this.resolution,clearBeforeRender:!0}),this.context=this.renderer.context}else this.renderType=c.WEBGL,this.renderer=new PIXI.WebGLRenderer(this.width,this.height,{view:this.canvas,transparent:this.transparent,resolution:this.resolution,antialias:this.antialias,preserveDrawingBuffer:this.preserveDrawingBuffer}),this.context=null,this.canvas.addEventListener("webglcontextlost",this.contextLost.bind(this),!1),this.canvas.addEventListener("webglcontextrestored",this.contextRestored.bind(this),!1);this.renderType!==c.HEADLESS&&(this.stage.smoothed=this.antialias,c.Canvas.addToDOM(this.canvas,this.parent,!1),c.Canvas.setTouchAction(this.canvas))},contextLost:function(a){a.preventDefault(),this.renderer.contextLost=!0},contextRestored:function(){this.renderer.initContext(),this.cache.clearGLTextures(),this.renderer.contextLost=!1
+},update:function(a){if(this.time.update(a),this._kickstart)return this.updateLogic(1/this.time.desiredFps),this.stage.updateTransform(),this.updateRender(this.time.slowMotion*this.time.desiredFps),void(this._kickstart=!1);if(this._spiraling>1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.updateRender(this.time.slowMotion*this.time.desiredFps);else{var b=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*b,this.time.elapsed),0);var c=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/b),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame));this._deltaTime>=b&&(this._deltaTime-=b,this.currentUpdateID=c,this.updateLogic(1/this.time.desiredFps),this.stage.updateTransform(),c++,!this.forceSingleUpdate||1!==c););c>this._lastCount?this._spiraling++:c<this._lastCount&&(this._spiraling=0),this._lastCount=c,this.updateRender(this._deltaTime/b)}},updateLogic:function(a){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(),this.debug.preUpdate()):(this.stepping&&(this.pendingStep=!0),this.scale.preUpdate(),this.debug.preUpdate(),this.world.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(a),this.plugins.preUpdate(a),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(a),this.sound.update(),this.input.update(),this.physics.update(),this.particles.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate())},updateRender:function(a){this.lockRender||(this.state.preRender(a),this.renderer.render(this.stage),this.plugins.render(a),this.state.render(a),this.plugins.postRender(a))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.state=null,this.cache=null,this.input=null,this.load=null,this.sound=null,this.stage=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),c.Canvas.removeFromDOM(this.canvas),c.GAMES[this.id]=null},gamePaused:function(a){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.setMute(),this.onPause.dispatch(a),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(a){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.unsetMute(),this.onResume.dispatch(a),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(a){this.onBlur.dispatch(a),this.stage.disableVisibilityChange||this.gamePaused(a)},focusGain:function(a){this.onFocus.dispatch(a),this.stage.disableVisibilityChange||this.gameResumed(a)}},c.Game.prototype.constructor=c.Game,Object.defineProperty(c.Game.prototype,"paused",{get:function(){return this._paused},set:function(a){a===!0?(this._paused===!1&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),c.Input=function(a){this.game=a,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.pollRate=0,this.enabled=!0,this.multiInputOverride=c.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new c.ArraySet,this._localPoint=new c.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},c.Input.MOUSE_OVERRIDES_TOUCH=0,c.Input.TOUCH_OVERRIDES_MOUSE=1,c.Input.MOUSE_TOUCH_COMBINE=2,c.Input.MAX_POINTERS=10,c.Input.prototype={boot:function(){this.mousePointer=new c.Pointer(this.game,0),this.addPointer(),this.addPointer(),this.mouse=new c.Mouse(this.game),this.touch=new c.Touch(this.game),this.mspointer=new c.MSPointer(this.game),c.Keyboard&&(this.keyboard=new c.Keyboard(this.game)),c.Gamepad&&(this.gamepad=new c.Gamepad(this.game)),this.onDown=new c.Signal,this.onUp=new c.Signal,this.onTap=new c.Signal,this.onHold=new c.Signal,this.scale=new c.Point(1,1),this.speed=new c.Point,this.position=new c.Point,this._oldPosition=new c.Point,this.circle=new c.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=document.createElement("canvas"),this.hitCanvas.width=1,this.hitCanvas.height=1,this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var a=this;this._onClickTrampoline=function(b){a.onClickTrampoline(b)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],this.game.canvas.removeEventListener("click",this._onClickTrampoline)},addMoveCallback:function(a,b){this.moveCallbacks.push({callback:a,context:b})},deleteMoveCallback:function(a,b){for(var c=this.moveCallbacks.length;c--;)if(this.moveCallbacks[c].callback===a&&this.moveCallbacks[c].context===b)return void this.moveCallbacks.splice(c,1)},addPointer:function(){if(this.pointers.length>=c.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+c.Input.MAX_POINTERS+" pointers reached."),null;var a=this.pointers.length+1,b=new c.Pointer(this.game,a);return this.pointers.push(b),this["pointer"+a]=b,b},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter<this.pollRate)return void this._pollCounter++;this.speed.x=this.position.x-this._oldPosition.x,this.speed.y=this.position.y-this._oldPosition.y,this._oldPosition.copyFrom(this.position),this.mousePointer.update(),this.gamepad&&this.gamepad.active&&this.gamepad.update();for(var a=0;a<this.pointers.length;a++)this.pointers[a].update();this._pollCounter=0},reset:function(a){if(this.game.isBooted&&!this.resetLocked){void 0===a&&(a=!1),this.mousePointer.reset(),this.keyboard&&this.keyboard.reset(a),this.gamepad&&this.gamepad.reset();for(var b=0;b<this.pointers.length;b++)this.pointers[b].reset();"none"!==this.game.canvas.style.cursor&&(this.game.canvas.style.cursor="inherit"),a&&(this.onDown.dispose(),this.onUp.dispose(),this.onTap.dispose(),this.onHold.dispose(),this.onDown=new c.Signal,this.onUp=new c.Signal,this.onTap=new c.Signal,this.onHold=new c.Signal,this.moveCallbacks=[]),this._pollCounter=0}},resetSpeed:function(a,b){this._oldPosition.setTo(a,b),this.speed.setTo(0,0)},startPointer:function(a){if(this.maxPointers>=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(a);if(!this.pointer2.active)return this.pointer2.start(a);for(var b=2;b<this.pointers.length;b++){var c=this.pointers[b];if(!c.active)return c.start(a)}return null},updatePointer:function(a){if(this.pointer1.active&&this.pointer1.identifier===a.identifier)return this.pointer1.move(a);if(this.pointer2.active&&this.pointer2.identifier===a.identifier)return this.pointer2.move(a);for(var b=2;b<this.pointers.length;b++){var c=this.pointers[b];if(c.active&&c.identifier===a.identifier)return c.move(a)}return null},stopPointer:function(a){if(this.pointer1.active&&this.pointer1.identifier===a.identifier)return this.pointer1.stop(a);if(this.pointer2.active&&this.pointer2.identifier===a.identifier)return this.pointer2.stop(a);for(var b=2;b<this.pointers.length;b++){var c=this.pointers[b];if(c.active&&c.identifier===a.identifier)return c.stop(a)}return null},countActivePointers:function(a){void 0===a&&(a=this.pointers.length);for(var b=a,c=0;c<this.pointers.length&&b>0;c++){var d=this.pointers[c];d.active&&b--}return a-b},getPointer:function(a){void 0===a&&(a=!1);for(var b=0;b<this.pointers.length;b++){var c=this.pointers[b];if(c.active===a)return c}return null},getPointerFromIdentifier:function(a){for(var b=0;b<this.pointers.length;b++){var c=this.pointers[b];if(c.identifier===a)return c}return null},getPointerFromId:function(a){for(var b=0;b<this.pointers.length;b++){var c=this.pointers[b];if(c.pointerId===a)return c}return null},getLocalPosition:function(a,b,d){void 0===d&&(d=new c.Point);var e=a.worldTransform,f=1/(e.a*e.d+e.c*-e.b);return d.setTo(e.d*f*b.x+-e.c*f*b.y+(e.ty*e.c-e.tx*e.d)*f,e.a*f*b.y+-e.b*f*b.x+(-e.ty*e.a+e.tx*e.b)*f)},hitTest:function(a,b,d){if(!a.worldVisible)return!1;if(this.getLocalPosition(a,b,this._localPoint),d.copyFrom(this._localPoint),a.hitArea&&a.hitArea.contains)return a.hitArea.contains(this._localPoint.x,this._localPoint.y);if(a instanceof c.TileSprite){var e=a.width,f=a.height,g=-e*a.anchor.x;if(this._localPoint.x>=g&&this._localPoint.x<g+e){var h=-f*a.anchor.y;if(this._localPoint.y>=h&&this._localPoint.y<h+f)return!0}}else if(a instanceof PIXI.Sprite){var e=a.texture.frame.width,f=a.texture.frame.height,g=-e*a.anchor.x;if(this._localPoint.x>=g&&this._localPoint.x<g+e){var h=-f*a.anchor.y;if(this._localPoint.y>=h&&this._localPoint.y<h+f)return!0}}else if(a instanceof c.Graphics)for(var i=0;i<a.graphicsData.length;i++){var j=a.graphicsData[i];if(j.fill&&j.shape&&j.shape.contains(this._localPoint.x,this._localPoint.y))return!0}for(var i=0,k=a.children.length;k>i;i++)if(this.hitTest(a.children[i],b,d))return!0;return!1},onClickTrampoline:function(){this.activePointer.processClickTrampolines()}},c.Input.prototype.constructor=c.Input,Object.defineProperty(c.Input.prototype,"x",{get:function(){return this._x},set:function(a){this._x=Math.floor(a)}}),Object.defineProperty(c.Input.prototype,"y",{get:function(){return this._y},set:function(a){this._y=Math.floor(a)}}),Object.defineProperty(c.Input.prototype,"pollLocked",{get:function(){return this.pollRate>0&&this._pollCounter<this.pollRate}}),Object.defineProperty(c.Input.prototype,"totalInactivePointers",{get:function(){return this.pointers.length-this.countActivePointers()}}),Object.defineProperty(c.Input.prototype,"totalActivePointers",{get:function(){return this.countActivePointers()}}),Object.defineProperty(c.Input.prototype,"worldX",{get:function(){return this.game.camera.view.x+this.x}}),Object.defineProperty(c.Input.prototype,"worldY",{get:function(){return this.game.camera.view.y+this.y}}),c.Mouse=function(a){this.game=a,this.input=a.input,this.callbackContext=this.game,this.mouseDownCallback=null,this.mouseUpCallback=null,this.mouseOutCallback=null,this.mouseOverCallback=null,this.mouseWheelCallback=null,this.capture=!1,this.button=-1,this.wheelDelta=0,this.enabled=!0,this.locked=!1,this.stopOnGameOut=!1,this.pointerLock=new c.Signal,this.event=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null,this._onMouseOut=null,this._onMouseOver=null,this._onMouseWheel=null,this._wheelEvent=null},c.Mouse.NO_BUTTON=-1,c.Mouse.LEFT_BUTTON=0,c.Mouse.MIDDLE_BUTTON=1,c.Mouse.RIGHT_BUTTON=2,c.Mouse.BACK_BUTTON=3,c.Mouse.FORWARD_BUTTON=4,c.Mouse.WHEEL_UP=1,c.Mouse.WHEEL_DOWN=-1,c.Mouse.prototype={start:function(){if((!this.game.device.android||this.game.device.chrome!==!1)&&null===this._onMouseDown){var b=this;this._onMouseDown=function(a){return b.onMouseDown(a)},this._onMouseMove=function(a){return b.onMouseMove(a)},this._onMouseUp=function(a){return b.onMouseUp(a)},this._onMouseUpGlobal=function(a){return b.onMouseUpGlobal(a)},this._onMouseOut=function(a){return b.onMouseOut(a)},this._onMouseOver=function(a){return b.onMouseOver(a)},this._onMouseWheel=function(a){return b.onMouseWheel(a)};var c=this.game.canvas;c.addEventListener("mousedown",this._onMouseDown,!0),c.addEventListener("mousemove",this._onMouseMove,!0),c.addEventListener("mouseup",this._onMouseUp,!0),this.game.device.cocoonJS||(window.addEventListener("mouseup",this._onMouseUpGlobal,!0),c.addEventListener("mouseover",this._onMouseOver,!0),c.addEventListener("mouseout",this._onMouseOut,!0));var d=this.game.device.wheelEvent;d&&(c.addEventListener(d,this._onMouseWheel,!0),"mousewheel"===d?this._wheelEvent=new a(-1/40,1):"DOMMouseScroll"===d&&(this._wheelEvent=new a(1,1)))}},onMouseDown:function(a){this.event=a,this.capture&&a.preventDefault(),this.mouseDownCallback&&this.mouseDownCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=0,this.input.mousePointer.start(a))},onMouseMove:function(a){this.event=a,this.capture&&a.preventDefault(),this.mouseMoveCallback&&this.mouseMoveCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=0,this.input.mousePointer.move(a))},onMouseUp:function(a){this.event=a,this.capture&&a.preventDefault(),this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=0,this.input.mousePointer.stop(a))},onMouseUpGlobal:function(a){this.input.mousePointer.withinGame||(this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,a),a.identifier=0,this.input.mousePointer.stop(a))},onMouseOut:function(a){this.event=a,this.capture&&a.preventDefault(),this.input.mousePointer.withinGame=!1,this.mouseOutCallback&&this.mouseOutCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&this.stopOnGameOut&&(a.identifier=0,this.input.mousePointer.stop(a))},onMouseWheel:function(a){this._wheelEvent&&(a=this._wheelEvent.bindEvent(a)),this.event=a,this.capture&&a.preventDefault(),this.wheelDelta=c.Math.clamp(-a.deltaY,-1,1),this.mouseWheelCallback&&this.mouseWheelCallback.call(this.callbackContext,a)},onMouseOver:function(a){this.event=a,this.capture&&a.preventDefault(),this.input.mousePointer.withinGame=!0,this.mouseOverCallback&&this.mouseOverCallback.call(this.callbackContext,a),!this.input.enabled||!this.enabled},requestPointerLock:function(){if(this.game.device.pointerLock){var a=this.game.canvas;a.requestPointerLock=a.requestPointerLock||a.mozRequestPointerLock||a.webkitRequestPointerLock,a.requestPointerLock();var b=this;this._pointerLockChange=function(a){return b.pointerLockChange(a)},document.addEventListener("pointerlockchange",this._pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},pointerLockChange:function(a){var b=this.game.canvas;document.pointerLockElement===b||document.mozPointerLockElement===b||document.webkitPointerLockElement===b?(this.locked=!0,this.pointerLock.dispatch(!0,a)):(this.locked=!1,this.pointerLock.dispatch(!1,a))},releasePointerLock:function(){document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock(),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)},stop:function(){var a=this.game.canvas;a.removeEventListener("mousedown",this._onMouseDown,!0),a.removeEventListener("mousemove",this._onMouseMove,!0),a.removeEventListener("mouseup",this._onMouseUp,!0),a.removeEventListener("mouseover",this._onMouseOver,!0),a.removeEventListener("mouseout",this._onMouseOut,!0);var b=this.game.device.wheelEvent;b&&a.removeEventListener(b,this._onMouseWheel,!0),window.removeEventListener("mouseup",this._onMouseUpGlobal,!0),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},c.Mouse.prototype.constructor=c.Mouse,a.prototype={},a.prototype.constructor=a,a.prototype.bindEvent=function(b){if(!a._stubsGenerated&&b){var c=function(a){return function(){var b=this.originalEvent[a];return"function"!=typeof b?b:b.bind(this.originalEvent)}};for(var d in b)d in a.prototype||Object.defineProperty(a.prototype,d,{get:c(d)});a._stubsGenerated=!0}return this.originalEvent=b,this},Object.defineProperties(a.prototype,{type:{value:"wheel"},deltaMode:{get:function(){return this._deltaMode}},deltaY:{get:function(){return this._scaleFactor*(this.originalEvent.wheelDelta||this.originalEvent.detail)||0}},deltaX:{get:function(){return this._scaleFactor*this.originalEvent.wheelDeltaX||0}},deltaZ:{value:0}}),c.MSPointer=function(a){this.game=a,this.input=a.input,this.callbackContext=this.game,this.pointerDownCallback=null,this.pointerMoveCallback=null,this.pointerUpCallback=null,this.capture=!0,this.button=-1,this.event=null,this.enabled=!0,this._onMSPointerDown=null,this._onMSPointerMove=null,this._onMSPointerUp=null},c.MSPointer.prototype={start:function(){if(null===this._onMSPointerDown){var a=this;if(this.game.device.mspointer){this._onMSPointerDown=function(b){return a.onPointerDown(b)},this._onMSPointerMove=function(b){return a.onPointerMove(b)},this._onMSPointerUp=function(b){return a.onPointerUp(b)};var b=this.game.canvas;b.addEventListener("MSPointerDown",this._onMSPointerDown,!1),b.addEventListener("MSPointerMove",this._onMSPointerMove,!1),b.addEventListener("MSPointerUp",this._onMSPointerUp,!1),b.addEventListener("pointerDown",this._onMSPointerDown,!1),b.addEventListener("pointerMove",this._onMSPointerMove,!1),b.addEventListener("pointerUp",this._onMSPointerUp,!1),b.style["-ms-content-zooming"]="none",b.style["-ms-touch-action"]="none"}}},onPointerDown:function(a){this.event=a,this.capture&&a.preventDefault(),this.pointerDownCallback&&this.pointerDownCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=a.pointerId,"mouse"===a.pointerType||4===a.pointerType?this.input.mousePointer.start(a):this.input.startPointer(a))},onPointerMove:function(a){this.event=a,this.capture&&a.preventDefault(),this.pointerMoveCallback&&this.pointerMoveCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=a.pointerId,"mouse"===a.pointerType||4===a.pointerType?this.input.mousePointer.move(a):this.input.updatePointer(a))},onPointerUp:function(a){this.event=a,this.capture&&a.preventDefault(),this.pointerUpCallback&&this.pointerUpCallback.call(this.callbackContext,a),this.input.enabled&&this.enabled&&(a.identifier=a.pointerId,"mouse"===a.pointerType||4===a.pointerType?this.input.mousePointer.stop(a):this.input.stopPointer(a))},stop:function(){var a=this.game.canvas;a.removeEventListener("MSPointerDown",this._onMSPointerDown),a.removeEventListener("MSPointerMove",this._onMSPointerMove),a.removeEventListener("MSPointerUp",this._onMSPointerUp),a.removeEventListener("pointerDown",this._onMSPointerDown),a.removeEventListener("pointerMove",this._onMSPointerMove),a.removeEventListener("pointerUp",this._onMSPointerUp)}},c.MSPointer.prototype.constructor=c.MSPointer,c.DeviceButton=function(a,b){this.parent=a,this.game=a.game,this.event=null,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.duration=0,this.timeUp=0,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1,this.value=0,this.buttonCode=b,this.onDown=new c.Signal,this.onUp=new c.Signal,this.onFloat=new c.Signal},c.DeviceButton.prototype={start:function(a,b){this.isDown||(this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this.event=a,this.value=b,a&&(this.altKey=a.altKey,this.shiftKey=a.shiftKey,this.ctrlKey=a.ctrlKey),this.onDown.dispatch(this,b))},stop:function(a,b){this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.event=a,this.value=b,a&&(this.altKey=a.altKey,this.shiftKey=a.shiftKey,this.ctrlKey=a.ctrlKey),this.onUp.dispatch(this,b))},padFloat:function(a){this.value=a,this.onFloat.dispatch(this,a)},justPressed:function(a){return a=a||250,this.isDown&&this.timeDown+a>this.game.time.time},justReleased:function(a){return a=a||250,this.isUp&&this.timeUp+a>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},c.DeviceButton.prototype.constructor=c.DeviceButton,Object.defineProperty(c.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),c.Pointer=function(a,b){this.game=a,this.id=b,this.type=c.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.target=null,this.button=null,this.leftButton=new c.DeviceButton(this,c.Pointer.LEFT_BUTTON),this.middleButton=new c.DeviceButton(this,c.Pointer.MIDDLE_BUTTON),this.rightButton=new c.DeviceButton(this,c.Pointer.RIGHT_BUTTON),this.backButton=new c.DeviceButton(this,c.Pointer.BACK_BUTTON),this.forwardButton=new c.DeviceButton(this,c.Pointer.FORWARD_BUTTON),this.eraserButton=new c.DeviceButton(this,c.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===b,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.active=!1,this.dirty=!1,this.position=new c.Point,this.positionDown=new c.Point,this.positionUp=new c.Point,this.circle=new c.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},c.Pointer.NO_BUTTON=0,c.Pointer.LEFT_BUTTON=1,c.Pointer.RIGHT_BUTTON=2,c.Pointer.MIDDLE_BUTTON=4,c.Pointer.BACK_BUTTON=8,c.Pointer.FORWARD_BUTTON=16,c.Pointer.ERASER_BUTTON=32,c.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(a,b){c.Pointer.LEFT_BUTTON&a&&this.leftButton.start(b),c.Pointer.RIGHT_BUTTON&a&&this.rightButton.start(b),c.Pointer.MIDDLE_BUTTON&a&&this.middleButton.start(b),c.Pointer.BACK_BUTTON&a&&this.backButton.start(b),c.Pointer.FORWARD_BUTTON&a&&this.forwardButton.start(b),c.Pointer.ERASER_BUTTON&a&&this.eraserButton.start(b)},processButtonsUp:function(a,b){a===c.Mouse.LEFT_BUTTON&&this.leftButton.stop(b),a===c.Mouse.RIGHT_BUTTON&&this.rightButton.stop(b),a===c.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(b),a===c.Mouse.BACK_BUTTON&&this.backButton.stop(b),a===c.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(b),5===a&&this.eraserButton.stop(b)},updateButtons:function(a){this.button=a.button;var b="down"===a.type.toLowerCase().substr(-4);void 0!==a.buttons?b?this.processButtonsDown(a.buttons,a):this.processButtonsUp(a.button,a):b?this.leftButton.start(a):(this.leftButton.stop(a),this.rightButton.stop(a)),a.ctrlKey&&this.leftButton.isDown&&this.rightButton.start(a),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(a){return a.pointerId&&(this.pointerId=a.pointerId),this.identifier=a.identifier,this.target=a.target,this.isMouse?this.updateButtons(a):(this.isDown=!0,this.isUp=!1),this._history=[],this.active=!0,this.withinGame=!0,this.dirty=!1,this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(a,!0),this.positionDown.setTo(this.x,this.y),(this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&(this.game.input.x=this.x,this.game.input.y=this.y,this.game.input.position.setTo(this.x,this.y),this.game.input.onDown.dispatch(this,a),this.game.input.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){this.active&&(this.dirty&&(this.game.input.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),this._holdSent===!1&&this.duration>=this.game.input.holdRate&&((this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&this.game.input.onHold.dispatch(this),this._holdSent=!0),this.game.input.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+this.game.input.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>this.game.input.recordLimit&&this._history.shift()))},move:function(a,b){if(!this.game.input.pollLocked){if(void 0===b&&(b=!1),void 0!==a.button&&(this.button=a.button),b&&this.isMouse&&this.updateButtons(a),this.clientX=a.clientX,this.clientY=a.clientY,this.pageX=a.pageX,this.pageY=a.pageY,this.screenX=a.screenX,this.screenY=a.screenY,this.isMouse&&this.game.input.mouse.locked&&!b&&(this.rawMovementX=a.movementX||a.mozMovementX||a.webkitMovementX||0,this.rawMovementY=a.movementY||a.mozMovementY||a.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*this.game.input.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*this.game.input.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&(this.game.input.activePointer=this,this.game.input.x=this.x,this.game.input.y=this.y,this.game.input.position.setTo(this.game.input.x,this.game.input.y),this.game.input.circle.x=this.game.input.x,this.game.input.circle.y=this.game.input.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY),this.game.paused)return this;for(var d=this.game.input.moveCallbacks.length;d--;)this.game.input.moveCallbacks[d].callback.call(this.game.input.moveCallbacks[d].context,this,this.x,this.y,b);return null!==this.targetObject&&this.targetObject.isDragged===!0?this.targetObject.update(this)===!1&&(this.targetObject=null):this.game.input.interactiveItems.total>0&&this.processInteractiveObjects(b),this}},processInteractiveObjects:function(a){for(var b=Number.MAX_VALUE,c=-1,d=null,e=this.game.input.interactiveItems.first;e;)e.checked=!1,e.validForInput(c,b,!1)&&(e.checked=!0,(a&&e.checkPointerDown(this,!0)||!a&&e.checkPointerOver(this,!0))&&(b=e.sprite.renderOrderID,c=e.priorityID,d=e)),e=this.game.input.interactiveItems.next;for(var e=this.game.input.interactiveItems.first;e;)!e.checked&&e.validForInput(c,b,!0)&&(a&&e.checkPointerDown(this,!1)||!a&&e.checkPointerOver(this,!1))&&(b=e.sprite.renderOrderID,c=e.priorityID,d=e),e=this.game.input.interactiveItems.next;return null===d?this.targetObject&&(this.targetObject._pointerOutHandler(this),this.targetObject=null):null===this.targetObject?(this.targetObject=d,d._pointerOverHandler(this)):this.targetObject===d?d.update(this)===!1&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this),this.targetObject=d,this.targetObject._pointerOverHandler(this)),null!==this.targetObject},leave:function(a){this.withinGame=!1,this.move(a,!1)},stop:function(a){return this._stateReset&&this.withinGame?void a.preventDefault():(this.isMouse?this.updateButtons(a):(this.isDown=!1,this.isUp=!0),this.timeUp=this.game.time.time,(this.game.input.multiInputOverride===c.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===c.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===c.Input.TOUCH_OVERRIDES_MOUSE&&0===this.game.input.totalActivePointers)&&(this.game.input.onUp.dispatch(this,a),this.duration>=0&&this.duration<=this.game.input.tapRate&&(this.timeUp-this.previousTapTime<this.game.input.doubleTapRate?this.game.input.onTap.dispatch(this,!0):this.game.input.onTap.dispatch(this,!1),this.previousTapTime=this.timeUp)),this.id>0&&(this.active=!1),this.withinGame=!1,this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),this.isMouse===!1&&this.game.input.currentPointers--,this.game.input.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this)},justPressed:function(a){return a=a||this.game.input.justPressedRate,this.isDown===!0&&this.timeDown+a>this.game.time.time},justReleased:function(a){return a=a||this.game.input.justReleasedRate,this.isUp&&this.timeUp+a>this.game.time.time},addClickTrampoline:function(a,b,c,d){if(this.isDown){for(var e=this._clickTrampolines=this._clickTrampolines||[],f=0;f<e.length;f++)if(e[f].name===a){e.splice(f,1);break}e.push({name:a,targetObject:this.targetObject,callback:b,callbackContext:c,callbackArgs:d})}},processClickTrampolines:function(){var a=this._clickTrampolines;if(a){for(var b=0;b<a.length;b++){var c=a[b];c.targetObject===this._trampolineTargetObject&&c.callback.apply(c.callbackContext,c.callbackArgs)}this._clickTrampolines=null,this._trampolineTargetObject=null}},reset:function(){this.isMouse===!1&&(this.active=!1),this.pointerId=null,this.identifier=null,this.dirty=!1,this.totalTouches=0,this._holdSent=!1,this._history.length=0,this._stateReset=!0,this.resetButtons(),this.targetObject&&this.targetObject._releasedHandler(this),this.targetObject=null},resetMovement:function(){this.movementX=0,this.movementY=0}},c.Pointer.prototype.constructor=c.Pointer,Object.defineProperty(c.Pointer.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),Object.defineProperty(c.Pointer.prototype,"worldX",{get:function(){return this.game.world.camera.x+this.x}}),Object.defineProperty(c.Pointer.prototype,"worldY",{get:function(){return this.game.world.camera.y+this.y}}),c.Touch=function(a){this.game=a,this.enabled=!0,this.touchLockCallbacks=[],this.callbackContext=this.game,this.touchStartCallback=null,this.touchMoveCallback=null,this.touchEndCallback=null,this.touchEnterCallback=null,this.touchLeaveCallback=null,this.touchCancelCallback=null,this.preventDefault=!0,this.event=null,this._onTouchStart=null,this._onTouchMove=null,this._onTouchEnd=null,this._onTouchEnter=null,this._onTouchLeave=null,this._onTouchCancel=null,this._onTouchMove=null},c.Touch.prototype={start:function(){if(null===this._onTouchStart){var a=this;this.game.device.touch&&(this._onTouchStart=function(b){return a.onTouchStart(b)},this._onTouchMove=function(b){return a.onTouchMove(b)},this._onTouchEnd=function(b){return a.onTouchEnd(b)},this._onTouchEnter=function(b){return a.onTouchEnter(b)},this._onTouchLeave=function(b){return a.onTouchLeave(b)},this._onTouchCancel=function(b){return a.onTouchCancel(b)},this.game.canvas.addEventListener("touchstart",this._onTouchStart,!1),this.game.canvas.addEventListener("touchmove",this._onTouchMove,!1),this.game.canvas.addEventListener("touchend",this._onTouchEnd,!1),this.game.canvas.addEventListener("touchcancel",this._onTouchCancel,!1),this.game.device.cocoonJS||(this.game.canvas.addEventListener("touchenter",this._onTouchEnter,!1),this.game.canvas.addEventListener("touchleave",this._onTouchLeave,!1)))
+}},consumeDocumentTouches:function(){this._documentTouchMove=function(a){a.preventDefault()},document.addEventListener("touchmove",this._documentTouchMove,!1)},addTouchLockCallback:function(a,b){this.touchLockCallbacks.push({callback:a,context:b})},removeTouchLockCallback:function(a,b){for(var c=this.touchLockCallbacks.length;c--;)if(this.touchLockCallbacks[c].callback===a&&this.touchLockCallbacks[c].context===b)return this.touchLockCallbacks.splice(c,1),!0;return!1},onTouchStart:function(a){for(var b=this.touchLockCallbacks.length;b--;)this.touchLockCallbacks[b].callback.call(this.touchLockCallbacks[b].context,this,a)&&this.touchLockCallbacks.splice(b,1);if(this.event=a,this.game.input.enabled&&this.enabled){this.touchStartCallback&&this.touchStartCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.startPointer(a.changedTouches[b])}},onTouchCancel:function(a){if(this.event=a,this.touchCancelCallback&&this.touchCancelCallback.call(this.callbackContext,a),this.game.input.enabled&&this.enabled){this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.stopPointer(a.changedTouches[b])}},onTouchEnter:function(a){this.event=a,this.touchEnterCallback&&this.touchEnterCallback.call(this.callbackContext,a),this.game.input.enabled&&this.enabled&&this.preventDefault&&a.preventDefault()},onTouchLeave:function(a){this.event=a,this.touchLeaveCallback&&this.touchLeaveCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault()},onTouchMove:function(a){this.event=a,this.touchMoveCallback&&this.touchMoveCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.updatePointer(a.changedTouches[b])},onTouchEnd:function(a){this.event=a,this.touchEndCallback&&this.touchEndCallback.call(this.callbackContext,a),this.preventDefault&&a.preventDefault();for(var b=0;b<a.changedTouches.length;b++)this.game.input.stopPointer(a.changedTouches[b])},stop:function(){this.game.device.touch&&(this.game.canvas.removeEventListener("touchstart",this._onTouchStart),this.game.canvas.removeEventListener("touchmove",this._onTouchMove),this.game.canvas.removeEventListener("touchend",this._onTouchEnd),this.game.canvas.removeEventListener("touchenter",this._onTouchEnter),this.game.canvas.removeEventListener("touchleave",this._onTouchLeave),this.game.canvas.removeEventListener("touchcancel",this._onTouchCancel))}},c.Touch.prototype.constructor=c.Touch,c.InputHandler=function(a){this.sprite=a,this.game=a.game,this.enabled=!1,this.checked=!1,this.priorityID=0,this.useHandCursor=!1,this._setHandCursor=!1,this.isDragged=!1,this.allowHorizontalDrag=!0,this.allowVerticalDrag=!0,this.bringToTop=!1,this.snapOffset=null,this.snapOnDrag=!1,this.snapOnRelease=!1,this.snapX=0,this.snapY=0,this.snapOffsetX=0,this.snapOffsetY=0,this.pixelPerfectOver=!1,this.pixelPerfectClick=!1,this.pixelPerfectAlpha=255,this.draggable=!1,this.boundsRect=null,this.boundsSprite=null,this.consumePointerEvent=!1,this.scaleLayer=!1,this.dragOffset=new c.Point,this.dragFromCenter=!1,this.dragStartPoint=new c.Point,this.snapPoint=new c.Point,this._dragPoint=new c.Point,this._dragPhase=!1,this._wasEnabled=!1,this._tempPoint=new c.Point,this._pointerData=[],this._pointerData.push({id:0,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1})},c.InputHandler.prototype={start:function(a,b){if(a=a||0,void 0===b&&(b=!1),this.enabled===!1){this.game.input.interactiveItems.add(this),this.useHandCursor=b,this.priorityID=a;for(var d=0;10>d;d++)this._pointerData[d]={id:d,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1};this.snapOffset=new c.Point,this.enabled=!0,this._wasEnabled=!0}return this.sprite.events.onAddedToGroup.add(this.addedToGroup,this),this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup,this),this.flagged=!1,this.sprite},addedToGroup:function(){this._dragPhase||this._wasEnabled&&!this.enabled&&this.start()},removedFromGroup:function(){this._dragPhase||(this.enabled?(this._wasEnabled=!0,this.stop()):this._wasEnabled=!1)},reset:function(){this.enabled=!1,this.flagged=!1;for(var a=0;10>a;a++)this._pointerData[a]={id:a,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1}},stop:function(){this.enabled!==!1&&(this.enabled=!1,this.game.input.interactiveItems.remove(this))},destroy:function(){this.sprite&&(this._setHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),this.enabled=!1,this.game.input.interactiveItems.remove(this),this._pointerData.length=0,this.boundsRect=null,this.boundsSprite=null,this.sprite=null)},validForInput:function(a,b,c){return void 0===c&&(c=!0),0===this.sprite.scale.x||0===this.sprite.scale.y||this.priorityID<this.game.input.minPriorityID?!1:(c||!this.pixelPerfectClick&&!this.pixelPerfectOver)&&(this.priorityID>a||this.priorityID===a&&this.sprite.renderOrderID<b)?!0:!1},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(a){return a=a||0,this._pointerData[a].x},pointerY:function(a){return a=a||0,this._pointerData[a].y},pointerDown:function(a){return a=a||0,this._pointerData[a].isDown},pointerUp:function(a){return a=a||0,this._pointerData[a].isUp},pointerTimeDown:function(a){return a=a||0,this._pointerData[a].timeDown},pointerTimeUp:function(a){return a=a||0,this._pointerData[a].timeUp},pointerOver:function(a){if(this.enabled){if(void 0!==a)return this._pointerData[a].isOver;for(var b=0;10>b;b++)if(this._pointerData[b].isOver)return!0}return!1},pointerOut:function(a){if(this.enabled){if(void 0!==a)return this._pointerData[a].isOut;for(var b=0;10>b;b++)if(this._pointerData[b].isOut)return!0}return!1},pointerTimeOver:function(a){return a=a||0,this._pointerData[a].timeOver},pointerTimeOut:function(a){return a=a||0,this._pointerData[a].timeOut},pointerDragged:function(a){return a=a||0,this._pointerData[a].isDragged},checkPointerDown:function(a,b){return a.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&this.game.input.hitTest(this.sprite,a,this._tempPoint)?(void 0===b&&(b=!1),!b&&this.pixelPerfectClick?this.checkPixel(this._tempPoint.x,this._tempPoint.y):!0):!1},checkPointerOver:function(a,b){return this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&this.game.input.hitTest(this.sprite,a,this._tempPoint)?(void 0===b&&(b=!1),!b&&this.pixelPerfectOver?this.checkPixel(this._tempPoint.x,this._tempPoint.y):!0):!1},checkPixel:function(a,b,c){if(this.sprite.texture.baseTexture.source){if(null===a&&null===b){this.game.input.getLocalPosition(this.sprite,c,this._tempPoint);var a=this._tempPoint.x,b=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(a-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(b-=-this.sprite.texture.frame.height*this.sprite.anchor.y),a+=this.sprite.texture.frame.x,b+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(a-=this.sprite.texture.trim.x,b-=this.sprite.texture.trim.y,a<this.sprite.texture.crop.x||a>this.sprite.texture.crop.right||b<this.sprite.texture.crop.y||b>this.sprite.texture.crop.bottom))return this._dx=a,this._dy=b,!1;this._dx=a,this._dy=b,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,a,b,1,1,0,0,1,1);var d=this.game.input.hitContext.getImageData(0,0,1,1);if(d.data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(a){return null!==this.sprite&&void 0!==this.sprite.parent?this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this.draggable&&this._draggedPointerID===a.id?this.updateDrag(a):this._pointerData[a.id].isOver?this.checkPointerOver(a)?(this._pointerData[a.id].x=a.x-this.sprite.x,this._pointerData[a.id].y=a.y-this.sprite.y,!0):(this._pointerOutHandler(a),!1):void 0:(this._pointerOutHandler(a),!1):void 0},_pointerOverHandler:function(a){null!==this.sprite&&(this._pointerData[a.id].isOver===!1||a.dirty)&&(this._pointerData[a.id].isOver=!0,this._pointerData[a.id].isOut=!1,this._pointerData[a.id].timeOver=this.game.time.time,this._pointerData[a.id].x=a.x-this.sprite.x,this._pointerData[a.id].y=a.y-this.sprite.y,this.useHandCursor&&this._pointerData[a.id].isDragged===!1&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,a))},_pointerOutHandler:function(a){null!==this.sprite&&(this._pointerData[a.id].isOver=!1,this._pointerData[a.id].isOut=!0,this._pointerData[a.id].timeOut=this.game.time.time,this.useHandCursor&&this._pointerData[a.id].isDragged===!1&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),this.sprite&&this.sprite.events&&this.sprite.events.onInputOut$dispatch(this.sprite,a))},_touchedHandler:function(a){if(null!==this.sprite){if(!this._pointerData[a.id].isDown&&this._pointerData[a.id].isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,a))return;this._pointerData[a.id].isDown=!0,this._pointerData[a.id].isUp=!1,this._pointerData[a.id].timeDown=this.game.time.time,this.sprite&&this.sprite.events&&this.sprite.events.onInputDown$dispatch(this.sprite,a),a.dirty=!0,this.draggable&&this.isDragged===!1&&this.startDrag(a),this.bringToTop&&this.sprite.bringToTop()}return this.consumePointerEvent}},_releasedHandler:function(a){null!==this.sprite&&this._pointerData[a.id].isDown&&a.isUp&&(this._pointerData[a.id].isDown=!1,this._pointerData[a.id].isUp=!0,this._pointerData[a.id].timeUp=this.game.time.time,this._pointerData[a.id].downDuration=this._pointerData[a.id].timeUp-this._pointerData[a.id].timeDown,this.checkPointerOver(a)?this.sprite&&this.sprite.events&&this.sprite.events.onInputUp$dispatch(this.sprite,a,!0):(this.sprite&&this.sprite.events&&this.sprite.events.onInputUp$dispatch(this.sprite,a,!1),this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1)),a.dirty=!0,this.draggable&&this.isDragged&&this._draggedPointerID===a.id&&this.stopDrag(a))},updateDrag:function(a){if(a.isUp)return this.stopDrag(a),!1;var b=this.globalToLocalX(a.x)+this._dragPoint.x+this.dragOffset.x,c=this.globalToLocalY(a.y)+this._dragPoint.y+this.dragOffset.y;return this.sprite.fixedToCamera?(this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=b),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=c),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y))):(this.allowHorizontalDrag&&(this.sprite.x=b),this.allowVerticalDrag&&(this.sprite.y=c),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.x,this.sprite.y))),this.sprite.events.onDragUpdate.dispatch(this.sprite,a,b,c,this.snapPoint),!0},justOver:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isOver&&this.overDuration(a)<b},justOut:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isOut&&this.game.time.time-this._pointerData[a].timeOut<b},justPressed:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isDown&&this.downDuration(a)<b},justReleased:function(a,b){return a=a||0,b=b||500,this._pointerData[a].isUp&&this.game.time.time-this._pointerData[a].timeUp<b},overDuration:function(a){return a=a||0,this._pointerData[a].isOver?this.game.time.time-this._pointerData[a].timeOver:-1},downDuration:function(a){return a=a||0,this._pointerData[a].isDown?this.game.time.time-this._pointerData[a].timeDown:-1},enableDrag:function(a,b,d,e,f,g){void 0===a&&(a=!1),void 0===b&&(b=!1),void 0===d&&(d=!1),void 0===e&&(e=255),void 0===f&&(f=null),void 0===g&&(g=null),this._dragPoint=new c.Point,this.draggable=!0,this.bringToTop=b,this.dragOffset=new c.Point,this.dragFromCenter=a,this.pixelPerfectClick=d,this.pixelPerfectAlpha=e,f&&(this.boundsRect=f),g&&(this.boundsSprite=g)},disableDrag:function(){if(this._pointerData)for(var a=0;10>a;a++)this._pointerData[a].isDragged=!1;this.draggable=!1,this.isDragged=!1,this._draggedPointerID=-1},startDrag:function(a){var b=this.sprite.x,c=this.sprite.y;if(this.isDragged=!0,this._draggedPointerID=a.id,this._pointerData[a.id].isDragged=!0,this.sprite.fixedToCamera)this.dragFromCenter?(this.sprite.centerOn(a.x,a.y),this._dragPoint.setTo(this.sprite.cameraOffset.x-a.x,this.sprite.cameraOffset.y-a.y)):this._dragPoint.setTo(this.sprite.cameraOffset.x-a.x,this.sprite.cameraOffset.y-a.y);else{if(this.dragFromCenter){var d=this.sprite.getBounds();this.sprite.x=this.globalToLocalX(a.x)+(this.sprite.x-d.centerX),this.sprite.y=this.globalToLocalY(a.y)+(this.sprite.y-d.centerY)}this._dragPoint.setTo(this.sprite.x-this.globalToLocalX(a.x),this.sprite.y-this.globalToLocalY(a.y))}this.updateDrag(a),this.bringToTop&&(this._dragPhase=!0,this.sprite.bringToTop()),this.dragStartPoint.set(b,c),this.sprite.events.onDragStart$dispatch(this.sprite,a,b,c)},globalToLocalX:function(a){return this.scaleLayer&&(a-=this.game.scale.grid.boundsFluid.x,a*=this.game.scale.grid.scaleFluidInversed.x),a},globalToLocalY:function(a){return this.scaleLayer&&(a-=this.game.scale.grid.boundsFluid.y,a*=this.game.scale.grid.scaleFluidInversed.y),a},stopDrag:function(a){this.isDragged=!1,this._draggedPointerID=-1,this._pointerData[a.id].isDragged=!1,this._dragPhase=!1,this.snapOnRelease&&(this.sprite.fixedToCamera?(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY):(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY)),this.sprite.events.onDragStop$dispatch(this.sprite,a),this.checkPointerOver(a)===!1&&this._pointerOutHandler(a)},setDragLock:function(a,b){void 0===a&&(a=!0),void 0===b&&(b=!0),this.allowHorizontalDrag=a,this.allowVerticalDrag=b},enableSnap:function(a,b,c,d,e,f){void 0===c&&(c=!0),void 0===d&&(d=!1),void 0===e&&(e=0),void 0===f&&(f=0),this.snapX=a,this.snapY=b,this.snapOffsetX=e,this.snapOffsetY=f,this.snapOnDrag=c,this.snapOnRelease=d},disableSnap:function(){this.snapOnDrag=!1,this.snapOnRelease=!1},checkBoundsRect:function(){this.sprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsRect.left?this.sprite.cameraOffset.x=this.boundsRect.left:this.sprite.cameraOffset.x+this.sprite.width>this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.y<this.boundsRect.top?this.sprite.cameraOffset.y=this.boundsRect.top:this.sprite.cameraOffset.y+this.sprite.height>this.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.left<this.boundsRect.left?this.sprite.x=this.boundsRect.x+this.sprite.offsetX:this.sprite.right>this.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsRect.top?this.sprite.y=this.boundsRect.top+this.sprite.offsetY:this.sprite.bottom>this.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsSprite.cameraOffset.x?this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x:this.sprite.cameraOffset.x+this.sprite.width>this.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.y<this.boundsSprite.cameraOffset.y?this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y:this.sprite.cameraOffset.y+this.sprite.height>this.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.left<this.boundsSprite.left?this.sprite.x=this.boundsSprite.left+this.sprite.offsetX:this.sprite.right>this.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsSprite.top?this.sprite.y=this.boundsSprite.top+this.sprite.offsetY:this.sprite.bottom>this.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},c.InputHandler.prototype.constructor=c.InputHandler,c.Gamepad=function(a){this.game=a,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!=navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new c.SinglePad(a,this),new c.SinglePad(a,this),new c.SinglePad(a,this),new c.SinglePad(a,this)]},c.Gamepad.prototype={addCallbacks:function(a,b){"undefined"!=typeof b&&(this.onConnectCallback="function"==typeof b.onConnect?b.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof b.onDisconnect?b.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof b.onDown?b.onDown:this.onDownCallback,this.onUpCallback="function"==typeof b.onUp?b.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof b.onAxis?b.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof b.onFloat?b.onFloat:this.onFloatCallback,this.callbackContext=a)},start:function(){if(!this._active){this._active=!0;var a=this;this._onGamepadConnected=function(b){return a.onGamepadConnected(b)},this._onGamepadDisconnected=function(b){return a.onGamepadDisconnected(b)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(a){var b=a.gamepad;this._rawPads.push(b),this._gamepads[b.index].connect(b)},onGamepadDisconnected:function(a){var b=a.gamepad;for(var c in this._rawPads)this._rawPads[c].index===b.index&&this._rawPads.splice(c,1);this._gamepads[b.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(navigator.getGamepads)var a=navigator.getGamepads();else if(navigator.webkitGetGamepads)var a=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var a=navigator.webkitGamepads();if(a){this._rawPads=[];for(var b=!1,c=0;c<a.length&&(typeof a[c]!==this._prevRawGamepadTypes[c]&&(b=!0,this._prevRawGamepadTypes[c]=typeof a[c]),a[c]&&this._rawPads.push(a[c]),3!==c);c++);if(b){for(var d,e={rawIndices:{},padIndices:{}},f=0;f<this._gamepads.length;f++)if(d=this._gamepads[f],d.connected)for(var g=0;g<this._rawPads.length;g++)this._rawPads[g].index===d.index&&(e.rawIndices[d.index]=!0,e.padIndices[f]=!0);for(var h=0;h<this._gamepads.length;h++)if(d=this._gamepads[h],!e.padIndices[h]){this._rawPads.length<1&&d.disconnect();for(var i=0;i<this._rawPads.length&&!e.padIndices[h];i++){var j=this._rawPads[i];if(j){if(e.rawIndices[j.index]){d.disconnect();continue}d.connect(j),e.rawIndices[j.index]=!0,e.padIndices[h]=!0}else d.disconnect()}}}}},setDeadZones:function(a){for(var b=0;b<this._gamepads.length;b++)this._gamepads[b].deadZone=a},stop:function(){this._active=!1,window.removeEventListener("gamepadconnected",this._onGamepadConnected),window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnected)},reset:function(){this.update();for(var a=0;a<this._gamepads.length;a++)this._gamepads[a].reset()},justPressed:function(a,b){for(var c=0;c<this._gamepads.length;c++)if(this._gamepads[c].justPressed(a,b)===!0)return!0;return!1},justReleased:function(a,b){for(var c=0;c<this._gamepads.length;c++)if(this._gamepads[c].justReleased(a,b)===!0)return!0;return!1},isDown:function(a){for(var b=0;b<this._gamepads.length;b++)if(this._gamepads[b].isDown(a)===!0)return!0;return!1},destroy:function(){this.stop();for(var a=0;a<this._gamepads.length;a++)this._gamepads[a].destroy()}},c.Gamepad.prototype.constructor=c.Gamepad,Object.defineProperty(c.Gamepad.prototype,"active",{get:function(){return this._active}}),Object.defineProperty(c.Gamepad.prototype,"supported",{get:function(){return this._gamepadSupportAvailable}}),Object.defineProperty(c.Gamepad.prototype,"padsConnected",{get:function(){return this._rawPads.length}}),Object.defineProperty(c.Gamepad.prototype,"pad1",{get:function(){return this._gamepads[0]}}),Object.defineProperty(c.Gamepad.prototype,"pad2",{get:function(){return this._gamepads[1]}}),Object.defineProperty(c.Gamepad.prototype,"pad3",{get:function(){return this._gamepads[2]}}),Object.defineProperty(c.Gamepad.prototype,"pad4",{get:function(){return this._gamepads[3]}}),c.Gamepad.BUTTON_0=0,c.Gamepad.BUTTON_1=1,c.Gamepad.BUTTON_2=2,c.Gamepad.BUTTON_3=3,c.Gamepad.BUTTON_4=4,c.Gamepad.BUTTON_5=5,c.Gamepad.BUTTON_6=6,c.Gamepad.BUTTON_7=7,c.Gamepad.BUTTON_8=8,c.Gamepad.BUTTON_9=9,c.Gamepad.BUTTON_10=10,c.Gamepad.BUTTON_11=11,c.Gamepad.BUTTON_12=12,c.Gamepad.BUTTON_13=13,c.Gamepad.BUTTON_14=14,c.Gamepad.BUTTON_15=15,c.Gamepad.AXIS_0=0,c.Gamepad.AXIS_1=1,c.Gamepad.AXIS_2=2,c.Gamepad.AXIS_3=3,c.Gamepad.AXIS_4=4,c.Gamepad.AXIS_5=5,c.Gamepad.AXIS_6=6,c.Gamepad.AXIS_7=7,c.Gamepad.AXIS_8=8,c.Gamepad.AXIS_9=9,c.Gamepad.XBOX360_A=0,c.Gamepad.XBOX360_B=1,c.Gamepad.XBOX360_X=2,c.Gamepad.XBOX360_Y=3,c.Gamepad.XBOX360_LEFT_BUMPER=4,c.Gamepad.XBOX360_RIGHT_BUMPER=5,c.Gamepad.XBOX360_LEFT_TRIGGER=6,c.Gamepad.XBOX360_RIGHT_TRIGGER=7,c.Gamepad.XBOX360_BACK=8,c.Gamepad.XBOX360_START=9,c.Gamepad.XBOX360_STICK_LEFT_BUTTON=10,c.Gamepad.XBOX360_STICK_RIGHT_BUTTON=11,c.Gamepad.XBOX360_DPAD_LEFT=14,c.Gamepad.XBOX360_DPAD_RIGHT=15,c.Gamepad.XBOX360_DPAD_UP=12,c.Gamepad.XBOX360_DPAD_DOWN=13,c.Gamepad.XBOX360_STICK_LEFT_X=0,c.Gamepad.XBOX360_STICK_LEFT_Y=1,c.Gamepad.XBOX360_STICK_RIGHT_X=2,c.Gamepad.XBOX360_STICK_RIGHT_Y=3,c.Gamepad.PS3XC_X=0,c.Gamepad.PS3XC_CIRCLE=1,c.Gamepad.PS3XC_SQUARE=2,c.Gamepad.PS3XC_TRIANGLE=3,c.Gamepad.PS3XC_L1=4,c.Gamepad.PS3XC_R1=5,c.Gamepad.PS3XC_L2=6,c.Gamepad.PS3XC_R2=7,c.Gamepad.PS3XC_SELECT=8,c.Gamepad.PS3XC_START=9,c.Gamepad.PS3XC_STICK_LEFT_BUTTON=10,c.Gamepad.PS3XC_STICK_RIGHT_BUTTON=11,c.Gamepad.PS3XC_DPAD_UP=12,c.Gamepad.PS3XC_DPAD_DOWN=13,c.Gamepad.PS3XC_DPAD_LEFT=14,c.Gamepad.PS3XC_DPAD_RIGHT=15,c.Gamepad.PS3XC_STICK_LEFT_X=0,c.Gamepad.PS3XC_STICK_LEFT_Y=1,c.Gamepad.PS3XC_STICK_RIGHT_X=2,c.Gamepad.PS3XC_STICK_RIGHT_Y=3,c.SinglePad=function(a,b){this.game=a,this.index=null,this.connected=!1,this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this.deadZone=.26,this._padParent=b,this._rawPad=null,this._prevTimestamp=null,this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0},c.SinglePad.prototype={addCallbacks:function(a,b){"undefined"!=typeof b&&(this.onConnectCallback="function"==typeof b.onConnect?b.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof b.onDisconnect?b.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof b.onDown?b.onDown:this.onDownCallback,this.onUpCallback="function"==typeof b.onUp?b.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof b.onAxis?b.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof b.onFloat?b.onFloat:this.onFloatCallback)},getButton:function(a){return this._buttons[a]?this._buttons[a]:null},pollStatus:function(){if(this.connected&&this.game.input.enabled&&this.game.input.gamepad.enabled&&(!this._rawPad.timestamp||this._rawPad.timestamp!==this._prevTimestamp)){for(var a=0;a<this._buttonsLen;a++){var b=isNaN(this._rawPad.buttons[a])?this._rawPad.buttons[a].value:this._rawPad.buttons[a];b!==this._buttons[a].value&&(1===b?this.processButtonDown(a,b):0===b?this.processButtonUp(a,b):this.processButtonFloat(a,b))}for(var c=0;c<this._axesLen;c++){var d=this._rawPad.axes[c];d>0&&d>this.deadZone||0>d&&d<-this.deadZone?this.processAxisChange(c,d):this.processAxisChange(c,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(a){var b=!this.connected;this.connected=!0,this.index=a.index,this._rawPad=a,this._buttons=[],this._buttonsLen=a.buttons.length,this._axes=[],this._axesLen=a.axes.length;for(var d=0;d<this._axesLen;d++)this._axes[d]=a.axes[d];for(var e in a.buttons)e=parseInt(e,10),this._buttons[e]=new c.DeviceButton(this,e);b&&this._padParent.onConnectCallback&&this._padParent.onConnectCallback.call(this._padParent.callbackContext,this.index),b&&this.onConnectCallback&&this.onConnectCallback.call(this.callbackContext)},disconnect:function(){var a=this.connected,b=this.index;this.connected=!1,this.index=null,this._rawPad=void 0;for(var c=0;c<this._buttonsLen;c++)this._buttons[c].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,a&&this._padParent.onDisconnectCallback&&this._padParent.onDisconnectCallback.call(this._padParent.callbackContext,b),a&&this.onDisconnectCallback&&this.onDisconnectCallback.call(this.callbackContext)},destroy:function(){this._rawPad=void 0;for(var a=0;a<this._buttonsLen;a++)this._buttons[a].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null},processAxisChange:function(a,b){this._axes[a]!==b&&(this._axes[a]=b,this._padParent.onAxisCallback&&this._padParent.onAxisCallback.call(this._padParent.callbackContext,this,a,b),this.onAxisCallback&&this.onAxisCallback.call(this.callbackContext,this,a,b))},processButtonDown:function(a,b){this._padParent.onDownCallback&&this._padParent.onDownCallback.call(this._padParent.callbackContext,a,b,this.index),this.onDownCallback&&this.onDownCallback.call(this.callbackContext,a,b),this._buttons[a]&&this._buttons[a].start(null,b)},processButtonUp:function(a,b){this._padParent.onUpCallback&&this._padParent.onUpCallback.call(this._padParent.callbackContext,a,b,this.index),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,a,b),this._buttons[a]&&this._buttons[a].stop(null,b)},processButtonFloat:function(a,b){this._padParent.onFloatCallback&&this._padParent.onFloatCallback.call(this._padParent.callbackContext,a,b,this.index),this.onFloatCallback&&this.onFloatCallback.call(this.callbackContext,a,b),this._buttons[a]&&this._buttons[a].padFloat(b)},axis:function(a){return this._axes[a]?this._axes[a]:!1},isDown:function(a){return this._buttons[a]?this._buttons[a].isDown:!1},isUp:function(a){return this._buttons[a]?this._buttons[a].isUp:!1},justReleased:function(a,b){return this._buttons[a]?this._buttons[a].justReleased(b):void 0},justPressed:function(a,b){return this._buttons[a]?this._buttons[a].justPressed(b):void 0},buttonValue:function(a){return this._buttons[a]?this._buttons[a].value:null},reset:function(){for(var a=0;a<this._axes.length;a++)this._axes[a]=0}},c.SinglePad.prototype.constructor=c.SinglePad,c.Key=function(a,b){this.game=a,this._enabled=!0,this.event=null,this.isDown=!1,this.isUp=!0,this.altKey=!1,this.ctrlKey=!1,this.shiftKey=!1,this.timeDown=0,this.duration=0,this.timeUp=-2500,this.repeats=0,this.keyCode=b,this.onDown=new c.Signal,this.onHoldCallback=null,this.onHoldContext=null,this.onUp=new c.Signal,this._justDown=!1,this._justUp=!1},c.Key.prototype={update:function(){this._enabled&&this.isDown&&(this.duration=this.game.time.time-this.timeDown,this.repeats++,this.onHoldCallback&&this.onHoldCallback.call(this.onHoldContext,this))},processKeyDown:function(a){this._enabled&&(this.event=a,this.isDown||(this.altKey=a.altKey,this.ctrlKey=a.ctrlKey,this.shiftKey=a.shiftKey,this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this._justDown=!0,this.onDown.dispatch(this)))},processKeyUp:function(a){this._enabled&&(this.event=a,this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=this.game.time.time-this.timeDown,this._justUp=!0,this.onUp.dispatch(this)))},reset:function(a){void 0===a&&(a=!0),this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=0,this._enabled=!0,this._justDown=!1,this._justUp=!1,a&&(this.onDown.removeAll(),this.onUp.removeAll(),this.onHoldCallback=null,this.onHoldContext=null)},downDuration:function(a){return void 0===a&&(a=50),this.isDown&&this.duration<a},upDuration:function(a){return void 0===a&&(a=50),!this.isDown&&this.game.time.time-this.timeUp<a}},Object.defineProperty(c.Key.prototype,"justDown",{get:function(){var a=this._justDown;return this._justDown=!1,a}}),Object.defineProperty(c.Key.prototype,"justUp",{get:function(){var a=this._justUp;return this._justUp=!1,a}}),Object.defineProperty(c.Key.prototype,"enabled",{get:function(){return this._enabled},set:function(a){a=!!a,a!==this._enabled&&(a||this.reset(!1),this._enabled=a)}}),c.Key.prototype.constructor=c.Key,c.Keyboard=function(a){this.game=a,this.enabled=!0,this.event=null,this.pressEvent=null,this.callbackContext=this,this.onDownCallback=null,this.onPressCallback=null,this.onUpCallback=null,this._keys=[],this._capture=[],this._onKeyDown=null,this._onKeyPress=null,this._onKeyUp=null,this._i=0,this._k=0},c.Keyboard.prototype={addCallbacks:function(a,b,c,d){this.callbackContext=a,"undefined"!=typeof b&&(this.onDownCallback=b),"undefined"!=typeof c&&(this.onUpCallback=c),"undefined"!=typeof d&&(this.onPressCallback=d)},addKey:function(a){return this._keys[a]||(this._keys[a]=new c.Key(this.game,a),this.addKeyCapture(a)),this._keys[a]},addKeys:function(a){var b={};for(var c in a)b[c]=this.addKey(a[c]);return b},removeKey:function(a){this._keys[a]&&(this._keys[a]=null,this.removeKeyCapture(a))},createCursorKeys:function(){return this.addKeys({up:c.Keyboard.UP,down:c.Keyboard.DOWN,left:c.Keyboard.LEFT,right:c.Keyboard.RIGHT})},start:function(){if(!this.game.device.cocoonJS&&null===this._onKeyDown){var a=this;this._onKeyDown=function(b){return a.processKeyDown(b)},this._onKeyUp=function(b){return a.processKeyUp(b)},this._onKeyPress=function(b){return a.processKeyPress(b)},window.addEventListener("keydown",this._onKeyDown,!1),window.addEventListener("keyup",this._onKeyUp,!1),window.addEventListener("keypress",this._onKeyPress,!1)}},stop:function(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("keypress",this._onKeyPress),this._onKeyDown=null,this._onKeyUp=null,this._onKeyPress=null},destroy:function(){this.stop(),this.clearCaptures(),this._keys.length=0,this._i=0},addKeyCapture:function(a){if("object"==typeof a)for(var b in a)this._capture[a[b]]=!0;else this._capture[a]=!0},removeKeyCapture:function(a){delete this._capture[a]
+},clearCaptures:function(){this._capture={}},update:function(){for(this._i=this._keys.length;this._i--;)this._keys[this._i]&&this._keys[this._i].update()},processKeyDown:function(a){this.event=a,this.game.input.enabled&&this.enabled&&(this._capture[a.keyCode]&&a.preventDefault(),this._keys[a.keyCode]||(this._keys[a.keyCode]=new c.Key(this.game,a.keyCode)),this._keys[a.keyCode].processKeyDown(a),this._k=a.keyCode,this.onDownCallback&&this.onDownCallback.call(this.callbackContext,a))},processKeyPress:function(a){this.pressEvent=a,this.game.input.enabled&&this.enabled&&this.onPressCallback&&this.onPressCallback.call(this.callbackContext,String.fromCharCode(a.charCode),a)},processKeyUp:function(a){this.event=a,this.game.input.enabled&&this.enabled&&(this._capture[a.keyCode]&&a.preventDefault(),this._keys[a.keyCode]||(this._keys[a.keyCode]=new c.Key(this.game,a.keyCode)),this._keys[a.keyCode].processKeyUp(a),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,a))},reset:function(a){void 0===a&&(a=!0),this.event=null;for(var b=this._keys.length;b--;)this._keys[b]&&this._keys[b].reset(a)},downDuration:function(a,b){return this._keys[a]?this._keys[a].downDuration(b):null},upDuration:function(a,b){return this._keys[a]?this._keys[a].upDuration(b):null},isDown:function(a){return this._keys[a]?this._keys[a].isDown:null}},Object.defineProperty(c.Keyboard.prototype,"lastChar",{get:function(){return 32===this.event.charCode?"":String.fromCharCode(this.pressEvent.charCode)}}),Object.defineProperty(c.Keyboard.prototype,"lastKey",{get:function(){return this._keys[this._k]}}),c.Keyboard.prototype.constructor=c.Keyboard,c.Keyboard.A="A".charCodeAt(0),c.Keyboard.B="B".charCodeAt(0),c.Keyboard.C="C".charCodeAt(0),c.Keyboard.D="D".charCodeAt(0),c.Keyboard.E="E".charCodeAt(0),c.Keyboard.F="F".charCodeAt(0),c.Keyboard.G="G".charCodeAt(0),c.Keyboard.H="H".charCodeAt(0),c.Keyboard.I="I".charCodeAt(0),c.Keyboard.J="J".charCodeAt(0),c.Keyboard.K="K".charCodeAt(0),c.Keyboard.L="L".charCodeAt(0),c.Keyboard.M="M".charCodeAt(0),c.Keyboard.N="N".charCodeAt(0),c.Keyboard.O="O".charCodeAt(0),c.Keyboard.P="P".charCodeAt(0),c.Keyboard.Q="Q".charCodeAt(0),c.Keyboard.R="R".charCodeAt(0),c.Keyboard.S="S".charCodeAt(0),c.Keyboard.T="T".charCodeAt(0),c.Keyboard.U="U".charCodeAt(0),c.Keyboard.V="V".charCodeAt(0),c.Keyboard.W="W".charCodeAt(0),c.Keyboard.X="X".charCodeAt(0),c.Keyboard.Y="Y".charCodeAt(0),c.Keyboard.Z="Z".charCodeAt(0),c.Keyboard.ZERO="0".charCodeAt(0),c.Keyboard.ONE="1".charCodeAt(0),c.Keyboard.TWO="2".charCodeAt(0),c.Keyboard.THREE="3".charCodeAt(0),c.Keyboard.FOUR="4".charCodeAt(0),c.Keyboard.FIVE="5".charCodeAt(0),c.Keyboard.SIX="6".charCodeAt(0),c.Keyboard.SEVEN="7".charCodeAt(0),c.Keyboard.EIGHT="8".charCodeAt(0),c.Keyboard.NINE="9".charCodeAt(0),c.Keyboard.NUMPAD_0=96,c.Keyboard.NUMPAD_1=97,c.Keyboard.NUMPAD_2=98,c.Keyboard.NUMPAD_3=99,c.Keyboard.NUMPAD_4=100,c.Keyboard.NUMPAD_5=101,c.Keyboard.NUMPAD_6=102,c.Keyboard.NUMPAD_7=103,c.Keyboard.NUMPAD_8=104,c.Keyboard.NUMPAD_9=105,c.Keyboard.NUMPAD_MULTIPLY=106,c.Keyboard.NUMPAD_ADD=107,c.Keyboard.NUMPAD_ENTER=108,c.Keyboard.NUMPAD_SUBTRACT=109,c.Keyboard.NUMPAD_DECIMAL=110,c.Keyboard.NUMPAD_DIVIDE=111,c.Keyboard.F1=112,c.Keyboard.F2=113,c.Keyboard.F3=114,c.Keyboard.F4=115,c.Keyboard.F5=116,c.Keyboard.F6=117,c.Keyboard.F7=118,c.Keyboard.F8=119,c.Keyboard.F9=120,c.Keyboard.F10=121,c.Keyboard.F11=122,c.Keyboard.F12=123,c.Keyboard.F13=124,c.Keyboard.F14=125,c.Keyboard.F15=126,c.Keyboard.COLON=186,c.Keyboard.EQUALS=187,c.Keyboard.COMMA=188,c.Keyboard.UNDERSCORE=189,c.Keyboard.PERIOD=190,c.Keyboard.QUESTION_MARK=191,c.Keyboard.TILDE=192,c.Keyboard.OPEN_BRACKET=219,c.Keyboard.BACKWARD_SLASH=220,c.Keyboard.CLOSED_BRACKET=221,c.Keyboard.QUOTES=222,c.Keyboard.BACKSPACE=8,c.Keyboard.TAB=9,c.Keyboard.CLEAR=12,c.Keyboard.ENTER=13,c.Keyboard.SHIFT=16,c.Keyboard.CONTROL=17,c.Keyboard.ALT=18,c.Keyboard.CAPS_LOCK=20,c.Keyboard.ESC=27,c.Keyboard.SPACEBAR=32,c.Keyboard.PAGE_UP=33,c.Keyboard.PAGE_DOWN=34,c.Keyboard.END=35,c.Keyboard.HOME=36,c.Keyboard.LEFT=37,c.Keyboard.UP=38,c.Keyboard.RIGHT=39,c.Keyboard.DOWN=40,c.Keyboard.PLUS=43,c.Keyboard.MINUS=44,c.Keyboard.INSERT=45,c.Keyboard.DELETE=46,c.Keyboard.HELP=47,c.Keyboard.NUM_LOCK=144,c.Component=function(){},c.Component.Angle=function(){},c.Component.Angle.prototype={angle:{get:function(){return c.Math.wrapAngle(c.Math.radToDeg(this.rotation))},set:function(a){this.rotation=c.Math.degToRad(c.Math.wrapAngle(a))}}},c.Component.Animation=function(){},c.Component.Animation.prototype={play:function(a,b,c,d){return this.animations?this.animations.play(a,b,c,d):void 0}},c.Component.AutoCull=function(){},c.Component.AutoCull.prototype={autoCull:!1,inCamera:{get:function(){return this.autoCull||this.checkWorldBounds||(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y),this.game.world.camera.view.intersects(this._bounds)}}},c.Component.Bounds=function(){},c.Component.Bounds.prototype={offsetX:{get:function(){return this.anchor.x*this.width}},offsetY:{get:function(){return this.anchor.y*this.height}},left:{get:function(){return this.x-this.offsetX}},right:{get:function(){return this.x+this.width-this.offsetX}},top:{get:function(){return this.y-this.offsetY}},bottom:{get:function(){return this.y+this.height-this.offsetY}}},c.Component.BringToTop=function(){},c.Component.BringToTop.prototype.bringToTop=function(){return this.parent&&this.parent.bringToTop(this),this},c.Component.BringToTop.prototype.sendToBack=function(){return this.parent&&this.parent.sendToBack(this),this},c.Component.BringToTop.prototype.moveUp=function(){return this.parent&&this.parent.moveUp(this),this},c.Component.BringToTop.prototype.moveDown=function(){return this.parent&&this.parent.moveDown(this),this},c.Component.Core=function(){},c.Component.Core.install=function(a){c.Utils.mixinPrototype(this,c.Component.Core.prototype),this.components={};for(var b=0;b<a.length;b++){var d=a[b],e=!1;"Destroy"===d&&(e=!0),c.Utils.mixinPrototype(this,c.Component[d].prototype,e),this.components[d]=!0}},c.Component.Core.init=function(a,b,d,e,f){this.game=a,this.key=e,this.position.set(b,d),this.world=new c.Point(b,d),this.previousPosition=new c.Point(b,d),this.events=new c.Events(this),this._bounds=new c.Rectangle,this.components.PhysicsBody&&(this.body=this.body),this.components.Animation&&(this.animations=new c.AnimationManager(this)),this.components.LoadTexture&&null!==e&&this.loadTexture(e,f),this.components.FixedToCamera&&(this.cameraOffset=new c.Point(b,d))},c.Component.Core.preUpdate=function(){if(this.pendingDestroy)return void this.destroy();if(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;this.world.setTo(this.game.camera.x+this.worldTransform.tx,this.game.camera.y+this.worldTransform.ty),this.visible&&(this.renderOrderID=this.game.stage.currentRenderOrderID++),this.texture&&(this.texture.requiresReTint=!1),this.animations&&this.animations.update(),this.body&&this.body.preUpdate();for(var a=0;a<this.children.length;a++)this.children[a].preUpdate();return!0},c.Component.Core.prototype={game:null,name:"",components:{},z:0,events:void 0,animations:void 0,key:"",world:null,debug:!1,previousPosition:null,previousRotation:0,renderOrderID:0,fresh:!0,pendingDestroy:!1,_bounds:null,_exists:!0,exists:{get:function(){return this._exists},set:function(a){a?(this._exists=!0,this.body&&this.body.type===c.Physics.P2JS&&this.body.addToWorld(),this.visible=!0):(this._exists=!1,this.body&&this.body.type===c.Physics.P2JS&&this.body.removeFromWorld(),this.visible=!1)}},update:function(){},postUpdate:function(){this.customRender&&this.key.render(),this.components.PhysicsBody&&c.Component.PhysicsBody.postUpdate.call(this),this.components.FixedToCamera&&c.Component.FixedToCamera.postUpdate.call(this);for(var a=0;a<this.children.length;a++)this.children[a].postUpdate()}},c.Component.Crop=function(){},c.Component.Crop.prototype={cropRect:null,_crop:null,crop:function(a,b){void 0===b&&(b=!1),a?(b&&null!==this.cropRect?this.cropRect.setTo(a.x,a.y,a.width,a.height):this.cropRect=b&&null===this.cropRect?new c.Rectangle(a.x,a.y,a.width,a.height):a,this.updateCrop()):(this._crop=null,this.cropRect=null,this.resetFrame())},updateCrop:function(){if(this.cropRect){this._crop=c.Rectangle.clone(this.cropRect,this._crop),this._crop.x+=this._frame.x,this._crop.y+=this._frame.y;var a=Math.max(this._frame.x,this._crop.x),b=Math.max(this._frame.y,this._crop.y),d=Math.min(this._frame.right,this._crop.right)-a,e=Math.min(this._frame.bottom,this._crop.bottom)-b;this.texture.crop.x=a,this.texture.crop.y=b,this.texture.crop.width=d,this.texture.crop.height=e,this.texture.frame.width=Math.min(d,this.cropRect.width),this.texture.frame.height=Math.min(e,this.cropRect.height),this.texture.width=this.texture.frame.width,this.texture.height=this.texture.frame.height,this.texture._updateUvs()}}},c.Component.Delta=function(){},c.Component.Delta.prototype={deltaX:{get:function(){return this.world.x-this.previousPosition.x}},deltaY:{get:function(){return this.world.y-this.previousPosition.y}},deltaZ:{get:function(){return this.rotation-this.previousRotation}}},c.Component.Destroy=function(){},c.Component.Destroy.prototype={destroyPhase:!1,destroy:function(a){if(null!==this.game&&!this.destroyPhase){void 0===a&&(a=!0),this.destroyPhase=!0,this.events&&this.events.onDestroy$dispatch(this),this.parent&&(this.parent instanceof c.Group?this.parent.remove(this):this.parent.removeChild(this)),this.input&&this.input.destroy(),this.animations&&this.animations.destroy(),this.body&&this.body.destroy(),this.events&&this.events.destroy();var b=this.children.length;if(a)for(;b--;)this.children[b].destroy(a);else for(;b--;)this.removeChild(this.children[b]);this._crop&&(this._crop=null),this._frame&&(this._frame=null),c.Video&&this.key instanceof c.Video&&this.key.onChangeSource.remove(this.resizeFrame,this),c.BitmapText&&this._glyphs&&(this._glyphs=[]),this.alive=!1,this.exists=!1,this.visible=!1,this.filters=null,this.mask=null,this.game=null,this.renderable=!1,this.transformCallback=null,this.transformCallbackContext=null,this.hitArea=null,this.parent=null,this.stage=null,this.worldTransform=null,this.filterArea=null,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite(),this.destroyPhase=!1,this.pendingDestroy=!1}}},c.Events=function(a){this.parent=a},c.Events.prototype={destroy:function(){this._parent=null,this._onDestroy&&this._onDestroy.dispose(),this._onAddedToGroup&&this._onAddedToGroup.dispose(),this._onRemovedFromGroup&&this._onRemovedFromGroup.dispose(),this._onRemovedFromWorld&&this._onRemovedFromWorld.dispose(),this._onKilled&&this._onKilled.dispose(),this._onRevived&&this._onRevived.dispose(),this._onEnterBounds&&this._onEnterBounds.dispose(),this._onOutOfBounds&&this._onOutOfBounds.dispose(),this._onInputOver&&this._onInputOver.dispose(),this._onInputOut&&this._onInputOut.dispose(),this._onInputDown&&this._onInputDown.dispose(),this._onInputUp&&this._onInputUp.dispose(),this._onDragStart&&this._onDragStart.dispose(),this._onDragUpdate&&this._onDragUpdate.dispose(),this._onDragStop&&this._onDragStop.dispose(),this._onAnimationStart&&this._onAnimationStart.dispose(),this._onAnimationComplete&&this._onAnimationComplete.dispose(),this._onAnimationLoop&&this._onAnimationLoop.dispose()},onAddedToGroup:null,onRemovedFromGroup:null,onRemovedFromWorld:null,onDestroy:null,onKilled:null,onRevived:null,onOutOfBounds:null,onEnterBounds:null,onInputOver:null,onInputOut:null,onInputDown:null,onInputUp:null,onDragStart:null,onDragUpdate:null,onDragStop:null,onAnimationStart:null,onAnimationComplete:null,onAnimationLoop:null},c.Events.prototype.constructor=c.Events;for(var e in c.Events.prototype)c.Events.prototype.hasOwnProperty(e)&&0===e.indexOf("on")&&null===c.Events.prototype[e]&&!function(a,b){"use strict";Object.defineProperty(c.Events.prototype,a,{get:function(){return this[b]||(this[b]=new c.Signal)}}),c.Events.prototype[a+"$dispatch"]=function(){return this[b]?this[b].dispatch.apply(this[b],arguments):null}}(e,"_"+e);c.Component.FixedToCamera=function(){},c.Component.FixedToCamera.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y)},c.Component.FixedToCamera.prototype={_fixedToCamera:!1,fixedToCamera:{get:function(){return this._fixedToCamera},set:function(a){a?(this._fixedToCamera=!0,this.cameraOffset.set(this.x,this.y)):this._fixedToCamera=!1}},cameraOffset:new c.Point},c.Component.Health=function(){},c.Component.Health.prototype={health:1,maxHealth:100,damage:function(a){return this.alive&&(this.health-=a,this.health<=0&&this.kill()),this},heal:function(a){return this.alive&&(this.health+=a,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},c.Component.InCamera=function(){},c.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},c.Component.InputEnabled=function(){},c.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(a){a?null===this.input?(this.input=new c.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},c.Component.InWorld=function(){},c.Component.InWorld.preUpdate=function(){if((this.autoCull||this.checkWorldBounds)&&(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull&&(this.game.world.camera.view.intersects(this._bounds)?(this.renderable=!0,this.game.world.camera.totalInView++):this.renderable=!1),this.checkWorldBounds))if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1;return!0},c.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},c.Component.LifeSpan=function(){},c.Component.LifeSpan.preUpdate=function(){return this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0)?(this.kill(),!1):!0},c.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(a){return void 0===a&&(a=1),this.alive=!0,this.exists=!0,this.visible=!0,"number"==typeof this.health&&(this.health=a),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},c.Component.LoadTexture=function(){},c.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(a,b,d){b=b||0,(d||void 0===d)&&this.animations&&this.animations.stop(),this.key=a,this.customRender=!1;var e=this.game.cache,f=!0,g=!this.texture.baseTexture.scaleMode;if(c.RenderTexture&&a instanceof c.RenderTexture)this.key=a.key,this.setTexture(a);else if(c.BitmapData&&a instanceof c.BitmapData)this.customRender=!0,this.setTexture(a.texture),e.hasFrameData(a.key,c.Cache.BITMAPDATA)&&(f=!this.animations.loadFrameData(e.getFrameData(a.key,c.Cache.BITMAPDATA),b));else if(c.Video&&a instanceof c.Video){this.customRender=!0;var h=a.texture.valid;this.setTexture(a.texture),this.setFrame(a.texture.frame.clone()),a.onChangeSource.add(this.resizeFrame,this),this.texture.valid=h}else if(a instanceof PIXI.Texture)this.setTexture(a);else{var i=e.getImage(a,!0);this.key=i.key,this.setTexture(new PIXI.Texture(i.base)),f=!this.animations.loadFrameData(i.frameData,b)}f&&(this._frame=c.Rectangle.clone(this.texture.frame)),g||(this.texture.baseTexture.scaleMode=1)},setFrame:function(a){this._frame=a,this.texture.frame.x=a.x,this.texture.frame.y=a.y,this.texture.frame.width=a.width,this.texture.frame.height=a.height,this.texture.crop.x=a.x,this.texture.crop.y=a.y,this.texture.crop.width=a.width,this.texture.crop.height=a.height,a.trimmed?(this.texture.trim?(this.texture.trim.x=a.spriteSourceSizeX,this.texture.trim.y=a.spriteSourceSizeY,this.texture.trim.width=a.sourceSizeW,this.texture.trim.height=a.sourceSizeH):this.texture.trim={x:a.spriteSourceSizeX,y:a.spriteSourceSizeY,width:a.sourceSizeW,height:a.sourceSizeH},this.texture.width=a.sourceSizeW,this.texture.height=a.sourceSizeH,this.texture.frame.width=a.sourceSizeW,this.texture.frame.height=a.sourceSizeH):!a.trimmed&&this.texture.trim&&(this.texture.trim=null),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(a,b,c){this.texture.frame.resize(b,c),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(a){this.animations.frame=a}},frameName:{get:function(){return this.animations.frameName},set:function(a){this.animations.frameName=a}}},c.Component.Overlap=function(){},c.Component.Overlap.prototype={overlap:function(a){return c.Rectangle.intersects(this.getBounds(),a.getBounds())}},c.Component.PhysicsBody=function(){},c.Component.PhysicsBody.preUpdate=function(){return this.fresh&&this.exists?(this.world.setTo(this.parent.position.x+this.position.x,this.parent.position.y+this.position.y),this.worldTransform.tx=this.world.x,this.worldTransform.ty=this.world.y,this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this._exists&&this.parent.exists?!0:(this.renderOrderID=-1,!1))},c.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},c.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(a){this.position.x=a,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(a){this.position.y=a,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},c.Component.Reset=function(){},c.Component.Reset.prototype.reset=function(a,b,c){return void 0===c&&(c=1),this.world.set(a,b),this.position.set(a,b),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=c),this.components.PhysicsBody&&this.body&&this.body.reset(a,b,!1,!1),this},c.Component.ScaleMinMax=function(){},c.Component.ScaleMinMax.prototype={transformCallback:this.checkTransform,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(a){this.scaleMin&&(a.a<this.scaleMin.x&&(a.a=this.scaleMin.x),a.d<this.scaleMin.y&&(a.d=this.scaleMin.y)),this.scaleMax&&(a.a>this.scaleMax.x&&(a.a=this.scaleMax.x),a.d>this.scaleMax.y&&(a.d=this.scaleMax.y))},setScaleMinMax:function(a,b,d,e){void 0===b?b=d=e=a:void 0===d&&(d=e=b,b=a),null===a?this.scaleMin=null:this.scaleMin?this.scaleMin.set(a,b):this.scaleMin=new c.Point(a,b),null===d?this.scaleMax=null:this.scaleMax?this.scaleMax.set(d,e):this.scaleMax=new c.Point(d,e)}},c.Component.Smoothed=function(){},c.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(a){a?this.texture&&(this.texture.baseTexture.scaleMode=0):this.texture&&(this.texture.baseTexture.scaleMode=1)}}},c.GameObjectFactory=function(a){this.game=a,this.world=this.game.world},c.GameObjectFactory.prototype={existing:function(a){return this.world.add(a)},image:function(a,b,d,e,f){return void 0===f&&(f=this.world),f.add(new c.Image(this.game,a,b,d,e))},sprite:function(a,b,c,d,e){return void 0===e&&(e=this.world),e.create(a,b,c,d)},creature:function(a,b,d,e,f){void 0===f&&(f=this.world);var g=new c.Creature(this.game,a,b,d,e);return f.add(g),g},tween:function(a){return this.game.tweens.create(a)},group:function(a,b,d,e,f){return new c.Group(this.game,a,b,d,e,f)},physicsGroup:function(a,b,d,e){return new c.Group(this.game,b,d,e,!0,a)},spriteBatch:function(a,b,d){return void 0===a&&(a=null),void 0===b&&(b="group"),void 0===d&&(d=!1),new c.SpriteBatch(this.game,a,b,d)},audio:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},sound:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},audioSprite:function(a){return this.game.sound.addSprite(a)},tileSprite:function(a,b,d,e,f,g,h){return void 0===h&&(h=this.world),h.add(new c.TileSprite(this.game,a,b,d,e,f,g))},rope:function(a,b,d,e,f,g){return void 0===g&&(g=this.world),g.add(new c.Rope(this.game,a,b,d,e,f))},text:function(a,b,d,e,f){return void 0===f&&(f=this.world),f.add(new c.Text(this.game,a,b,d,e))},button:function(a,b,d,e,f,g,h,i,j,k){return void 0===k&&(k=this.world),k.add(new c.Button(this.game,a,b,d,e,f,g,h,i,j))},graphics:function(a,b,d){return void 0===d&&(d=this.world),d.add(new c.Graphics(this.game,a,b))},emitter:function(a,b,d){return this.game.particles.add(new c.Particles.Arcade.Emitter(this.game,a,b,d))},retroFont:function(a,b,d,e,f,g,h,i,j){return new c.RetroFont(this.game,a,b,d,e,f,g,h,i,j)},bitmapText:function(a,b,d,e,f,g){return void 0===g&&(g=this.world),g.add(new c.BitmapText(this.game,a,b,d,e,f))},tilemap:function(a,b,d,e,f){return new c.Tilemap(this.game,a,b,d,e,f)},renderTexture:function(a,b,d,e){(void 0===d||""===d)&&(d=this.game.rnd.uuid()),void 0===e&&(e=!1);var f=new c.RenderTexture(this.game,a,b,d);return e&&this.game.cache.addRenderTexture(d,f),f},video:function(a,b){return new c.Video(this.game,a,b)},bitmapData:function(a,b,d,e){void 0===e&&(e=!1),(void 0===d||""===d)&&(d=this.game.rnd.uuid());var f=new c.BitmapData(this.game,d,a,b);return e&&this.game.cache.addBitmapData(d,f),f},filter:function(a){var b=Array.prototype.splice.call(arguments,1),a=new c.Filter[a](this.game);return a.init.apply(a,b),a},plugin:function(a){return this.game.plugins.add(a)}},c.GameObjectFactory.prototype.constructor=c.GameObjectFactory,c.GameObjectCreator=function(a){this.game=a,this.world=this.game.world},c.GameObjectCreator.prototype={image:function(a,b,d,e){return new c.Image(this.game,a,b,d,e)},sprite:function(a,b,d,e){return new c.Sprite(this.game,a,b,d,e)},tween:function(a){return new c.Tween(a,this.game,this.game.tweens)},group:function(a,b,d,e,f){return new c.Group(this.game,a,b,d,e,f)},spriteBatch:function(a,b,d){return void 0===b&&(b="group"),void 0===d&&(d=!1),new c.SpriteBatch(this.game,a,b,d)},audio:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},audioSprite:function(a){return this.game.sound.addSprite(a)},sound:function(a,b,c,d){return this.game.sound.add(a,b,c,d)},tileSprite:function(a,b,d,e,f,g){return new c.TileSprite(this.game,a,b,d,e,f,g)},rope:function(a,b,d,e,f){return new c.Rope(this.game,a,b,d,e,f)},text:function(a,b,d,e){return new c.Text(this.game,a,b,d,e)},button:function(a,b,d,e,f,g,h,i,j){return new c.Button(this.game,a,b,d,e,f,g,h,i,j)},graphics:function(a,b){return new c.Graphics(this.game,a,b)},emitter:function(a,b,d){return new c.Particles.Arcade.Emitter(this.game,a,b,d)},retroFont:function(a,b,d,e,f,g,h,i,j){return new c.RetroFont(this.game,a,b,d,e,f,g,h,i,j)},bitmapText:function(a,b,d,e,f,g){return new c.BitmapText(this.game,a,b,d,e,f,g)},tilemap:function(a,b,d,e,f){return new c.Tilemap(this.game,a,b,d,e,f)},renderTexture:function(a,b,d,e){(void 0===d||""===d)&&(d=this.game.rnd.uuid()),void 0===e&&(e=!1);var f=new c.RenderTexture(this.game,a,b,d);return e&&this.game.cache.addRenderTexture(d,f),f},bitmapData:function(a,b,d,e){void 0===e&&(e=!1),(void 0===d||""===d)&&(d=this.game.rnd.uuid());var f=new c.BitmapData(this.game,d,a,b);return e&&this.game.cache.addBitmapData(d,f),f},filter:function(a){var b=Array.prototype.splice.call(arguments,1),a=new c.Filter[a](this.game);return a.init.apply(a,b),a}},c.GameObjectCreator.prototype.constructor=c.GameObjectCreator,c.Sprite=function(a,b,d,e,f){b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.SPRITE,this.physicsType=c.SPRITE,PIXI.Sprite.call(this,PIXI.TextureCache.__default),c.Component.Core.init.call(this,a,b,d,e,f)},c.Sprite.prototype=Object.create(PIXI.Sprite.prototype),c.Sprite.prototype.constructor=c.Sprite,c.Component.Core.install.call(c.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),c.Sprite.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Sprite.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Sprite.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Sprite.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Sprite.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Image=function(a,b,d,e,f){b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.IMAGE,PIXI.Sprite.call(this,PIXI.TextureCache.__default),c.Component.Core.init.call(this,a,b,d,e,f)},c.Image.prototype=Object.create(PIXI.Sprite.prototype),c.Image.prototype.constructor=c.Image,c.Component.Core.install.call(c.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","Smoothed"]),c.Image.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Image.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Image.prototype.preUpdate=function(){return this.preUpdateInWorld()?this.preUpdateCore():!1},c.TileSprite=function(a,b,d,e,f,g,h){b=b||0,d=d||0,e=e||256,f=f||256,g=g||null,h=h||null,this.type=c.TILESPRITE,this.physicsType=c.SPRITE,this._scroll=new c.Point;var i=a.cache.getImage("__default",!0);PIXI.TilingSprite.call(this,new PIXI.Texture(i.base),e,f),c.Component.Core.init.call(this,a,b,d,g,h)},c.TileSprite.prototype=Object.create(PIXI.TilingSprite.prototype),c.TileSprite.prototype.constructor=c.TileSprite,c.Component.Core.install.call(c.TileSprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","Smoothed"]),c.TileSprite.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.TileSprite.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.TileSprite.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.TileSprite.prototype.preUpdateCore=c.Component.Core.preUpdate,c.TileSprite.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.TileSprite.prototype.autoScroll=function(a,b){this._scroll.set(a,b)},c.TileSprite.prototype.stopScroll=function(){this._scroll.set(0,0)},c.TileSprite.prototype.destroy=function(a){c.Component.Destroy.prototype.destroy.call(this,a),PIXI.TilingSprite.prototype.destroy.call(this)},c.TileSprite.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},c.Rope=function(a,b,d,e,f,g){this.points=[],this.points=g,this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.ROPE,this._scroll=new c.Point,PIXI.Rope.call(this,PIXI.TextureCache.__default,this.points),c.Component.Core.init.call(this,a,b,d,e,f)},c.Rope.prototype=Object.create(PIXI.Rope.prototype),c.Rope.prototype.constructor=c.Rope,c.Component.Core.install.call(c.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),c.Rope.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Rope.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Rope.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Rope.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Rope.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},c.Rope.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},Object.defineProperty(c.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(a){a&&"function"==typeof a?(this._hasUpdateAnimation=!0,this._updateAnimation=a):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(c.Rope.prototype,"segments",{get:function(){for(var a,b,d,e,f,g,h,i,j=[],k=0;k<this.points.length;k++)a=4*k,b=this.vertices[a]*this.scale.x,d=this.vertices[a+1]*this.scale.y,e=this.vertices[a+4]*this.scale.x,f=this.vertices[a+3]*this.scale.y,g=c.Math.difference(b,e),h=c.Math.difference(d,f),b+=this.world.x,d+=this.world.y,i=new c.Rectangle(b,d,g,h),j.push(i);return j}}),c.Button=function(a,b,d,e,f,g,h,i,j,k){b=b||0,d=d||0,e=e||null,f=f||null,g=g||this,c.Image.call(this,a,b,d,e,i),this.type=c.BUTTON,this.physicsType=c.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new c.Signal,this.onInputOut=new c.Signal,this.onInputDown=new c.Signal,this.onInputUp=new c.Signal,this.onOverMouseOnly=!1,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(h,i,j,k),null!==f&&this.onInputUp.add(f,g),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this),this.events.onRemovedFromWorld.add(this.removedFromWorld,this)},c.Button.prototype=Object.create(c.Image.prototype),c.Button.prototype.constructor=c.Button;var f="Over",g="Out",h="Down",i="Up";c.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},c.Button.prototype.removedFromWorld=function(){this.inputEnabled=!1},c.Button.prototype.setStateFrame=function(a,b,c){var d="_on"+a+"Frame";null!==b?(this[d]=b,c&&this.changeStateFrame(a)):this[d]=null},c.Button.prototype.changeStateFrame=function(a){if(this.freezeFrames)return!1;var b="_on"+a+"Frame",c=this[b];return"string"==typeof c?(this.frameName=c,!0):"number"==typeof c?(this.frame=c,!0):!1},c.Button.prototype.setFrames=function(a,b,c,d){this.setStateFrame(f,a,this.input.pointerOver()),this.setStateFrame(g,b,!this.input.pointerOver()),this.setStateFrame(h,c,this.input.pointerDown()),this.setStateFrame(i,d,this.input.pointerUp())},c.Button.prototype.setStateSound=function(a,b,d){var e="on"+a+"Sound",f="on"+a+"SoundMarker";b instanceof c.Sound||b instanceof c.AudioSprite?(this[e]=b,this[f]="string"==typeof d?d:""):(this[e]=null,this[f]="")},c.Button.prototype.playStateSound=function(a){var b="on"+a+"Sound",c=this[b];if(c){var d="on"+a+"SoundMarker",e=this[d];return c.play(e),!0}return!1},c.Button.prototype.setSounds=function(a,b,c,d,e,j,k,l){this.setStateSound(f,a,b),this.setStateSound(g,e,j),this.setStateSound(h,c,d),this.setStateSound(i,k,l)
+},c.Button.prototype.setOverSound=function(a,b){this.setStateSound(f,a,b)},c.Button.prototype.setOutSound=function(a,b){this.setStateSound(g,a,b)},c.Button.prototype.setDownSound=function(a,b){this.setStateSound(h,a,b)},c.Button.prototype.setUpSound=function(a,b){this.setStateSound(i,a,b)},c.Button.prototype.onInputOverHandler=function(a,b){b.justReleased()||(this.changeStateFrame(f),(!this.onOverMouseOnly||b.isMouse)&&(this.playStateSound(f),this.onInputOver&&this.onInputOver.dispatch(this,b)))},c.Button.prototype.onInputOutHandler=function(a,b){this.changeStateFrame(g),this.playStateSound(g),this.onInputOut&&this.onInputOut.dispatch(this,b)},c.Button.prototype.onInputDownHandler=function(a,b){this.changeStateFrame(h),this.playStateSound(h),this.onInputDown&&this.onInputDown.dispatch(this,b)},c.Button.prototype.onInputUpHandler=function(a,b,c){if(this.playStateSound(i),this.onInputUp&&this.onInputUp.dispatch(this,b,c),!this.freezeFrames)if(this.forceOut)this.changeStateFrame(g);else{var d=this.changeStateFrame(i);d||this.changeStateFrame(c?f:g)}},c.SpriteBatch=function(a,b,d,e){(void 0===b||null===b)&&(b=a.world),PIXI.SpriteBatch.call(this),c.Group.call(this,a,b,d,e),this.type=c.SPRITEBATCH},c.SpriteBatch.prototype=c.Utils.extend(!0,c.SpriteBatch.prototype,c.Group.prototype,PIXI.SpriteBatch.prototype),c.SpriteBatch.prototype.constructor=c.SpriteBatch,c.Particle=function(a,b,d,e,f){c.Sprite.call(this,a,b,d,e,f),this.autoScale=!1,this.scaleData=null,this._s=0,this.autoAlpha=!1,this.alphaData=null,this._a=0},c.Particle.prototype=Object.create(c.Sprite.prototype),c.Particle.prototype.constructor=c.Particle,c.Particle.prototype.update=function(){this.autoScale&&(this._s--,this._s?this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y):this.autoScale=!1),this.autoAlpha&&(this._a--,this._a?this.alpha=this.alphaData[this._a].v:this.autoAlpha=!1)},c.Particle.prototype.onEmit=function(){},c.Particle.prototype.setAlphaData=function(a){this.alphaData=a,this._a=a.length-1,this.alpha=this.alphaData[this._a].v,this.autoAlpha=!0},c.Particle.prototype.setScaleData=function(a){this.scaleData=a,this._s=a.length-1,this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y),this.autoScale=!0},c.Particle.prototype.reset=function(a,b,d){return c.Component.Reset.prototype.reset.call(this,a,b,d),this.alpha=1,this.scale.set(1),this.autoScale=!1,this.autoAlpha=!1,this},c.BitmapData=function(a,b,d,e){(void 0===d||0===d)&&(d=256),(void 0===e||0===e)&&(e=256),this.game=a,this.key=b,this.width=d,this.height=e,this.canvas=c.Canvas.create(d,e,"",!0),this.context=this.canvas.getContext("2d",{alpha:!0}),this.ctx=this.context,this.imageData=this.context.getImageData(0,0,d,e),this.data=null,this.imageData&&(this.data=this.imageData.data),this.pixels=null,this.data&&(this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data),this.baseTexture=new PIXI.BaseTexture(this.canvas),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new c.Frame(0,0,0,d,e,"bitmapData"),this.texture.frame=this.textureFrame,this.type=c.BITMAPDATA,this.disableTextureUpload=!1,this.dirty=!1,this.cls=this.clear,this._image=null,this._pos=new c.Point,this._size=new c.Point,this._scale=new c.Point,this._rotate=0,this._alpha={prev:1,current:1},this._anchor=new c.Point,this._tempR=0,this._tempG=0,this._tempB=0,this._circle=new c.Circle,this._swapCanvas=c.Canvas.create(d,e,"",!0)},c.BitmapData.prototype={move:function(a,b){return 0!==a&&this.moveH(a),0!==b&&this.moveV(b),this},moveH:function(a){var b=this._swapCanvas,c=b.getContext("2d"),d=this.height,e=this.canvas;if(c.clearRect(0,0,this.width,this.height),0>a){a=Math.abs(a);var f=this.width-a;c.drawImage(e,0,0,a,d,f,0,a,d),c.drawImage(e,a,0,f,d,0,0,f,d)}else{var f=this.width-a;c.drawImage(e,f,0,a,d,0,0,a,d),c.drawImage(e,0,0,f,d,a,0,f,d)}return this.clear(),this.copy(this._swapCanvas)},moveV:function(a){var b=this._swapCanvas,c=b.getContext("2d"),d=this.width,e=this.canvas;if(c.clearRect(0,0,this.width,this.height),0>a){a=Math.abs(a);var f=this.height-a;c.drawImage(e,0,0,d,a,0,f,d,a),c.drawImage(e,0,a,d,f,0,0,d,f)}else{var f=this.height-a;c.drawImage(e,0,f,d,a,0,0,d,a),c.drawImage(e,0,0,d,f,0,a,d,f)}return this.clear(),this.copy(this._swapCanvas)},add:function(a){if(Array.isArray(a))for(var b=0;b<a.length;b++)a[b].loadTexture&&a[b].loadTexture(this);else a.loadTexture(this);return this},load:function(a){return"string"==typeof a&&(a=this.game.cache.getImage(a)),a?(this.resize(a.width,a.height),this.cls(),this.draw(a),this.update(),this):void 0},clear:function(a,b,c,d){return void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c=this.width),void 0===d&&(d=this.height),this.context.clearRect(a,b,c,d),this.dirty=!0,this},fill:function(a,b,c,d){return void 0===d&&(d=1),this.context.fillStyle="rgba("+a+","+b+","+c+","+d+")",this.context.fillRect(0,0,this.width,this.height),this.dirty=!0,this},generateTexture:function(a){var b=new Image;b.src=this.canvas.toDataURL("image/png");var c=this.game.cache.addImage(a,"",b);return new PIXI.Texture(c.base)},resize:function(a,b){return(a!==this.width||b!==this.height)&&(this.width=a,this.height=b,this.canvas.width=a,this.canvas.height=b,this._swapCanvas.width=a,this._swapCanvas.height=b,this.baseTexture.width=a,this.baseTexture.height=b,this.textureFrame.width=a,this.textureFrame.height=b,this.texture.width=a,this.texture.height=b,this.texture.crop.width=a,this.texture.crop.height=b,this.update(),this.dirty=!0),this},update:function(a,b,c,d){return void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c=Math.max(1,this.width)),void 0===d&&(d=Math.max(1,this.height)),this.imageData=this.context.getImageData(a,b,c,d),this.data=this.imageData.data,this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data,this},processPixelRGB:function(a,b,d,e,f,g){void 0===d&&(d=0),void 0===e&&(e=0),void 0===f&&(f=this.width),void 0===g&&(g=this.height);for(var h=d+f,i=e+g,j=c.Color.createColor(),k={r:0,g:0,b:0,a:0},l=!1,m=e;i>m;m++)for(var n=d;h>n;n++)c.Color.unpackPixel(this.getPixel32(n,m),j),k=a.call(b,j,n,m),k!==!1&&null!==k&&void 0!==k&&(this.setPixel32(n,m,k.r,k.g,k.b,k.a,!1),l=!0);return l&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},processPixel:function(a,b,c,d,e,f){void 0===c&&(c=0),void 0===d&&(d=0),void 0===e&&(e=this.width),void 0===f&&(f=this.height);for(var g=c+e,h=d+f,i=0,j=0,k=!1,l=d;h>l;l++)for(var m=c;g>m;m++)i=this.getPixel32(m,l),j=a.call(b,i,m,l),j!==i&&(this.pixels[l*this.width+m]=j,k=!0);return k&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},replaceRGB:function(a,b,d,e,f,g,h,i,j){var k=0,l=0,m=this.width,n=this.height,o=c.Color.packPixel(a,b,d,e);void 0!==j&&j instanceof c.Rectangle&&(k=j.x,l=j.y,m=j.width,n=j.height);for(var p=0;n>p;p++)for(var q=0;m>q;q++)this.getPixel32(k+q,l+p)===o&&this.setPixel32(k+q,l+p,f,g,h,i,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this},setHSL:function(a,b,d,e){if((void 0===a||null===a)&&(a=!1),(void 0===b||null===b)&&(b=!1),(void 0===d||null===d)&&(d=!1),a||b||d){void 0===e&&(e=new c.Rectangle(0,0,this.width,this.height));for(var f=c.Color.createColor(),g=e.y;g<e.bottom;g++)for(var h=e.x;h<e.right;h++)c.Color.unpackPixel(this.getPixel32(h,g),f,!0),a&&(f.h=a),b&&(f.s=b),d&&(f.l=d),c.Color.HSLtoRGB(f.h,f.s,f.l,f),this.setPixel32(h,g,f.r,f.g,f.b,f.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},shiftHSL:function(a,b,d,e){if((void 0===a||null===a)&&(a=!1),(void 0===b||null===b)&&(b=!1),(void 0===d||null===d)&&(d=!1),a||b||d){void 0===e&&(e=new c.Rectangle(0,0,this.width,this.height));for(var f=c.Color.createColor(),g=e.y;g<e.bottom;g++)for(var h=e.x;h<e.right;h++)c.Color.unpackPixel(this.getPixel32(h,g),f,!0),a&&(f.h=this.game.math.wrap(f.h+a,0,1)),b&&(f.s=this.game.math.limitValue(f.s+b,0,1)),d&&(f.l=this.game.math.limitValue(f.l+d,0,1)),c.Color.HSLtoRGB(f.h,f.s,f.l,f),this.setPixel32(h,g,f.r,f.g,f.b,f.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},setPixel32:function(a,b,d,e,f,g,h){return void 0===h&&(h=!0),a>=0&&a<=this.width&&b>=0&&b<=this.height&&(this.pixels[b*this.width+a]=c.Device.LITTLE_ENDIAN?g<<24|f<<16|e<<8|d:d<<24|e<<16|f<<8|g,h&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(a,b,c,d,e,f){return this.setPixel32(a,b,c,d,e,255,f)},getPixel:function(a,b,d){d||(d=c.Color.createColor());var e=~~(a+b*this.width);return e*=4,d.r=this.data[e],d.g=this.data[++e],d.b=this.data[++e],d.a=this.data[++e],d},getPixel32:function(a,b){return a>=0&&a<=this.width&&b>=0&&b<=this.height?this.pixels[b*this.width+a]:void 0},getPixelRGB:function(a,b,d,e,f){return c.Color.unpackPixel(this.getPixel32(a,b),d,e,f)},getPixels:function(a){return this.context.getImageData(a.x,a.y,a.width,a.height)},getFirstPixel:function(a){void 0===a&&(a=0);var b=c.Color.createColor(),d=0,e=0,f=1,g=!1;1===a?(f=-1,e=this.height):3===a&&(f=-1,d=this.width);do c.Color.unpackPixel(this.getPixel32(d,e),b),0===a||1===a?(d++,d===this.width&&(d=0,e+=f,(e>=this.height||0>=e)&&(g=!0))):(2===a||3===a)&&(e++,e===this.height&&(e=0,d+=f,(d>=this.width||0>=d)&&(g=!0)));while(0===b.a&&!g);return b.x=d,b.y=e,b},getBounds:function(a){return void 0===a&&(a=new c.Rectangle),a.x=this.getFirstPixel(2).x,a.x===this.width?a.setTo(0,0,0,0):(a.y=this.getFirstPixel(0).y,a.width=this.getFirstPixel(3).x-a.x+1,a.height=this.getFirstPixel(1).y-a.y+1,a)},addToWorld:function(a,b,c,d,e,f){e=e||1,f=f||1;var g=this.game.add.image(a,b,this);return g.anchor.set(c,d),g.scale.set(e,f),g},copy:function(a,b,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){if((void 0===a||null===a)&&(a=this),this._image=a,a instanceof c.Sprite||a instanceof c.Image||a instanceof c.Text)this._pos.set(a.texture.crop.x,a.texture.crop.y),this._size.set(a.texture.crop.width,a.texture.crop.height),this._scale.set(a.scale.x,a.scale.y),this._anchor.set(a.anchor.x,a.anchor.y),this._rotate=a.rotation,this._alpha.current=a.alpha,this._image=a.texture.baseTexture.source,(void 0===g||null===g)&&(g=a.x),(void 0===h||null===h)&&(h=a.y),a.texture.trim&&(g+=a.texture.trim.x-a.anchor.x*a.texture.trim.width,h+=a.texture.trim.y-a.anchor.y*a.texture.trim.height),16777215!==a.tint&&(a.cachedTint!==a.tint&&(a.cachedTint=a.tint,a.tintedTexture=PIXI.CanvasTinter.getTintedTexture(a,a.tint)),this._image=a.tintedTexture);else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,a instanceof c.BitmapData)this._image=a.canvas;else if("string"==typeof a){if(a=this.game.cache.getImage(a),null===a)return;this._image=a}this._size.set(this._image.width,this._image.height)}return(void 0===b||null===b)&&(b=0),(void 0===d||null===d)&&(d=0),e&&(this._size.x=e),f&&(this._size.y=f),(void 0===g||null===g)&&(g=b),(void 0===h||null===h)&&(h=d),(void 0===i||null===i)&&(i=this._size.x),(void 0===j||null===j)&&(j=this._size.y),"number"==typeof k&&(this._rotate=k),"number"==typeof l&&(this._anchor.x=l),"number"==typeof m&&(this._anchor.y=m),"number"==typeof n&&(this._scale.x=n),"number"==typeof o&&(this._scale.y=o),"number"==typeof p&&(this._alpha.current=p),void 0===q&&(q=null),void 0===r&&(r=!1),this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y?void 0:(this._alpha.prev=this.context.globalAlpha,this.context.save(),this.context.globalAlpha=this._alpha.current,q&&(this.context.globalCompositeOperation=q),r&&(g|=0,h|=0),this.context.translate(g,h),this.context.scale(this._scale.x,this._scale.y),this.context.rotate(this._rotate),this.context.drawImage(this._image,this._pos.x+b,this._pos.y+d,this._size.x,this._size.y,-i*this._anchor.x,-j*this._anchor.y,i,j),this.context.restore(),this.context.globalAlpha=this._alpha.prev,this.dirty=!0,this)},copyRect:function(a,b,c,d,e,f,g){return this.copy(a,b.x,b.y,b.width,b.height,c,d,b.width,b.height,0,0,0,1,1,e,f,g)},draw:function(a,b,c,d,e,f,g){return this.copy(a,null,null,null,null,b,c,d,e,null,null,null,null,null,null,f,g)},drawGroup:function(a,b,c){return a.total>0&&a.forEachExists(this.copy,this,null,null,null,null,null,null,null,null,null,null,null,null,null,null,b,c),this},shadow:function(a,b,c,d){void 0===a||null===a?this.context.shadowColor="rgba(0,0,0,0)":(this.context.shadowColor=a,this.context.shadowBlur=b||5,this.context.shadowOffsetX=c||10,this.context.shadowOffsetY=d||10)},alphaMask:function(a,b,c,d){return void 0===d||null===d?this.draw(b).blendSourceAtop():this.draw(b,d.x,d.y,d.width,d.height).blendSourceAtop(),void 0===c||null===c?this.draw(a).blendReset():this.draw(a,c.x,c.y,c.width,c.height).blendReset(),this},extract:function(a,b,c,d,e,f,g,h,i){return void 0===e&&(e=255),void 0===f&&(f=!1),void 0===g&&(g=b),void 0===h&&(h=c),void 0===i&&(i=d),f&&a.resize(this.width,this.height),this.processPixelRGB(function(f,j,k){return f.r===b&&f.g===c&&f.b===d&&a.setPixel32(j,k,g,h,i,e,!1),!1},this),a.context.putImageData(a.imageData,0,0),a.dirty=!0,a},rect:function(a,b,c,d,e){return"undefined"!=typeof e&&(this.context.fillStyle=e),this.context.fillRect(a,b,c,d),this},text:function(a,b,c,d,e,f){void 0===b&&(b=0),void 0===c&&(c=0),void 0===d&&(d="14px Courier"),void 0===e&&(e="rgb(255,255,255)"),void 0===f&&(f=!0);var g=this.context.font;this.context.font=d,f&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(a,b+1,c+1)),this.context.fillStyle=e,this.context.fillText(a,b,c),this.context.font=g},circle:function(a,b,c,d){return"undefined"!=typeof d&&(this.context.fillStyle=d),this.context.beginPath(),this.context.arc(a,b,c,0,2*Math.PI,!1),this.context.closePath(),this.context.fill(),this},textureLine:function(a,b,d){if(void 0===d&&(d="repeat-x"),"string"!=typeof b||(b=this.game.cache.getImage(b))){var e=a.length;return"no-repeat"===d&&e>b.width&&(e=b.width),this.context.fillStyle=this.context.createPattern(b,d),this._circle=new c.Circle(a.start.x,a.start.y,b.height),this._circle.circumferencePoint(a.angle-1.5707963267948966,!1,this._pos),this.context.save(),this.context.translate(this._pos.x,this._pos.y),this.context.rotate(a.angle),this.context.fillRect(0,0,e,b.height),this.context.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},blendReset:function(){return this.context.globalCompositeOperation="source-over",this},blendSourceOver:function(){return this.context.globalCompositeOperation="source-over",this},blendSourceIn:function(){return this.context.globalCompositeOperation="source-in",this},blendSourceOut:function(){return this.context.globalCompositeOperation="source-out",this},blendSourceAtop:function(){return this.context.globalCompositeOperation="source-atop",this},blendDestinationOver:function(){return this.context.globalCompositeOperation="destination-over",this},blendDestinationIn:function(){return this.context.globalCompositeOperation="destination-in",this},blendDestinationOut:function(){return this.context.globalCompositeOperation="destination-out",this},blendDestinationAtop:function(){return this.context.globalCompositeOperation="destination-atop",this},blendXor:function(){return this.context.globalCompositeOperation="xor",this},blendAdd:function(){return this.context.globalCompositeOperation="lighter",this},blendMultiply:function(){return this.context.globalCompositeOperation="multiply",this},blendScreen:function(){return this.context.globalCompositeOperation="screen",this},blendOverlay:function(){return this.context.globalCompositeOperation="overlay",this},blendDarken:function(){return this.context.globalCompositeOperation="darken",this},blendLighten:function(){return this.context.globalCompositeOperation="lighten",this},blendColorDodge:function(){return this.context.globalCompositeOperation="color-dodge",this},blendColorBurn:function(){return this.context.globalCompositeOperation="color-burn",this},blendHardLight:function(){return this.context.globalCompositeOperation="hard-light",this},blendSoftLight:function(){return this.context.globalCompositeOperation="soft-light",this},blendDifference:function(){return this.context.globalCompositeOperation="difference",this},blendExclusion:function(){return this.context.globalCompositeOperation="exclusion",this},blendHue:function(){return this.context.globalCompositeOperation="hue",this},blendSaturation:function(){return this.context.globalCompositeOperation="saturation",this},blendColor:function(){return this.context.globalCompositeOperation="color",this},blendLuminosity:function(){return this.context.globalCompositeOperation="luminosity",this}},Object.defineProperty(c.BitmapData.prototype,"smoothed",{get:function(){c.Canvas.getSmoothingEnabled(this.context)},set:function(a){c.Canvas.setSmoothingEnabled(this.context,a)}}),c.BitmapData.getTransform=function(a,b,c,d,e,f){return"number"!=typeof a&&(a=0),"number"!=typeof b&&(b=0),"number"!=typeof c&&(c=1),"number"!=typeof d&&(d=1),"number"!=typeof e&&(e=0),"number"!=typeof f&&(f=0),{sx:c,sy:d,scaleX:c,scaleY:d,skewX:e,skewY:f,translateX:a,translateY:b,tx:a,ty:b}},c.BitmapData.prototype.constructor=c.BitmapData,PIXI.Graphics=function(){PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new PIXI.Rectangle(0,0,1,1),this.dirty=!0,this.webGLDirty=!1,this.cachedSpriteDirty=!1},PIXI.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),PIXI.Graphics.prototype.constructor=PIXI.Graphics,PIXI.Graphics.prototype.lineStyle=function(a,b,c){return this.lineWidth=a||0,this.lineColor=b||0,this.lineAlpha=void 0===c?1:c,this.currentPath&&(this.currentPath.shape.points.length?this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))):(this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha)),this},PIXI.Graphics.prototype.moveTo=function(a,b){return this.drawShape(new PIXI.Polygon([a,b])),this},PIXI.Graphics.prototype.lineTo=function(a,b){return this.currentPath||this.moveTo(0,0),this.currentPath.shape.points.push(a,b),this.dirty=!0,this},PIXI.Graphics.prototype.quadraticCurveTo=function(a,b,c,d){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var e,f,g=20,h=this.currentPath.shape.points;0===h.length&&this.moveTo(0,0);for(var i=h[h.length-2],j=h[h.length-1],k=0,l=1;g>=l;++l)k=l/g,e=i+(a-i)*k,f=j+(b-j)*k,h.push(e+(a+(c-a)*k-e)*k,f+(b+(d-b)*k-f)*k);return this.dirty=!0,this},PIXI.Graphics.prototype.bezierCurveTo=function(a,b,c,d,e,f){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);for(var g,h,i,j,k,l=20,m=this.currentPath.shape.points,n=m[m.length-2],o=m[m.length-1],p=0,q=1;l>=q;++q)p=q/l,g=1-p,h=g*g,i=h*g,j=p*p,k=j*p,m.push(i*n+3*h*p*a+3*g*j*c+k*e,i*o+3*h*p*b+3*g*j*d+k*f);return this.dirty=!0,this},PIXI.Graphics.prototype.arcTo=function(a,b,c,d,e){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(a,b):this.moveTo(a,b);var f=this.currentPath.shape.points,g=f[f.length-2],h=f[f.length-1],i=h-b,j=g-a,k=d-b,l=c-a,m=Math.abs(i*l-j*k);if(1e-8>m||0===e)(f[f.length-2]!==a||f[f.length-1]!==b)&&f.push(a,b);else{var n=i*i+j*j,o=k*k+l*l,p=i*k+j*l,q=e*Math.sqrt(n)/m,r=e*Math.sqrt(o)/m,s=q*p/n,t=r*p/o,u=q*l+r*j,v=q*k+r*i,w=j*(r+s),x=i*(r+s),y=l*(q+t),z=k*(q+t),A=Math.atan2(x-v,w-u),B=Math.atan2(z-v,y-u);this.arc(u+a,v+b,e,A,B,j*k>l*i)}return this.dirty=!0,this},PIXI.Graphics.prototype.arc=function(a,b,c,d,e,f){if(d===e)return this;void 0===f&&(f=!1),!f&&d>=e?e+=2*Math.PI:f&&e>=d&&(d+=2*Math.PI);var g=f?-1*(d-e):e-d,h=40*Math.ceil(Math.abs(g)/(2*Math.PI));if(0===g)return this;var i=a+Math.cos(d)*c,j=b+Math.sin(d)*c;f&&this.filling?this.moveTo(a,b):this.moveTo(i,j);for(var k=this.currentPath.shape.points,l=g/(2*h),m=2*l,n=Math.cos(l),o=Math.sin(l),p=h-1,q=p%1/p,r=0;p>=r;r++){var s=r+q*r,t=l+d+m*s,u=Math.cos(t),v=-Math.sin(t);k.push((n*u+o*v)*c+a,(n*-v+o*u)*c+b)}return this.dirty=!0,this},PIXI.Graphics.prototype.beginFill=function(a,b){return this.filling=!0,this.fillColor=a||0,this.fillAlpha=void 0===b?1:b,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},PIXI.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},PIXI.Graphics.prototype.drawRect=function(a,b,c,d){return this.drawShape(new PIXI.Rectangle(a,b,c,d)),this},PIXI.Graphics.prototype.drawRoundedRect=function(a,b,c,d,e){return this.drawShape(new PIXI.RoundedRectangle(a,b,c,d,e)),this},PIXI.Graphics.prototype.drawCircle=function(a,b,c){return this.drawShape(new PIXI.Circle(a,b,c)),this},PIXI.Graphics.prototype.drawEllipse=function(a,b,c,d){return this.drawShape(new PIXI.Ellipse(a,b,c,d)),this},PIXI.Graphics.prototype.drawPolygon=function(a){(a instanceof c.Polygon||a instanceof PIXI.Polygon)&&(a=a.points);var b=a;if(!Array.isArray(b)){b=new Array(arguments.length);for(var d=0;d<b.length;++d)b[d]=arguments[d]}return this.drawShape(new c.Polygon(b)),this},PIXI.Graphics.prototype.clear=function(){return this.lineWidth=0,this.filling=!1,this.dirty=!0,this.clearDirty=!0,this.graphicsData=[],this},PIXI.Graphics.prototype.generateTexture=function(a,b){a=a||1;var c=this.getBounds(),d=new PIXI.CanvasBuffer(c.width*a,c.height*a),e=PIXI.Texture.fromCanvas(d.canvas,b);return e.baseTexture.resolution=a,d.context.scale(a,a),d.context.translate(-c.x,-c.y),PIXI.CanvasGraphics.renderGraphics(this,d.context),e},PIXI.Graphics.prototype._renderWebGL=function(a){if(this.visible!==!1&&0!==this.alpha&&this.isMask!==!0){if(this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.worldAlpha=this.worldAlpha,void PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite,a);if(a.spriteBatch.stop(),a.blendModeManager.setBlendMode(this.blendMode),this._mask&&a.maskManager.pushMask(this._mask,a),this._filters&&a.filterManager.pushFilter(this._filterBlock),this.blendMode!==a.spriteBatch.currentBlendMode){a.spriteBatch.currentBlendMode=this.blendMode;var b=PIXI.blendModesWebGL[a.spriteBatch.currentBlendMode];a.spriteBatch.gl.blendFunc(b[0],b[1])}if(this.webGLDirty&&(this.dirty=!0,this.webGLDirty=!1),PIXI.WebGLGraphics.renderGraphics(this,a),this.children.length){a.spriteBatch.start();for(var c=0;c<this.children.length;c++)this.children[c]._renderWebGL(a);a.spriteBatch.stop()}this._filters&&a.filterManager.popFilter(),this._mask&&a.maskManager.popMask(this.mask,a),a.drawCount++,a.spriteBatch.start()}},PIXI.Graphics.prototype._renderCanvas=function(a){if(this.visible!==!1&&0!==this.alpha&&this.isMask!==!0){if(this._prevTint!==this.tint&&(this.dirty=!0,this._prevTint=this.tint),this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.alpha=this.alpha,void PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite,a);var b=a.context,c=this.worldTransform;this.blendMode!==a.currentBlendMode&&(a.currentBlendMode=this.blendMode,b.globalCompositeOperation=PIXI.blendModesCanvas[a.currentBlendMode]),this._mask&&a.maskManager.pushMask(this._mask,a);var d=a.resolution;b.setTransform(c.a*d,c.b*d,c.c*d,c.d*d,c.tx*d,c.ty*d),PIXI.CanvasGraphics.renderGraphics(this,b);for(var e=0;e<this.children.length;e++)this.children[e]._renderCanvas(a);this._mask&&a.maskManager.popMask(a)}},PIXI.Graphics.prototype.getBounds=function(a){if(!this._currentBounds){if(!this.renderable)return PIXI.EmptyRectangle;this.dirty&&(this.updateLocalBounds(),this.webGLDirty=!0,this.cachedSpriteDirty=!0,this.dirty=!1);var b=this._localBounds,c=b.x,d=b.width+b.x,e=b.y,f=b.height+b.y,g=a||this.worldTransform,h=g.a,i=g.b,j=g.c,k=g.d,l=g.tx,m=g.ty,n=h*d+j*f+l,o=k*f+i*d+m,p=h*c+j*f+l,q=k*f+i*c+m,r=h*c+j*e+l,s=k*e+i*c+m,t=h*d+j*e+l,u=k*e+i*d+m,v=n,w=o,x=n,y=o;x=x>p?p:x,x=x>r?r:x,x=x>t?t:x,y=y>q?q:y,y=y>s?s:y,y=y>u?u:y,v=p>v?p:v,v=r>v?r:v,v=t>v?t:v,w=q>w?q:w,w=s>w?s:w,w=u>w?u:w,this._bounds.x=x,this._bounds.width=v-x,this._bounds.y=y,this._bounds.height=w-y,this._currentBounds=this._bounds}return this._currentBounds},PIXI.Graphics.prototype.containsPoint=function(a){this.worldTransform.applyInverse(a,tempPoint);for(var b=this.graphicsData,c=0;c<b.length;c++){var d=b[c];if(d.fill&&d.shape&&d.shape.contains(tempPoint.x,tempPoint.y))return!0}return!1},PIXI.Graphics.prototype.updateLocalBounds=function(){var a=1/0,b=-1/0,d=1/0,e=-1/0;if(this.graphicsData.length)for(var f,g,h,i,j,k,l=0;l<this.graphicsData.length;l++){var m=this.graphicsData[l],n=m.type,o=m.lineWidth;if(f=m.shape,n===PIXI.Graphics.RECT||n===PIXI.Graphics.RREC)h=f.x-o/2,i=f.y-o/2,j=f.width+o,k=f.height+o,a=a>h?h:a,b=h+j>b?h+j:b,d=d>i?i:d,e=i+k>e?i+k:e;else if(n===PIXI.Graphics.CIRC)h=f.x,i=f.y,j=f.radius+o/2,k=f.radius+o/2,a=a>h-j?h-j:a,b=h+j>b?h+j:b,d=d>i-k?i-k:d,e=i+k>e?i+k:e;else if(n===PIXI.Graphics.ELIP)h=f.x,i=f.y,j=f.width+o/2,k=f.height+o/2,a=a>h-j?h-j:a,b=h+j>b?h+j:b,d=d>i-k?i-k:d,e=i+k>e?i+k:e;else{g=f.points;for(var p=0;p<g.length;p++)g[p]instanceof c.Point?(h=g[p].x,i=g[p].y):(h=g[p],i=g[p+1],p<g.length-1&&p++),a=a>h-o?h-o:a,b=h+o>b?h+o:b,d=d>i-o?i-o:d,e=i+o>e?i+o:e}}else a=0,b=0,d=0,e=0;var q=this.boundsPadding;this._localBounds.x=a-q,this._localBounds.width=b-a+2*q,this._localBounds.y=d-q,this._localBounds.height=e-d+2*q},PIXI.Graphics.prototype._generateCachedSprite=function(){var a=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(a.width,a.height);else{var b=new PIXI.CanvasBuffer(a.width,a.height),c=PIXI.Texture.fromCanvas(b.canvas);this._cachedSprite=new PIXI.Sprite(c),this._cachedSprite.buffer=b,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-(a.x/a.width),this._cachedSprite.anchor.y=-(a.y/a.height),this._cachedSprite.buffer.context.translate(-a.x,-a.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},PIXI.Graphics.prototype.updateCachedSpriteTexture=function(){var a=this._cachedSprite,b=a.texture,c=a.buffer.canvas;b.baseTexture.width=c.width,b.baseTexture.height=c.height,b.crop.width=b.frame.width=c.width,b.crop.height=b.frame.height=c.height,a._width=c.width,a._height=c.height,b.baseTexture.dirty()},PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},PIXI.Graphics.prototype.drawShape=function(a){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,a instanceof c.Polygon&&(a=a.clone(),a.flatten());var b=new PIXI.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,a);return this.graphicsData.push(b),b.type===PIXI.Graphics.POLY&&(b.shape.closed=this.filling,this.currentPath=b),this.dirty=!0,b},Object.defineProperty(PIXI.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(a){this._cacheAsBitmap=a,this._cacheAsBitmap?this._generateCachedSprite():(this.destroyCachedSprite(),this.dirty=!0)}}),PIXI.GraphicsData=function(a,b,c,d,e,f,g){this.lineWidth=a,this.lineColor=b,this.lineAlpha=c,this._lineTint=b,this.fillColor=d,this.fillAlpha=e,this._fillTint=d,this.fill=f,this.shape=g,this.type=g.type},PIXI.GraphicsData.prototype.constructor=PIXI.GraphicsData,PIXI.GraphicsData.prototype.clone=function(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},c.Graphics=function(a,b,d){void 0===b&&(b=0),void 0===d&&(d=0),this.type=c.GRAPHICS,this.physicsType=c.SPRITE,PIXI.Graphics.call(this),c.Component.Core.init.call(this,a,b,d,"",null)},c.Graphics.prototype=Object.create(PIXI.Graphics.prototype),c.Graphics.prototype.constructor=c.Graphics,c.Component.Core.install.call(c.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),c.Graphics.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Graphics.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Graphics.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Graphics.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Graphics.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Graphics.prototype.destroy=function(a){this.clear(),c.Component.Destroy.prototype.destroy.call(this,a)},c.Graphics.prototype.drawTriangle=function(a,b){void 0===b&&(b=!1);var d=new c.Polygon(a);if(b){var e=new c.Point(this.game.camera.x-a[0].x,this.game.camera.y-a[0].y),f=new c.Point(a[1].x-a[0].x,a[1].y-a[0].y),g=new c.Point(a[1].x-a[2].x,a[1].y-a[2].y),h=g.cross(f);e.dot(h)>0&&this.drawPolygon(d)}else this.drawPolygon(d)},c.Graphics.prototype.drawTriangles=function(a,b,d){void 0===d&&(d=!1);var e,f=new c.Point,g=new c.Point,h=new c.Point,i=[];if(b)if(a[0]instanceof c.Point)for(e=0;e<b.length/3;e++)i.push(a[b[3*e]]),i.push(a[b[3*e+1]]),i.push(a[b[3*e+2]]),3===i.length&&(this.drawTriangle(i,d),i=[]);else for(e=0;e<b.length;e++)f.x=a[2*b[e]],f.y=a[2*b[e]+1],i.push(f.copyTo({})),3===i.length&&(this.drawTriangle(i,d),i=[]);else if(a[0]instanceof c.Point)for(e=0;e<a.length/3;e++)this.drawTriangle([a[3*e],a[3*e+1],a[3*e+2]],d);else for(e=0;e<a.length/6;e++)f.x=a[6*e+0],f.y=a[6*e+1],g.x=a[6*e+2],g.y=a[6*e+3],h.x=a[6*e+4],h.y=a[6*e+5],this.drawTriangle([f,g,h],d)},c.RenderTexture=function(a,b,d,e,f,g){void 0===e&&(e=""),void 0===f&&(f=c.scaleModes.DEFAULT),void 0===g&&(g=1),this.game=a,this.key=e,this.type=c.RENDERTEXTURE,this._tempMatrix=new PIXI.Matrix,PIXI.RenderTexture.call(this,b,d,this.game.renderer,f,g),this.render=c.RenderTexture.prototype.render},c.RenderTexture.prototype=Object.create(PIXI.RenderTexture.prototype),c.RenderTexture.prototype.constructor=c.RenderTexture,c.RenderTexture.prototype.renderXY=function(a,b,c,d){a.updateTransform(),this._tempMatrix.copyFrom(a.worldTransform),this._tempMatrix.tx=b,this._tempMatrix.ty=c,this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(a,this._tempMatrix,d):this.renderCanvas(a,this._tempMatrix,d)},c.RenderTexture.prototype.renderRawXY=function(a,b,c,d){this._tempMatrix.identity().translate(b,c),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(a,this._tempMatrix,d):this.renderCanvas(a,this._tempMatrix,d)},c.RenderTexture.prototype.render=function(a,b,c){this._tempMatrix.copyFrom(void 0===b||null===b?a.worldTransform:b),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(a,this._tempMatrix,c):this.renderCanvas(a,this._tempMatrix,c)},c.Text=function(a,b,d,e,f){b=b||0,d=d||0,e=e.toString()||"",f=f||{},this.type=c.TEXT,this.physicsType=c.SPRITE,this.padding=new c.Point,this.textBounds=null,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.colors=[],this.strokeColors=[],this.autoRound=!1,this._res=a.renderer.resolution,this._text=e,this._fontComponents=null,this._lineSpacing=0,this._charCount=0,this._width=0,this._height=0,c.Sprite.call(this,a,b,d,PIXI.Texture.fromCanvas(this.canvas)),this.setStyle(f),""!==e&&this.updateText()},c.Text.prototype=Object.create(c.Sprite.prototype),c.Text.prototype.constructor=c.Text,c.Text.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1
+},c.Text.prototype.update=function(){},c.Text.prototype.destroy=function(a){this.texture.destroy(!0),this.canvas&&this.canvas.parentNode?this.canvas.parentNode.removeChild(this.canvas):(this.canvas=null,this.context=null),c.Component.Destroy.prototype.destroy.call(this,a)},c.Text.prototype.setShadow=function(a,b,c,d,e,f){return void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c="rgba(0, 0, 0, 1)"),void 0===d&&(d=0),void 0===e&&(e=!0),void 0===f&&(f=!0),this.style.shadowOffsetX=a,this.style.shadowOffsetY=b,this.style.shadowColor=c,this.style.shadowBlur=d,this.style.shadowStroke=e,this.style.shadowFill=f,this.dirty=!0,this},c.Text.prototype.setStyle=function(a){a=a||{},a.font=a.font||"bold 20pt Arial",a.backgroundColor=a.backgroundColor||null,a.fill=a.fill||"black",a.align=a.align||"left",a.boundsAlignH=a.boundsAlignH||"left",a.boundsAlignV=a.boundsAlignV||"top",a.stroke=a.stroke||"black",a.strokeThickness=a.strokeThickness||0,a.wordWrap=a.wordWrap||!1,a.wordWrapWidth=a.wordWrapWidth||100,a.shadowOffsetX=a.shadowOffsetX||0,a.shadowOffsetY=a.shadowOffsetY||0,a.shadowColor=a.shadowColor||"rgba(0,0,0,0)",a.shadowBlur=a.shadowBlur||0,a.tabs=a.tabs||0;var b=this.fontToComponents(a.font);return a.fontStyle&&(b.fontStyle=a.fontStyle),a.fontVariant&&(b.fontVariant=a.fontVariant),a.fontWeight&&(b.fontWeight=a.fontWeight),a.fontSize&&("number"==typeof a.fontSize&&(a.fontSize=a.fontSize+"px"),b.fontSize=a.fontSize),this._fontComponents=b,a.font=this.componentsToFont(this._fontComponents),this.style=a,this.dirty=!0,this},c.Text.prototype.updateText=function(){this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font;var a=this.text;this.style.wordWrap&&(a=this.runWordWrap(this.text));for(var b=a.split(/(?:\r\n|\r|\n)/),c=this.style.tabs,d=[],e=0,f=this.determineFontProperties(this.style.font),g=0;g<b.length;g++){if(0===c)var h=this.context.measureText(b[g]).width+this.style.strokeThickness+this.padding.x;else{var i=b[g].split(/(?:\t)/),h=this.padding.x+this.style.strokeThickness;if(Array.isArray(c))for(var j=0,k=0;k<i.length;k++){var l=Math.ceil(this.context.measureText(i[k]).width);k>0&&(j+=c[k-1]),h=j+l}else for(var k=0;k<i.length;k++){h+=Math.ceil(this.context.measureText(i[k]).width);var m=this.game.math.snapToCeil(h,c)-h;h+=m}}d[g]=Math.ceil(h),e=Math.max(e,d[g])}var n=e+this.style.strokeThickness;this.canvas.width=n*this._res;var o=f.fontSize+this.style.strokeThickness+this.padding.y,p=o*b.length,q=this._lineSpacing;if(0>q&&Math.abs(q)>o&&(q=-o),0!==q){var m=q*(b.length-1);p+=m}this.canvas.height=p*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var r,s;for(this._charCount=0,g=0;g<b.length;g++)r=this.style.strokeThickness/2,s=this.style.strokeThickness/2+g*o+f.ascent,g>0&&(s+=q*g),"right"===this.style.align?r+=e-d[g]:"center"===this.style.align&&(r+=(e-d[g])/2),this.autoRound&&(r=Math.round(r),s=Math.round(s)),this.colors.length>0||this.strokeColors.length>0?this.updateLine(b[g],r,s):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===c?this.context.strokeText(b[g],r,s):this.renderTabLine(b[g],r,s,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===c?this.context.fillText(b[g],r,s):this.renderTabLine(b[g],r,s,!0)));this.updateTexture()},c.Text.prototype.renderTabLine=function(a,b,c,d){var e=a.split(/(?:\t)/),f=this.style.tabs,g=0;if(Array.isArray(f))for(var h=0,i=0;i<e.length;i++)i>0&&(h+=f[i-1]),g=b+h,d?this.context.fillText(e[i],g,c):this.context.strokeText(e[i],g,c);else for(var i=0;i<e.length;i++){var j=Math.ceil(this.context.measureText(e[i]).width);g=this.game.math.snapToCeil(b,f),d?this.context.fillText(e[i],g,c):this.context.strokeText(e[i],g,c),b=g+j}},c.Text.prototype.updateShadow=function(a){a?(this.context.shadowOffsetX=this.style.shadowOffsetX,this.context.shadowOffsetY=this.style.shadowOffsetY,this.context.shadowColor=this.style.shadowColor,this.context.shadowBlur=this.style.shadowBlur):(this.context.shadowOffsetX=0,this.context.shadowOffsetY=0,this.context.shadowColor=0,this.context.shadowBlur=0)},c.Text.prototype.updateLine=function(a,b,c){for(var d=0;d<a.length;d++){var e=a[d];this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(e,b,c)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(e,b,c)),b+=this.context.measureText(e).width,this._charCount++}},c.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},c.Text.prototype.addColor=function(a,b){return this.colors[b]=a,this.dirty=!0,this},c.Text.prototype.addStrokeColor=function(a,b){return this.strokeColors[b]=a,this.dirty=!0,this},c.Text.prototype.runWordWrap=function(a){for(var b="",c=a.split("\n"),d=0;d<c.length;d++){for(var e=this.style.wordWrapWidth,f=c[d].split(" "),g=0;g<f.length;g++){var h=this.context.measureText(f[g]).width,i=h+this.context.measureText(" ").width;i>e?(g>0&&(b+="\n"),b+=f[g]+" ",e=this.style.wordWrapWidth-h):(e-=i,b+=f[g]+" ")}d<c.length-1&&(b+="\n")}return b},c.Text.prototype.updateFont=function(a){var b=this.componentsToFont(a);this.style.font!==b&&(this.style.font=b,this.dirty=!0,this.parent&&this.updateTransform())},c.Text.prototype.fontToComponents=function(a){var b=a.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);return b?{font:a,fontStyle:b[1]||"normal",fontVariant:b[2]||"normal",fontWeight:b[3]||"normal",fontSize:b[4]||"medium",fontFamily:b[5]}:(console.warn("Phaser.Text - unparsable CSS font: "+a),{font:a})},c.Text.prototype.componentsToFont=function(a){var b,c=[];return b=a.fontStyle,b&&"normal"!==b&&c.push(b),b=a.fontVariant,b&&"normal"!==b&&c.push(b),b=a.fontWeight,b&&"normal"!==b&&c.push(b),b=a.fontSize,b&&"medium"!==b&&c.push(b),b=a.fontFamily,b&&c.push(b),c.length||c.push(a.font),c.join(" ")},c.Text.prototype.setText=function(a){return this.text=a.toString()||"",this.dirty=!0,this},c.Text.prototype.parseList=function(a){if(!Array.isArray(a))return this;for(var b="",c=0;c<a.length;c++)Array.isArray(a[c])?(b+=a[c].join("	"),c<a.length-1&&(b+="\n")):(b+=a[c],c<a.length-1&&(b+="	"));return this.text=b,this.dirty=!0,this},c.Text.prototype.setTextBounds=function(a,b,d,e){return void 0===a?this.textBounds=null:(this.textBounds?this.textBounds.setTo(a,b,d,e):this.textBounds=new c.Rectangle(a,b,d,e),this.style.wordWrapWidth>d&&(this.style.wordWrapWidth=d)),this.updateTexture(),this},c.Text.prototype.updateTexture=function(){var a=this.texture.baseTexture,b=this.texture.crop,c=this.texture.frame,d=this.canvas.width,e=this.canvas.height;if(a.width=d,a.height=e,b.width=d,b.height=e,c.width=d,c.height=e,this.texture.width=d,this.texture.height=e,this._width=d,this._height=e,this.textBounds){var f=this.textBounds.x,g=this.textBounds.y;"right"===this.style.boundsAlignH?f=this.textBounds.width-this.canvas.width:"center"===this.style.boundsAlignH&&(f=this.textBounds.halfWidth-this.canvas.width/2),"bottom"===this.style.boundsAlignV?g=this.textBounds.height-this.canvas.height:"middle"===this.style.boundsAlignV&&(g=this.textBounds.halfHeight-this.canvas.height/2),this.pivot.x=-f,this.pivot.y=-g}this.renderable=0!==d&&0!==e,this.texture.baseTexture.dirty()},c.Text.prototype._renderWebGL=function(a){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,a)},c.Text.prototype._renderCanvas=function(a){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,a)},c.Text.prototype.determineFontProperties=function(a){var b=c.Text.fontPropertiesCache[a];if(!b){b={};var d=c.Text.fontPropertiesCanvas,e=c.Text.fontPropertiesContext;e.font=a;var f=Math.ceil(e.measureText("|MÉq").width),g=Math.ceil(e.measureText("|MÉq").width),h=2*g;if(g=1.4*g|0,d.width=f,d.height=h,e.fillStyle="#f00",e.fillRect(0,0,f,h),e.font=a,e.textBaseline="alphabetic",e.fillStyle="#000",e.fillText("|MÉq",0,g),!e.getImageData(0,0,f,h))return b.ascent=g,b.descent=g+6,b.fontSize=b.ascent+b.descent,c.Text.fontPropertiesCache[a]=b,b;var i,j,k=e.getImageData(0,0,f,h).data,l=k.length,m=4*f,n=0,o=!1;for(i=0;g>i;i++){for(j=0;m>j;j+=4)if(255!==k[n+j]){o=!0;break}if(o)break;n+=m}for(b.ascent=g-i,n=l-m,o=!1,i=h;i>g;i--){for(j=0;m>j;j+=4)if(255!==k[n+j]){o=!0;break}if(o)break;n-=m}b.descent=i-g,b.descent+=6,b.fontSize=b.ascent+b.descent,c.Text.fontPropertiesCache[a]=b}return b},c.Text.prototype.getBounds=function(a){return this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype.getBounds.call(this,a)},Object.defineProperty(c.Text.prototype,"text",{get:function(){return this._text},set:function(a){a!==this._text&&(this._text=a.toString()||"",this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(c.Text.prototype,"cssFont",{get:function(){return this.componentsToFont(this._fontComponents)},set:function(a){a=a||"bold 20pt Arial",this._fontComponents=this.fontToComponents(a),this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"font",{get:function(){return this._fontComponents.fontFamily},set:function(a){a=a||"Arial",a=a.trim(),/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(a)||/['",]/.exec(a)||(a="'"+a+"'"),this._fontComponents.fontFamily=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontSize",{get:function(){var a=this._fontComponents.fontSize;return a&&/(?:^0$|px$)/.exec(a)?parseInt(a,10):a},set:function(a){a=a||"0","number"==typeof a&&(a+="px"),this._fontComponents.fontSize=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontWeight",{get:function(){return this._fontComponents.fontWeight||"normal"},set:function(a){a=a||"normal",this._fontComponents.fontWeight=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontStyle",{get:function(){return this._fontComponents.fontStyle||"normal"},set:function(a){a=a||"normal",this._fontComponents.fontStyle=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fontVariant",{get:function(){return this._fontComponents.fontVariant||"normal"},set:function(a){a=a||"normal",this._fontComponents.fontVariant=a,this.updateFont(this._fontComponents)}}),Object.defineProperty(c.Text.prototype,"fill",{get:function(){return this.style.fill},set:function(a){a!==this.style.fill&&(this.style.fill=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"align",{get:function(){return this.style.align},set:function(a){a!==this.style.align&&(this.style.align=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"resolution",{get:function(){return this._res},set:function(a){a!==this._res&&(this._res=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"tabs",{get:function(){return this.style.tabs},set:function(a){a!==this.style.tabs&&(this.style.tabs=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"boundsAlignH",{get:function(){return this.style.boundsAlignH},set:function(a){a!==this.style.boundsAlignH&&(this.style.boundsAlignH=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"boundsAlignV",{get:function(){return this.style.boundsAlignV},set:function(a){a!==this.style.boundsAlignV&&(this.style.boundsAlignV=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"stroke",{get:function(){return this.style.stroke},set:function(a){a!==this.style.stroke&&(this.style.stroke=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"strokeThickness",{get:function(){return this.style.strokeThickness},set:function(a){a!==this.style.strokeThickness&&(this.style.strokeThickness=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"wordWrap",{get:function(){return this.style.wordWrap},set:function(a){a!==this.style.wordWrap&&(this.style.wordWrap=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"wordWrapWidth",{get:function(){return this.style.wordWrapWidth},set:function(a){a!==this.style.wordWrapWidth&&(this.style.wordWrapWidth=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"lineSpacing",{get:function(){return this._lineSpacing},set:function(a){a!==this._lineSpacing&&(this._lineSpacing=parseFloat(a),this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(c.Text.prototype,"shadowOffsetX",{get:function(){return this.style.shadowOffsetX},set:function(a){a!==this.style.shadowOffsetX&&(this.style.shadowOffsetX=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowOffsetY",{get:function(){return this.style.shadowOffsetY},set:function(a){a!==this.style.shadowOffsetY&&(this.style.shadowOffsetY=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowColor",{get:function(){return this.style.shadowColor},set:function(a){a!==this.style.shadowColor&&(this.style.shadowColor=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowBlur",{get:function(){return this.style.shadowBlur},set:function(a){a!==this.style.shadowBlur&&(this.style.shadowBlur=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowStroke",{get:function(){return this.style.shadowStroke},set:function(a){a!==this.style.shadowStroke&&(this.style.shadowStroke=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"shadowFill",{get:function(){return this.style.shadowFill},set:function(a){a!==this.style.shadowFill&&(this.style.shadowFill=a,this.dirty=!0)}}),Object.defineProperty(c.Text.prototype,"width",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.x*this.texture.frame.width},set:function(a){this.scale.x=a/this.texture.frame.width,this._width=a}}),Object.defineProperty(c.Text.prototype,"height",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.y*this.texture.frame.height},set:function(a){this.scale.y=a/this.texture.frame.height,this._height=a}}),c.Text.fontPropertiesCache={},c.Text.fontPropertiesCanvas=document.createElement("canvas"),c.Text.fontPropertiesContext=c.Text.fontPropertiesCanvas.getContext("2d"),c.BitmapText=function(a,b,d,e,f,g,h){b=b||0,d=d||0,e=e||"",f=f||"",g=g||32,h=h||"left",PIXI.DisplayObjectContainer.call(this),this.type=c.BITMAPTEXT,this.physicsType=c.SPRITE,this.textWidth=0,this.textHeight=0,this.anchor=new c.Point,this._prevAnchor=new c.Point,this._glyphs=[],this._maxWidth=0,this._text=f,this._data=a.cache.getBitmapFont(e),this._font=e,this._fontSize=g,this._align=h,this._tint=16777215,this.updateText(),this.dirty=!1,c.Component.Core.init.call(this,a,b,d,"",null)},c.BitmapText.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),c.BitmapText.prototype.constructor=c.BitmapText,c.Component.Core.install.call(c.BitmapText.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),c.BitmapText.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.BitmapText.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.BitmapText.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.BitmapText.prototype.preUpdateCore=c.Component.Core.preUpdate,c.BitmapText.prototype.preUpdate=function(){return this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.BitmapText.prototype.postUpdate=function(){c.Component.PhysicsBody.postUpdate.call(this),c.Component.FixedToCamera.postUpdate.call(this),this.body&&this.body.type===c.Physics.ARCADE&&(this.textWidth!==this.body.sourceWidth||this.textHeight!==this.body.sourceHeight)&&this.body.setSize(this.textWidth,this.textHeight)},c.BitmapText.prototype.setText=function(a){this.text=a},c.BitmapText.prototype.scanLine=function(a,b,c){for(var d=0,e=0,f=-1,g=null,h=this._maxWidth>0?this._maxWidth:null,i=[],j=0;j<c.length;j++){var k=j===c.length-1?!0:!1;if(/(?:\r\n|\r|\n)/.test(c.charAt(j)))return{width:e,text:c.substr(0,j),end:k,chars:i};var l=c.charCodeAt(j),m=a.chars[l],n=0;if(m){var o=g&&m.kerning[g]?m.kerning[g]:0;if(f=/(\s)/.test(c.charAt(j))?j:f,n=(o+m.texture.width+m.xOffset)*b,h&&e+n>=h&&f>-1)return{width:e,text:c.substr(0,j-(j-f)),end:k,chars:i};e+=m.xAdvance*b,i.push(d+m.xOffset*b),d+=m.xAdvance*b,g=l}}return{width:e,text:c,end:k,chars:i}},c.BitmapText.prototype.updateText=function(){var a=this._data.font;if(a){var b=this.text,c=this._fontSize/a.size,d=[],e=0;this.textWidth=0;do{var f=this.scanLine(a,c,b);f.y=e,d.push(f),f.width>this.textWidth&&(this.textWidth=f.width),e+=a.lineHeight*c,b=b.substr(f.text.length+1)}while(f.end===!1);this.textHeight=e;for(var g=0,h=0,i=this.textWidth*this.anchor.x,j=this.textHeight*this.anchor.y,k=0;k<d.length;k++){var f=d[k];"right"===this._align?h=this.textWidth-f.width:"center"===this._align&&(h=(this.textWidth-f.width)/2);for(var l=0;l<f.text.length;l++){var m=f.text.charCodeAt(l),n=a.chars[m],o=this._glyphs[g];o?o.texture=n.texture:(o=new PIXI.Sprite(n.texture),o.name=f.text[l],this._glyphs.push(o)),o.position.x=f.chars[l]+h-i,o.position.y=f.y+n.yOffset*c-j,o.scale.set(c),o.tint=this.tint,o.parent||this.addChild(o),g++}}for(k=g;k<this._glyphs.length;k++)this.removeChild(this._glyphs[k])}},c.BitmapText.prototype.purgeGlyphs=function(){for(var a=this._glyphs.length,b=[],c=0;c<this._glyphs.length;c++)this._glyphs[c].parent!==this?this._glyphs[c].destroy():b.push(this._glyphs[c]);return this._glyphs=[],this._glyphs=b,this.updateText(),a-b.length},c.BitmapText.prototype.updateTransform=function(){(this.dirty||!this.anchor.equals(this._prevAnchor))&&(this.updateText(),this.dirty=!1,this._prevAnchor.copyFrom(this.anchor)),PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)},Object.defineProperty(c.BitmapText.prototype,"align",{get:function(){return this._align},set:function(a){a===this._align||"left"!==a&&"center"!==a&&"right"!==a||(this._align=a,this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"tint",{get:function(){return this._tint},set:function(a){a!==this._tint&&(this._tint=a,this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"font",{get:function(){return this._font},set:function(a){a!==this._font&&(this._font=a.trim(),this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"fontSize",{get:function(){return this._fontSize},set:function(a){a=parseInt(a,10),a!==this._fontSize&&a>0&&(this._fontSize=a,this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"text",{get:function(){return this._text},set:function(a){a!==this._text&&(this._text=a.toString()||"",this.updateText())}}),Object.defineProperty(c.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(a){a!==this._maxWidth&&(this._maxWidth=a,this.updateText())}}),c.RetroFont=function(a,b,d,e,f,g,h,i,j,k){if(!a.cache.checkImageKey(b))return!1;(void 0===g||null===g)&&(g=a.cache.getImage(b).width/d),this.characterWidth=d,this.characterHeight=e,this.characterSpacingX=h||0,this.characterSpacingY=i||0,this.characterPerRow=g,this.offsetX=j||0,this.offsetY=k||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=a.cache.getImage(b),this._text="",this.grabData=[],this.frameData=new c.FrameData;for(var l=this.offsetX,m=this.offsetY,n=0,o=0;o<f.length;o++){var p=this.frameData.addFrame(new c.Frame(o,l,m,this.characterWidth,this.characterHeight));this.grabData[f.charCodeAt(o)]=p.index,n++,n===this.characterPerRow?(n=0,l=this.offsetX,m+=this.characterHeight+this.characterSpacingY):l+=this.characterWidth+this.characterSpacingX}a.cache.updateFrameData(b,this.frameData),this.stamp=new c.Image(a,0,0,b,0),c.RenderTexture.call(this,a,100,100,"",c.scaleModes.NEAREST),this.type=c.RETROFONT},c.RetroFont.prototype=Object.create(c.RenderTexture.prototype),c.RetroFont.prototype.constructor=c.RetroFont,c.RetroFont.ALIGN_LEFT="left",c.RetroFont.ALIGN_RIGHT="right",c.RetroFont.ALIGN_CENTER="center",c.RetroFont.TEXT_SET1=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",c.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",c.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",c.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",c.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",c.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",c.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",c.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",c.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",c.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",c.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",c.RetroFont.prototype.setFixedWidth=function(a,b){void 0===b&&(b="left"),this.fixedWidth=a,this.align=b},c.RetroFont.prototype.setText=function(a,b,c,d,e,f){this.multiLine=b||!1,this.customSpacingX=c||0,this.customSpacingY=d||0,this.align=e||"left",this.autoUpperCase=f?!1:!0,a.length>0&&(this.text=a)},c.RetroFont.prototype.buildRetroFontText=function(){var a=0,b=0;if(this.clear(),this.multiLine){var d=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,d.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),d.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var e=0;e<d.length;e++)a=0,this.align===c.RetroFont.ALIGN_RIGHT?a=this.width-d[e].length*(this.characterWidth+this.customSpacingX):this.align===c.RetroFont.ALIGN_CENTER&&(a=this.width/2-d[e].length*(this.characterWidth+this.customSpacingX)/2,a+=this.customSpacingX/2),0>a&&(a=0),this.pasteLine(d[e],a,b,this.customSpacingX),b+=this.characterHeight+this.customSpacingY}else this.fixedWidth>0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),a=0,this.align===c.RetroFont.ALIGN_RIGHT?a=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===c.RetroFont.ALIGN_CENTER&&(a=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,a+=this.customSpacingX/2),0>a&&(a=0),this.pasteLine(this._text,a,0,this.customSpacingX);this.requiresReTint=!0},c.RetroFont.prototype.pasteLine=function(a,b,c,d){for(var e=0;e<a.length;e++)if(" "===a.charAt(e))b+=this.characterWidth+d;else if(this.grabData[a.charCodeAt(e)]>=0&&(this.stamp.frame=this.grabData[a.charCodeAt(e)],this.renderXY(this.stamp,b,c,!1),b+=this.characterWidth+d,b>this.width))break},c.RetroFont.prototype.getLongestLine=function(){var a=0;if(this._text.length>0)for(var b=this._text.split("\n"),c=0;c<b.length;c++)b[c].length>a&&(a=b[c].length);return a},c.RetroFont.prototype.removeUnsupportedCharacters=function(a){for(var b="",c=0;c<this._text.length;c++){var d=this._text[c],e=d.charCodeAt(0);(this.grabData[e]>=0||!a&&"\n"===d)&&(b=b.concat(d))}return b},c.RetroFont.prototype.updateOffset=function(a,b){if(this.offsetX!==a||this.offsetY!==b){for(var c=a-this.offsetX,d=b-this.offsetY,e=this.game.cache.getFrameData(this.stamp.key).getFrames(),f=e.length;f--;)e[f].x+=c,e[f].y+=d;this.buildRetroFontText()}},Object.defineProperty(c.RetroFont.prototype,"text",{get:function(){return this._text},set:function(a){var b;b=this.autoUpperCase?a.toUpperCase():a,b!==this._text&&(this._text=b,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(c.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(a){this.stamp.smoothed=a,this.buildRetroFontText()}}),c.Rope=function(a,b,d,e,f,g){this.points=[],this.points=g,this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,b=b||0,d=d||0,e=e||null,f=f||null,this.type=c.ROPE,this._scroll=new c.Point,PIXI.Rope.call(this,PIXI.TextureCache.__default,this.points),c.Component.Core.init.call(this,a,b,d,e,f)},c.Rope.prototype=Object.create(PIXI.Rope.prototype),c.Rope.prototype.constructor=c.Rope,c.Component.Core.install.call(c.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),c.Rope.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.Rope.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.Rope.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.Rope.prototype.preUpdateCore=c.Component.Core.preUpdate,c.Rope.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},c.Rope.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},Object.defineProperty(c.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(a){a&&"function"==typeof a?(this._hasUpdateAnimation=!0,this._updateAnimation=a):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(c.Rope.prototype,"segments",{get:function(){for(var a,b,d,e,f,g,h,i,j=[],k=0;k<this.points.length;k++)a=4*k,b=this.vertices[a]*this.scale.x,d=this.vertices[a+1]*this.scale.y,e=this.vertices[a+4]*this.scale.x,f=this.vertices[a+3]*this.scale.y,g=c.Math.difference(b,e),h=c.Math.difference(d,f),b+=this.world.x,d+=this.world.y,i=new c.Rectangle(b,d,g,h),j.push(i);return j}}),c.TileSprite=function(a,b,d,e,f,g,h){b=b||0,d=d||0,e=e||256,f=f||256,g=g||null,h=h||null,this.type=c.TILESPRITE,this.physicsType=c.SPRITE,this._scroll=new c.Point;var i=a.cache.getImage("__default",!0);PIXI.TilingSprite.call(this,new PIXI.Texture(i.base),e,f),c.Component.Core.init.call(this,a,b,d,g,h)},c.TileSprite.prototype=Object.create(PIXI.TilingSprite.prototype),c.TileSprite.prototype.constructor=c.TileSprite,c.Component.Core.install.call(c.TileSprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","Smoothed"]),c.TileSprite.prototype.preUpdatePhysics=c.Component.PhysicsBody.preUpdate,c.TileSprite.prototype.preUpdateLifeSpan=c.Component.LifeSpan.preUpdate,c.TileSprite.prototype.preUpdateInWorld=c.Component.InWorld.preUpdate,c.TileSprite.prototype.preUpdateCore=c.Component.Core.preUpdate,c.TileSprite.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld()?this.preUpdateCore():!1},c.TileSprite.prototype.autoScroll=function(a,b){this._scroll.set(a,b)},c.TileSprite.prototype.stopScroll=function(){this._scroll.set(0,0)},c.TileSprite.prototype.destroy=function(a){c.Component.Destroy.prototype.destroy.call(this,a),PIXI.TilingSprite.prototype.destroy.call(this)},c.TileSprite.prototype.reset=function(a,b){return c.Component.Reset.prototype.reset.call(this,a,b),this.tilePosition.x=0,this.tilePosition.y=0,this},c.Device=function(){this.deviceReadyAt=0,this.initialized=!1,this.desktop=!1,this.iOS=!1,this.cocoonJS=!1,this.cocoonJSApp=!1,this.cordova=!1,this.node=!1,this.nodeWebkit=!1,this.electron=!1,this.ejecta=!1,this.crosswalk=!1,this.android=!1,this.chromeOS=!1,this.linux=!1,this.macOS=!1,this.windows=!1,this.windowsPhone=!1,this.canvas=!1,this.canvasBitBltShift=null,this.webGL=!1,this.file=!1,this.fileSystem=!1,this.localStorage=!1,this.worker=!1,this.css3D=!1,this.pointerLock=!1,this.typedArray=!1,this.vibration=!1,this.getUserMedia=!0,this.quirksMode=!1,this.touch=!1,this.mspointer=!1,this.wheelEvent=null,this.arora=!1,this.chrome=!1,this.chromeVersion=0,this.epiphany=!1,this.firefox=!1,this.firefoxVersion=0,this.ie=!1,this.ieVersion=0,this.trident=!1,this.tridentVersion=0,this.mobileSafari=!1,this.midori=!1,this.opera=!1,this.safari=!1,this.webApp=!1,this.silk=!1,this.audioData=!1,this.webAudio=!1,this.ogg=!1,this.opus=!1,this.mp3=!1,this.wav=!1,this.m4a=!1,this.webm=!1,this.oggVideo=!1,this.h264Video=!1,this.mp4Video=!1,this.webmVideo=!1,this.vp9Video=!1,this.hlsVideo=!1,this.iPhone=!1,this.iPhone4=!1,this.iPad=!1,this.pixelRatio=0,this.littleEndian=!1,this.LITTLE_ENDIAN=!1,this.support32bit=!1,this.fullscreen=!1,this.requestFullscreen="",this.cancelFullscreen="",this.fullscreenKeyboard=!1},c.Device=new c.Device,c.Device.onInitialized=new c.Signal,c.Device.whenReady=function(a,b,c){var d=this._readyCheck;if(this.deviceReadyAt||!d)a.call(b,this);else if(d._monitor||c)d._queue=d._queue||[],d._queue.push([a,b]);else{d._monitor=d.bind(this),d._queue=d._queue||[],d._queue.push([a,b]);var e="undefined"!=typeof window.cordova,f=navigator.isCocoonJS;"complete"===document.readyState||"interactive"===document.readyState?window.setTimeout(d._monitor,0):e&&!f?document.addEventListener("deviceready",d._monitor,!1):(document.addEventListener("DOMContentLoaded",d._monitor,!1),window.addEventListener("load",d._monitor,!1))}},c.Device._readyCheck=function(){var a=this._readyCheck;if(document.body){if(!this.deviceReadyAt){this.deviceReadyAt=Date.now(),document.removeEventListener("deviceready",a._monitor),document.removeEventListener("DOMContentLoaded",a._monitor),window.removeEventListener("load",a._monitor),this._initialize(),this.initialized=!0,this.onInitialized.dispatch(this);for(var b;b=a._queue.shift();){var c=b[0],d=b[1];c.call(d,this)}this._readyCheck=null,this._initialize=null,this.onInitialized=null}}else window.setTimeout(a._monitor,20)},c.Device._initialize=function(){function a(){var a=navigator.userAgent;/Playstation Vita/.test(a)?l.vita=!0:/Kindle/.test(a)||/\bKF[A-Z][A-Z]+/.test(a)||/Silk.*Mobile Safari/.test(a)?l.kindle=!0:/Android/.test(a)?l.android=!0:/CrOS/.test(a)?l.chromeOS=!0:/iP[ao]d|iPhone/i.test(a)?l.iOS=!0:/Linux/.test(a)?l.linux=!0:/Mac OS/.test(a)?l.macOS=!0:/Windows/.test(a)&&(l.windows=!0),(/Windows Phone/i.test(a)||/IEMobile/i.test(a))&&(l.android=!1,l.iOS=!1,l.macOS=!1,l.windows=!0,l.windowsPhone=!0);var b=/Silk/.test(a);(l.windows||l.macOS||l.linux&&!b||l.chromeOS)&&(l.desktop=!0),(l.windowsPhone||/Windows NT/i.test(a)&&/Touch/i.test(a))&&(l.desktop=!1)}function b(){l.canvas=!!window.CanvasRenderingContext2D||l.cocoonJS;try{l.localStorage=!!localStorage.getItem}catch(a){l.localStorage=!1}l.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),l.fileSystem=!!window.requestFileSystem,l.webGL=function(){try{var a=document.createElement("canvas");return a.screencanvas=!1,!!window.WebGLRenderingContext&&(a.getContext("webgl")||a.getContext("experimental-webgl"))}catch(b){return!1}}(),l.webGL=!!l.webGL,l.worker=!!window.Worker,l.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,l.quirksMode="CSS1Compat"===document.compatMode?!1:!0,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,l.getUserMedia=l.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,l.firefox&&l.firefoxVersion<21&&(l.getUserMedia=!1),!l.iOS&&(l.ie||l.firefox||l.chrome)&&(l.canvasBitBltShift=!0),(l.safari||l.mobileSafari)&&(l.canvasBitBltShift=!1)
+}function c(){("ontouchstart"in document.documentElement||window.navigator.maxTouchPoints&&window.navigator.maxTouchPoints>=1)&&(l.touch=!0),(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(l.mspointer=!0),l.cocoonJS||("onwheel"in window||l.ie&&"WheelEvent"in window?l.wheelEvent="wheel":"onmousewheel"in window?l.wheelEvent="mousewheel":l.firefox&&"MouseScrollEvent"in window&&(l.wheelEvent="DOMMouseScroll"))}function d(){for(var a=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],b=document.createElement("div"),c=0;c<a.length;c++)if(b[a[c]]){l.fullscreen=!0,l.requestFullscreen=a[c];break}var d=["cancelFullScreen","exitFullscreen","webkitCancelFullScreen","webkitExitFullscreen","msCancelFullScreen","msExitFullscreen","mozCancelFullScreen","mozExitFullscreen"];if(l.fullscreen)for(var c=0;c<d.length;c++)if(document[d[c]]){l.cancelFullscreen=d[c];break}window.Element&&Element.ALLOW_KEYBOARD_INPUT&&(l.fullscreenKeyboard=!0)}function e(){var a=navigator.userAgent;if(/Arora/.test(a)?l.arora=!0:/Chrome\/(\d+)/.test(a)&&!l.windowsPhone?(l.chrome=!0,l.chromeVersion=parseInt(RegExp.$1,10)):/Epiphany/.test(a)?l.epiphany=!0:/Firefox\D+(\d+)/.test(a)?(l.firefox=!0,l.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(a)&&l.iOS?l.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(a)?(l.ie=!0,l.ieVersion=parseInt(RegExp.$1,10)):/Midori/.test(a)?l.midori=!0:/Opera/.test(a)?l.opera=!0:/Safari/.test(a)&&!l.windowsPhone?l.safari=!0:/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(a)&&(l.ie=!0,l.trident=!0,l.tridentVersion=parseInt(RegExp.$1,10),l.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(a)&&(l.silk=!0),navigator.standalone&&(l.webApp=!0),"undefined"!=typeof window.cordova&&(l.cordova=!0),"undefined"!=typeof process&&"undefined"!=typeof require&&(l.node=!0),l.node&&"object"==typeof process.versions&&(l.nodeWebkit=!!process.versions["node-webkit"],l.electron=!!process.versions.electron),navigator.isCocoonJS&&(l.cocoonJS=!0),l.cocoonJS)try{l.cocoonJSApp="undefined"!=typeof CocoonJS}catch(b){l.cocoonJSApp=!1}"undefined"!=typeof window.ejecta&&(l.ejecta=!0),/Crosswalk/.test(a)&&(l.crosswalk=!0)}function f(){var a=document.createElement("video"),b=!1;try{(b=!!a.canPlayType)&&(a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(l.oggVideo=!0),a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(l.h264Video=!0,l.mp4Video=!0),a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(l.webmVideo=!0),a.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(l.vp9Video=!0),a.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(l.hlsVideo=!0))}catch(c){}}function g(){l.audioData=!!window.Audio,l.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var a=document.createElement("audio"),b=!1;try{(b=!!a.canPlayType)&&(a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(l.ogg=!0),(a.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||a.canPlayType("audio/opus;").replace(/^no$/,""))&&(l.opus=!0),a.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(l.mp3=!0),a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(l.wav=!0),(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;").replace(/^no$/,""))&&(l.m4a=!0),a.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(l.webm=!0))}catch(c){}}function h(){l.pixelRatio=window.devicePixelRatio||1,l.iPhone=-1!=navigator.userAgent.toLowerCase().indexOf("iphone"),l.iPhone4=2==l.pixelRatio&&l.iPhone,l.iPad=-1!=navigator.userAgent.toLowerCase().indexOf("ipad"),l.typedArray="undefined"!=typeof Int8Array?!0:!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(l.littleEndian=i(),l.LITTLE_ENDIAN=l.littleEndian),l.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==l.littleEndian&&j(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(l.vibration=!0)}function i(){var a=new ArrayBuffer(4),b=new Uint8Array(a),c=new Uint32Array(a);return b[0]=161,b[1]=178,b[2]=195,b[3]=212,3569595041==c[0]?!0:2712847316==c[0]?!1:null}function j(){if(void 0===Uint8ClampedArray)return!1;var a=document.createElement("canvas"),b=a.getContext("2d");if(!b)return!1;var c=b.createImageData(1,1);return c.data instanceof Uint8ClampedArray}function k(){var a,b=document.createElement("p"),c={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(b,null);for(var d in c)void 0!==b.style[d]&&(b.style[d]="translate3d(1px,1px,1px)",a=window.getComputedStyle(b).getPropertyValue(c[d]));document.body.removeChild(b),l.css3D=void 0!==a&&a.length>0&&"none"!==a}var l=this;a(),g(),f(),e(),k(),h(),b(),d(),c()},c.Device.canPlayAudio=function(a){return"mp3"===a&&this.mp3?!0:"ogg"===a&&(this.ogg||this.opus)?!0:"m4a"===a&&this.m4a?!0:"opus"===a&&this.opus?!0:"wav"===a&&this.wav?!0:"webm"===a&&this.webm?!0:!1},c.Device.canPlayVideo=function(a){return"webm"===a&&(this.webmVideo||this.vp9Video)?!0:"mp4"===a&&(this.mp4Video||this.h264Video)?!0:"ogg"!==a&&"ogv"!==a||!this.oggVideo?"mpeg"===a&&this.hlsVideo?!0:!1:!0},c.Device.isConsoleOpen=function(){return window.console&&window.console.firebug?!0:window.console&&(console.profile(),console.profileEnd(),console.clear&&console.clear(),console.profiles)?console.profiles.length>0:!1},c.Device.isAndroidStockBrowser=function(){var a=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return a&&a[1]<537},c.DOM={getOffset:function(a,b){b=b||new c.Point;var d=a.getBoundingClientRect(),e=c.DOM.scrollY,f=c.DOM.scrollX,g=document.documentElement.clientTop,h=document.documentElement.clientLeft;return b.x=d.left+f-h,b.y=d.top+e-g,b},getBounds:function(a,b){return void 0===b&&(b=0),a=a&&!a.nodeType?a[0]:a,a&&1===a.nodeType?this.calibrate(a.getBoundingClientRect(),b):!1},calibrate:function(a,b){b=+b||0;var c={width:0,height:0,left:0,right:0,top:0,bottom:0};return c.width=(c.right=a.right+b)-(c.left=a.left-b),c.height=(c.bottom=a.bottom+b)-(c.top=a.top-b),c},getAspectRatio:function(a){a=null==a?this.visualBounds:1===a.nodeType?this.getBounds(a):a;var b=a.width,c=a.height;return"function"==typeof b&&(b=b.call(a)),"function"==typeof c&&(c=c.call(a)),b/c},inLayoutViewport:function(a,b){var c=this.getBounds(a,b);return!!c&&c.bottom>=0&&c.right>=0&&c.top<=this.layoutBounds.width&&c.left<=this.layoutBounds.height},getScreenOrientation:function(a){var b=window.screen,c=b.orientation||b.mozOrientation||b.msOrientation;if(c&&"string"==typeof c.type)return c.type;if("string"==typeof c)return c;var d="portrait-primary",e="landscape-primary";if("screen"===a)return b.height>b.width?d:e;if("viewport"===a)return this.visualBounds.height>this.visualBounds.width?d:e;if("window.orientation"===a&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?d:e;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return d;if(window.matchMedia("(orientation: landscape)").matches)return e}return this.visualBounds.height>this.visualBounds.width?d:e},visualBounds:new c.Rectangle,layoutBounds:new c.Rectangle,documentBounds:new c.Rectangle},c.Device.whenReady(function(a){var b=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},d=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};Object.defineProperty(c.DOM,"scrollX",{get:b}),Object.defineProperty(c.DOM,"scrollY",{get:d}),Object.defineProperty(c.DOM.visualBounds,"x",{get:b}),Object.defineProperty(c.DOM.visualBounds,"y",{get:d}),Object.defineProperty(c.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(c.DOM.layoutBounds,"y",{value:0});var e=a.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight;if(e){var f=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},g=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(c.DOM.visualBounds,"width",{get:f}),Object.defineProperty(c.DOM.visualBounds,"height",{get:g}),Object.defineProperty(c.DOM.layoutBounds,"width",{get:f}),Object.defineProperty(c.DOM.layoutBounds,"height",{get:g})}else Object.defineProperty(c.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(c.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(c.DOM.layoutBounds,"width",{get:function(){var a=document.documentElement.clientWidth,b=window.innerWidth;return b>a?b:a}}),Object.defineProperty(c.DOM.layoutBounds,"height",{get:function(){var a=document.documentElement.clientHeight,b=window.innerHeight;return b>a?b:a}});Object.defineProperty(c.DOM.documentBounds,"x",{value:0}),Object.defineProperty(c.DOM.documentBounds,"y",{value:0}),Object.defineProperty(c.DOM.documentBounds,"width",{get:function(){var a=document.documentElement;return Math.max(a.clientWidth,a.offsetWidth,a.scrollWidth)}}),Object.defineProperty(c.DOM.documentBounds,"height",{get:function(){var a=document.documentElement;return Math.max(a.clientHeight,a.offsetHeight,a.scrollHeight)}})},null,!0),c.Canvas={create:function(a,b,c){a=a||256,b=b||256;var d=document.createElement("canvas");return"string"==typeof c&&""!==c&&(d.id=c),d.width=a,d.height=b,d.style.display="block",d},setBackgroundColor:function(a,b){return b=b||"rgb(0,0,0)",a.style.backgroundColor=b,a},setTouchAction:function(a,b){return b=b||"none",a.style.msTouchAction=b,a.style["ms-touch-action"]=b,a.style["touch-action"]=b,a},setUserSelect:function(a,b){return b=b||"none",a.style["-webkit-touch-callout"]=b,a.style["-webkit-user-select"]=b,a.style["-khtml-user-select"]=b,a.style["-moz-user-select"]=b,a.style["-ms-user-select"]=b,a.style["user-select"]=b,a.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",a},addToDOM:function(a,b,c){var d;return void 0===c&&(c=!0),b&&("string"==typeof b?d=document.getElementById(b):"object"==typeof b&&1===b.nodeType&&(d=b)),d||(d=document.body),c&&d.style&&(d.style.overflow="hidden"),d.appendChild(a),a},removeFromDOM:function(a){a.parentNode&&a.parentNode.removeChild(a)},setTransform:function(a,b,c,d,e,f,g){return a.setTransform(d,f,g,e,b,c),a},setSmoothingEnabled:function(a,b){var c=["i","mozI","oI","webkitI","msI"];for(var d in c){var e=c[d]+"mageSmoothingEnabled";if(e in a)return a[e]=b,a}return a},getSmoothingEnabled:function(a){return a.imageSmoothingEnabled||a.mozImageSmoothingEnabled||a.oImageSmoothingEnabled||a.webkitImageSmoothingEnabled||a.msImageSmoothingEnabled},setImageRenderingCrisp:function(a){return a.style["image-rendering"]="optimizeSpeed",a.style["image-rendering"]="crisp-edges",a.style["image-rendering"]="-moz-crisp-edges",a.style["image-rendering"]="-webkit-optimize-contrast",a.style["image-rendering"]="optimize-contrast",a.style["image-rendering"]="pixelated",a.style.msInterpolationMode="nearest-neighbor",a},setImageRenderingBicubic:function(a){return a.style["image-rendering"]="auto",a.style.msInterpolationMode="bicubic",a}},c.RequestAnimationFrame=function(a,b){void 0===b&&(b=!1),this.game=a,this.isRunning=!1,this.forceSetTimeOut=b;for(var c=["ms","moz","webkit","o"],d=0;d<c.length&&!window.requestAnimationFrame;d++)window.requestAnimationFrame=window[c[d]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[c[d]+"CancelAnimationFrame"];this._isSetTimeOut=!1,this._onLoop=null,this._timeOutID=null},c.RequestAnimationFrame.prototype={start:function(){this.isRunning=!0;var a=this;!window.requestAnimationFrame||this.forceSetTimeOut?(this._isSetTimeOut=!0,this._onLoop=function(){return a.updateSetTimeout()},this._timeOutID=window.setTimeout(this._onLoop,0)):(this._isSetTimeOut=!1,this._onLoop=function(b){return a.updateRAF(b)},this._timeOutID=window.requestAnimationFrame(this._onLoop))},updateRAF:function(a){this.game.update(Math.floor(a)),this._timeOutID=window.requestAnimationFrame(this._onLoop)},updateSetTimeout:function(){this.game.update(Date.now()),this._timeOutID=window.setTimeout(this._onLoop,this.game.time.timeToCall)},stop:function(){this._isSetTimeOut?clearTimeout(this._timeOutID):window.cancelAnimationFrame(this._timeOutID),this.isRunning=!1},isSetTimeOut:function(){return this._isSetTimeOut},isRAF:function(){return this._isSetTimeOut===!1}},c.RequestAnimationFrame.prototype.constructor=c.RequestAnimationFrame,c.Math={PI2:2*Math.PI,fuzzyEqual:function(a,b,c){return void 0===c&&(c=1e-4),Math.abs(a-b)<c},fuzzyLessThan:function(a,b,c){return void 0===c&&(c=1e-4),b+c>a},fuzzyGreaterThan:function(a,b,c){return void 0===c&&(c=1e-4),a>b-c},fuzzyCeil:function(a,b){return void 0===b&&(b=1e-4),Math.ceil(a-b)},fuzzyFloor:function(a,b){return void 0===b&&(b=1e-4),Math.floor(a+b)},average:function(){for(var a=0,b=0;b<arguments.length;b++)a+=+arguments[b];return a/arguments.length},shear:function(a){return a%1},snapTo:function(a,b,c){return void 0===c&&(c=0),0===b?a:(a-=c,a=b*Math.round(a/b),c+a)},snapToFloor:function(a,b,c){return void 0===c&&(c=0),0===b?a:(a-=c,a=b*Math.floor(a/b),c+a)},snapToCeil:function(a,b,c){return void 0===c&&(c=0),0===b?a:(a-=c,a=b*Math.ceil(a/b),c+a)},roundTo:function(a,b,c){void 0===b&&(b=0),void 0===c&&(c=10);var d=Math.pow(c,-b);return Math.round(a*d)/d},floorTo:function(a,b,c){void 0===b&&(b=0),void 0===c&&(c=10);var d=Math.pow(c,-b);return Math.floor(a*d)/d},ceilTo:function(a,b,c){void 0===b&&(b=0),void 0===c&&(c=10);var d=Math.pow(c,-b);return Math.ceil(a*d)/d},angleBetween:function(a,b,c,d){return Math.atan2(d-b,c-a)},angleBetweenY:function(a,b,c,d){return Math.atan2(c-a,d-b)},angleBetweenPoints:function(a,b){return Math.atan2(b.y-a.y,b.x-a.x)},angleBetweenPointsY:function(a,b){return Math.atan2(b.x-a.x,b.y-a.y)},reverseAngle:function(a){return this.normalizeAngle(a+Math.PI,!0)},normalizeAngle:function(a){return a%=2*Math.PI,a>=0?a:a+2*Math.PI},maxAdd:function(a,b,c){return Math.min(a+b,c)},minSub:function(a,b,c){return Math.max(a-b,c)},wrap:function(a,b,c){var d=c-b;if(0>=d)return 0;var e=(a-b)%d;return 0>e&&(e+=d),e+b},wrapValue:function(a,b,c){var d;return a=Math.abs(a),b=Math.abs(b),c=Math.abs(c),d=(a+b)%c},isOdd:function(a){return!!(1&a)},isEven:function(a){return!(1&a)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])var a=arguments[0];else var a=arguments;for(var b=1,c=0,d=a.length;d>b;b++)a[b]<a[c]&&(c=b);return a[c]},max:function(){if(1===arguments.length&&"object"==typeof arguments[0])var a=arguments[0];else var a=arguments;for(var b=1,c=0,d=a.length;d>b;b++)a[b]>a[c]&&(c=b);return a[c]},minProperty:function(a){if(2===arguments.length&&"object"==typeof arguments[1])var b=arguments[1];else var b=arguments.slice(1);for(var c=1,d=0,e=b.length;e>c;c++)b[c][a]<b[d][a]&&(d=c);return b[d][a]},maxProperty:function(a){if(2===arguments.length&&"object"==typeof arguments[1])var b=arguments[1];else var b=arguments.slice(1);for(var c=1,d=0,e=b.length;e>c;c++)b[c][a]>b[d][a]&&(d=c);return b[d][a]},wrapAngle:function(a,b){return b?this.wrap(a,-Math.PI,Math.PI):this.wrap(a,-180,180)},linearInterpolation:function(a,b){var c=a.length-1,d=c*b,e=Math.floor(d);return 0>b?this.linear(a[0],a[1],d):b>1?this.linear(a[c],a[c-1],c-d):this.linear(a[e],a[e+1>c?c:e+1],d-e)},bezierInterpolation:function(a,b){for(var c=0,d=a.length-1,e=0;d>=e;e++)c+=Math.pow(1-b,d-e)*Math.pow(b,e)*a[e]*this.bernstein(d,e);return c},catmullRomInterpolation:function(a,b){var c=a.length-1,d=c*b,e=Math.floor(d);return a[0]===a[c]?(0>b&&(e=Math.floor(d=c*(1+b))),this.catmullRom(a[(e-1+c)%c],a[e],a[(e+1)%c],a[(e+2)%c],d-e)):0>b?a[0]-(this.catmullRom(a[0],a[0],a[1],a[1],-d)-a[0]):b>1?a[c]-(this.catmullRom(a[c],a[c],a[c-1],a[c-1],d-c)-a[c]):this.catmullRom(a[e?e-1:0],a[e],a[e+1>c?c:e+1],a[e+2>c?c:e+2],d-e)},linear:function(a,b,c){return(b-a)*c+a},bernstein:function(a,b){return this.factorial(a)/this.factorial(b)/this.factorial(a-b)},factorial:function(a){if(0===a)return 1;for(var b=a;--a;)b*=a;return b},catmullRom:function(a,b,c,d,e){var f=.5*(c-a),g=.5*(d-b),h=e*e,i=e*h;return(2*b-2*c+f+g)*i+(-3*b+3*c-2*f-g)*h+f*e+b},difference:function(a,b){return Math.abs(a-b)},roundAwayFromZero:function(a){return a>0?Math.ceil(a):Math.floor(a)},sinCosGenerator:function(a,b,c,d){void 0===b&&(b=1),void 0===c&&(c=1),void 0===d&&(d=1);for(var e=b,f=c,g=d*Math.PI/a,h=[],i=[],j=0;a>j;j++)f-=e*g,e+=f*g,h[j]=f,i[j]=e;return{sin:i,cos:h,length:a}},distance:function(a,b,c,d){var e=a-c,f=b-d;return Math.sqrt(e*e+f*f)},distanceSq:function(a,b,c,d){var e=a-c,f=b-d;return e*e+f*f},distancePow:function(a,b,c,d,e){return void 0===e&&(e=2),Math.sqrt(Math.pow(c-a,e)+Math.pow(d-b,e))},clamp:function(a,b,c){return b>a?b:a>c?c:a},clampBottom:function(a,b){return b>a?b:a},within:function(a,b,c){return Math.abs(a-b)<=c},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},smoothstep:function(a,b,c){return a=Math.max(0,Math.min(1,(a-b)/(c-b))),a*a*(3-2*a)},smootherstep:function(a,b,c){return a=Math.max(0,Math.min(1,(a-b)/(c-b))),a*a*a*(a*(6*a-15)+10)},sign:function(a){return 0>a?-1:a>0?1:0},percent:function(a,b,c){return void 0===c&&(c=0),a>b||c>b?1:c>a||c>a?0:(a-c)/b}};var j=Math.PI/180,k=180/Math.PI;return c.Math.degToRad=function(a){return a*j},c.Math.radToDeg=function(a){return a*k},c.RandomDataGenerator=function(a){void 0===a&&(a=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,this.sow(a)},c.RandomDataGenerator.prototype={rnd:function(){var a=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|a,this.s0=this.s1,this.s1=this.s2,this.s2=a-this.c,this.s2},sow:function(a){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,a)for(var b=0;b<a.length&&null!=a[b];b++){var c=a[b];this.s0-=this.hash(c),this.s0+=~~(this.s0<0),this.s1-=this.hash(c),this.s1+=~~(this.s1<0),this.s2-=this.hash(c),this.s2+=~~(this.s2<0)}},hash:function(a){var b,c,d;for(d=4022871197,a=a.toString(),c=0;c<a.length;c++)d+=a.charCodeAt(c),b=.02519603282416938*d,d=b>>>0,b-=d,b*=d,d=b>>>0,b-=d,d+=4294967296*b;return 2.3283064365386963e-10*(d>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(a,b){return Math.floor(this.realInRange(0,b-a+1)+a)},between:function(a,b){return this.integerInRange(a,b)},realInRange:function(a,b){return this.frac()*(b-a)+a},normal:function(){return 1-2*this.frac()},uuid:function(){var a="",b="";for(b=a="";a++<36;b+=~a%5|3*a&4?(15^a?8^this.frac()*(20^a?16:4):4).toString(16):"-");return b},pick:function(a){return a[this.integerInRange(0,a.length-1)]},weightedPick:function(a){return a[~~(Math.pow(this.frac(),2)*(a.length-1)+.5)]},timestamp:function(a,b){return this.realInRange(a||9466848e5,b||1577862e6)},angle:function(){return this.integerInRange(-180,180)}},c.RandomDataGenerator.prototype.constructor=c.RandomDataGenerator,c.QuadTree=function(a,b,c,d,e,f,g){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(a,b,c,d,e,f,g)},c.QuadTree.prototype={reset:function(a,b,c,d,e,f,g){this.maxObjects=e||10,this.maxLevels=f||4,this.level=g||0,this.bounds={x:Math.round(a),y:Math.round(b),width:c,height:d,subWidth:Math.floor(c/2),subHeight:Math.floor(d/2),right:Math.round(a)+Math.floor(c/2),bottom:Math.round(b)+Math.floor(d/2)},this.objects.length=0,this.nodes.length=0},populate:function(a){a.forEach(this.populateHandler,this,!0)},populateHandler:function(a){a.body&&a.exists&&this.insert(a.body)},split:function(){this.nodes[0]=new c.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new c.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new c.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new c.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(a){var b,c=0;if(null!=this.nodes[0]&&(b=this.getIndex(a),-1!==b))return void this.nodes[b].insert(a);if(this.objects.push(a),this.objects.length>this.maxObjects&&this.level<this.maxLevels)for(null==this.nodes[0]&&this.split();c<this.objects.length;)b=this.getIndex(this.objects[c]),-1!==b?this.nodes[b].insert(this.objects.splice(c,1)[0]):c++},getIndex:function(a){var b=-1;return a.x<this.bounds.right&&a.right<this.bounds.right?a.y<this.bounds.bottom&&a.bottom<this.bounds.bottom?b=1:a.y>this.bounds.bottom&&(b=2):a.x>this.bounds.right&&(a.y<this.bounds.bottom&&a.bottom<this.bounds.bottom?b=0:a.y>this.bounds.bottom&&(b=3)),b},retrieve:function(a){if(a instanceof c.Rectangle)var b=this.objects,d=this.getIndex(a);else{if(!a.body)return this._empty;var b=this.objects,d=this.getIndex(a.body)}return this.nodes[0]&&(-1!==d?b=b.concat(this.nodes[d].retrieve(a)):(b=b.concat(this.nodes[0].retrieve(a)),b=b.concat(this.nodes[1].retrieve(a)),b=b.concat(this.nodes[2].retrieve(a)),b=b.concat(this.nodes[3].retrieve(a)))),b},clear:function(){this.objects.length=0;for(var a=this.nodes.length;a--;)this.nodes[a].clear(),this.nodes.splice(a,1);this.nodes.length=0}},c.QuadTree.prototype.constructor=c.QuadTree,c.Net=function(a){this.game=a},c.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(a){return-1!==window.location.hostname.indexOf(a)},updateQueryString:function(a,b,c,d){void 0===c&&(c=!1),(void 0===d||""===d)&&(d=window.location.href);var e="",f=new RegExp("([?|&])"+a+"=.*?(&|#|$)(.*)","gi");if(f.test(d))e="undefined"!=typeof b&&null!==b?d.replace(f,"$1"+a+"="+b+"$2$3"):d.replace(f,"$1$3").replace(/(&|\?)$/,"");else if("undefined"!=typeof b&&null!==b){var g=-1!==d.indexOf("?")?"&":"?",h=d.split("#");d=h[0]+g+a+"="+b,h[1]&&(d+="#"+h[1]),e=d}else e=d;return c?void(window.location.href=e):e},getQueryString:function(a){void 0===a&&(a="");var b={},c=location.search.substring(1).split("&");for(var d in c){var e=c[d].split("=");if(e.length>1){if(a&&a==this.decodeURI(e[0]))return this.decodeURI(e[1]);b[this.decodeURI(e[0])]=this.decodeURI(e[1])}}return b},decodeURI:function(a){return decodeURIComponent(a.replace(/\+/g," "))}},c.Net.prototype.constructor=c.Net,c.TweenManager=function(a){this.game=a,this._tweens=[],this._add=[],this.easeMap={Power0:c.Easing.Power0,Power1:c.Easing.Power1,Power2:c.Easing.Power2,Power3:c.Easing.Power3,Power4:c.Easing.Power4,Linear:c.Easing.Linear.None,Quad:c.Easing.Quadratic.Out,Cubic:c.Easing.Cubic.Out,Quart:c.Easing.Quartic.Out,Quint:c.Easing.Quintic.Out,Sine:c.Easing.Sinusoidal.Out,Expo:c.Easing.Exponential.Out,Circ:c.Easing.Circular.Out,Elastic:c.Easing.Elastic.Out,Back:c.Easing.Back.Out,Bounce:c.Easing.Bounce.Out,"Quad.easeIn":c.Easing.Quadratic.In,"Cubic.easeIn":c.Easing.Cubic.In,"Quart.easeIn":c.Easing.Quartic.In,"Quint.easeIn":c.Easing.Quintic.In,"Sine.easeIn":c.Easing.Sinusoidal.In,"Expo.easeIn":c.Easing.Exponential.In,"Circ.easeIn":c.Easing.Circular.In,"Elastic.easeIn":c.Easing.Elastic.In,"Back.easeIn":c.Easing.Back.In,"Bounce.easeIn":c.Easing.Bounce.In,"Quad.easeOut":c.Easing.Quadratic.Out,"Cubic.easeOut":c.Easing.Cubic.Out,"Quart.easeOut":c.Easing.Quartic.Out,"Quint.easeOut":c.Easing.Quintic.Out,"Sine.easeOut":c.Easing.Sinusoidal.Out,"Expo.easeOut":c.Easing.Exponential.Out,"Circ.easeOut":c.Easing.Circular.Out,"Elastic.easeOut":c.Easing.Elastic.Out,"Back.easeOut":c.Easing.Back.Out,"Bounce.easeOut":c.Easing.Bounce.Out,"Quad.easeInOut":c.Easing.Quadratic.InOut,"Cubic.easeInOut":c.Easing.Cubic.InOut,"Quart.easeInOut":c.Easing.Quartic.InOut,"Quint.easeInOut":c.Easing.Quintic.InOut,"Sine.easeInOut":c.Easing.Sinusoidal.InOut,"Expo.easeInOut":c.Easing.Exponential.InOut,"Circ.easeInOut":c.Easing.Circular.InOut,"Elastic.easeInOut":c.Easing.Elastic.InOut,"Back.easeInOut":c.Easing.Back.InOut,"Bounce.easeInOut":c.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},c.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var a=0;a<this._tweens.length;a++)this._tweens[a].pendingDelete=!0;this._add=[]},removeFrom:function(a,b){void 0===b&&(b=!0);var d,e;if(Array.isArray(a))for(d=0,e=a.length;e>d;d++)this.removeFrom(a[d]);else if(a.type===c.GROUP&&b)for(var d=0,e=a.children.length;e>d;d++)this.removeFrom(a.children[d]);else{for(d=0,e=this._tweens.length;e>d;d++)a===this._tweens[d].target&&this.remove(this._tweens[d]);for(d=0,e=this._add.length;e>d;d++)a===this._add[d].target&&this.remove(this._add[d])}},add:function(a){a._manager=this,this._add.push(a)},create:function(a){return new c.Tween(a,this.game,this)},remove:function(a){var b=this._tweens.indexOf(a);-1!==b?this._tweens[b].pendingDelete=!0:(b=this._add.indexOf(a),-1!==b&&(this._add[b].pendingDelete=!0))},update:function(){var a=this._add.length,b=this._tweens.length;if(0===b&&0===a)return!1;for(var c=0;b>c;)this._tweens[c].update(this.game.time.time)?c++:(this._tweens.splice(c,1),b--);return a>0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(a){return this._tweens.some(function(b){return b.target===a})},_pauseAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a]._pause()},_resumeAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a]._resume()},pauseAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a].pause()},resumeAll:function(){for(var a=this._tweens.length-1;a>=0;a--)this._tweens[a].resume(!0)}},c.TweenManager.prototype.constructor=c.TweenManager,c.Tween=function(a,b,d){this.game=b,this.target=a,this.manager=d,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new c.Signal,this.onLoop=new c.Signal,this.onRepeat=new c.Signal,this.onChildComplete=new c.Signal,this.onComplete=new c.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},c.Tween.prototype={to:function(a,b,d,e,f,g,h){return(void 0===b||0>=b)&&(b=1e3),(void 0===d||null===d)&&(d=c.Easing.Default),void 0===e&&(e=!1),void 0===f&&(f=0),void 0===g&&(g=0),void 0===h&&(h=!1),"string"==typeof d&&this.manager.easeMap[d]&&(d=this.manager.easeMap[d]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new c.TweenData(this).to(a,b,d,f,g,h)),e&&this.start(),this)},from:function(a,b,d,e,f,g,h){return void 0===b&&(b=1e3),(void 0===d||null===d)&&(d=c.Easing.Default),void 0===e&&(e=!1),void 0===f&&(f=0),void 0===g&&(g=0),void 0===h&&(h=!1),"string"==typeof d&&this.manager.easeMap[d]&&(d=this.manager.easeMap[d]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new c.TweenData(this).from(a,b,d,f,g,h)),e&&this.start(),this)},start:function(a){if(void 0===a&&(a=0),null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(var b=0;b<this.timeline.length;b++)for(var c in this.timeline[b].vEnd)this.properties[c]=this.target[c]||0,Array.isArray(this.properties[c])||(this.properties[c]*=1);for(var b=0;b<this.timeline.length;b++)this.timeline[b].loadValues();return this.manager.add(this),this.isRunning=!0,(0>a||a>this.timeline.length-1)&&(a=0),this.current=a,this.timeline[this.current].start(),this},stop:function(a){return void 0===a&&(a=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,a&&(this.onComplete.dispatch(this.target,this),this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(a,b,c){if(0===this.timeline.length)return this;if(void 0===c&&(c=0),-1===c)for(var d=0;d<this.timeline.length;d++)this.timeline[d][a]=b;else this.timeline[c][a]=b;return this},delay:function(a,b){return this.updateTweenData("delay",a,b)},repeat:function(a,b,c){return void 0===b&&(b=0),this.updateTweenData("repeatCounter",a,c),this.updateTweenData("repeatDelay",b,c)},repeatDelay:function(a,b){return this.updateTweenData("repeatDelay",a,b)},yoyo:function(a,b,c){return void 0===b&&(b=0),this.updateTweenData("yoyo",a,c),this.updateTweenData("yoyoDelay",b,c)},yoyoDelay:function(a,b){return this.updateTweenData("yoyoDelay",a,b)},easing:function(a,b){return"string"==typeof a&&this.manager.easeMap[a]&&(a=this.manager.easeMap[a]),this.updateTweenData("easingFunction",a,b)},interpolation:function(a,b,d){return void 0===b&&(b=c.Math),this.updateTweenData("interpolationFunction",a,d),this.updateTweenData("interpolationContext",b,d)},repeatAll:function(a){return void 0===a&&(a=0),this.repeatCounter=a,this},chain:function(){for(var a=arguments.length;a--;)a>0?arguments[a-1].chainedTween=arguments[a]:this.chainedTween=arguments[a];return this},loop:function(a){return void 0===a&&(a=!0),a?this.repeatAll(-1):this.repeatCounter=0,this},onUpdateCallback:function(a,b){return this._onUpdateCallback=a,this._onUpdateCallbackContext=b,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var a=0;a<this.timeline.length;a++)this.timeline[a].isRunning||(this.timeline[a].startTime+=this.game.time.time-this._pausedTime)}},_resume:function(){this._codePaused||this.resume()},update:function(a){if(this.pendingDelete)return!1;if(this.isPaused)return!0;var b=this.timeline[this.current].update(a);if(b===c.TweenData.PENDING)return!0;if(b===c.TweenData.RUNNING)return this._hasStarted||(this.onStart.dispatch(this.target,this),this._hasStarted=!0),null!==this._onUpdateCallback&&this._onUpdateCallback.call(this._onUpdateCallbackContext,this,this.timeline[this.current].value,this.timeline[this.current]),this.isRunning;if(b===c.TweenData.LOOPED)return this.onLoop.dispatch(this.target,this),!0;if(b===c.TweenData.COMPLETE){var d=!1;return this.reverse?(this.current--,this.current<0&&(this.current=this.timeline.length-1,d=!0)):(this.current++,this.current===this.timeline.length&&(this.current=0,d=!0)),d?-1===this.repeatCounter?(this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):this.repeatCounter>0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(a,b){if(null===this.game||null===this.target)return null;void 0===a&&(a=60),void 0===b&&(b=[]);for(var c=0;c<this.timeline.length;c++)for(var d in this.timeline[c].vEnd)this.properties[d]=this.target[d]||0,Array.isArray(this.properties[d])||(this.properties[d]*=1);for(var c=0;c<this.timeline.length;c++)this.timeline[c].loadValues();for(var c=0;c<this.timeline.length;c++)b=b.concat(this.timeline[c].generateData(a));return b}},Object.defineProperty(c.Tween.prototype,"totalDuration",{get:function(){for(var a=0,b=0;b<this.timeline.length;b++)a+=this.timeline[b].duration;return a}}),c.Tween.prototype.constructor=c.Tween,c.TweenData=function(a){this.parent=a,this.game=a.game,this.vStart={},this.vStartCache={},this.vEnd={},this.vEndCache={},this.duration=1e3,this.percent=0,this.value=0,this.repeatCounter=0,this.repeatDelay=0,this.interpolate=!1,this.yoyo=!1,this.yoyoDelay=0,this.inReverse=!1,this.delay=0,this.dt=0,this.startTime=null,this.easingFunction=c.Easing.Default,this.interpolationFunction=c.Math.linearInterpolation,this.interpolationContext=c.Math,this.isRunning=!1,this.isFrom=!1
+},c.TweenData.PENDING=0,c.TweenData.RUNNING=1,c.TweenData.LOOPED=2,c.TweenData.COMPLETE=3,c.TweenData.prototype={to:function(a,b,c,d,e,f){return this.vEnd=a,this.duration=b,this.easingFunction=c,this.delay=d,this.repeatCounter=e,this.yoyo=f,this.isFrom=!1,this},from:function(a,b,c,d,e,f){return this.vEnd=a,this.duration=b,this.easingFunction=c,this.delay=d,this.repeatCounter=e,this.yoyo=f,this.isFrom=!0,this},start:function(){if(this.startTime=this.game.time.time+this.delay,this.dt=this.parent.reverse?this.duration:0,this.isRunning=this.delay>0?!1:!0,this.isFrom)for(var a in this.vStartCache)this.vStart[a]=this.vEndCache[a],this.vEnd[a]=this.vStartCache[a],this.parent.target[a]=this.vStart[a];return this.value=0,this.yoyoCounter=0,this},loadValues:function(){for(var a in this.parent.properties){if(this.vStart[a]=this.parent.properties[a],Array.isArray(this.vEnd[a])){if(0===this.vEnd[a].length)continue;0===this.percent&&(this.vEnd[a]=[this.vStart[a]].concat(this.vEnd[a]))}"undefined"!=typeof this.vEnd[a]?("string"==typeof this.vEnd[a]&&(this.vEnd[a]=this.vStart[a]+parseFloat(this.vEnd[a],10)),this.parent.properties[a]=this.vEnd[a]):this.vEnd[a]=this.vStart[a],this.vStartCache[a]=this.vStart[a],this.vEndCache[a]=this.vEnd[a]}return this},update:function(a){if(this.isRunning){if(a<this.startTime)return c.TweenData.RUNNING}else{if(!(a>=this.startTime))return c.TweenData.PENDING;this.isRunning=!0}this.parent.reverse?(this.dt-=this.game.time.elapsedMS*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=this.game.time.elapsedMS*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var b in this.vEnd){var d=this.vStart[b],e=this.vEnd[b];this.parent.target[b]=Array.isArray(e)?this.interpolationFunction.call(this.interpolationContext,e,this.value):d+(e-d)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():c.TweenData.RUNNING},generateData:function(a){this.dt=this.parent.reverse?this.duration:0;var b=[],c=!1,d=1/a*1e3;do{this.parent.reverse?(this.dt-=d,this.dt=Math.max(this.dt,0)):(this.dt+=d,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var e={};for(var f in this.vEnd){var g=this.vStart[f],h=this.vEnd[f];e[f]=Array.isArray(h)?this.interpolationFunction(h,this.value):g+(h-g)*this.value}b.push(e),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(c=!0)}while(!c);if(this.yoyo){var i=b.slice();i.reverse(),b=b.concat(i)}return b},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter)return c.TweenData.COMPLETE;this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return c.TweenData.COMPLETE;if(this.inReverse)for(var a in this.vStartCache)this.vStart[a]=this.vEndCache[a],this.vEnd[a]=this.vStartCache[a];else{for(var a in this.vStartCache)this.vStart[a]=this.vStartCache[a],this.vEnd[a]=this.vEndCache[a];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.dt=this.parent.reverse?this.duration:0,c.TweenData.LOOPED}},c.TweenData.prototype.constructor=c.TweenData,c.Easing={Linear:{None:function(a){return a}},Quadratic:{In:function(a){return a*a},Out:function(a){return a*(2-a)},InOut:function(a){return(a*=2)<1?.5*a*a:-.5*(--a*(a-2)-1)}},Cubic:{In:function(a){return a*a*a},Out:function(a){return--a*a*a+1},InOut:function(a){return(a*=2)<1?.5*a*a*a:.5*((a-=2)*a*a+2)}},Quartic:{In:function(a){return a*a*a*a},Out:function(a){return 1- --a*a*a*a},InOut:function(a){return(a*=2)<1?.5*a*a*a*a:-.5*((a-=2)*a*a*a-2)}},Quintic:{In:function(a){return a*a*a*a*a},Out:function(a){return--a*a*a*a*a+1},InOut:function(a){return(a*=2)<1?.5*a*a*a*a*a:.5*((a-=2)*a*a*a*a+2)}},Sinusoidal:{In:function(a){return 0===a?0:1===a?1:1-Math.cos(a*Math.PI/2)},Out:function(a){return 0===a?0:1===a?1:Math.sin(a*Math.PI/2)},InOut:function(a){return 0===a?0:1===a?1:.5*(1-Math.cos(Math.PI*a))}},Exponential:{In:function(a){return 0===a?0:Math.pow(1024,a-1)},Out:function(a){return 1===a?1:1-Math.pow(2,-10*a)},InOut:function(a){return 0===a?0:1===a?1:(a*=2)<1?.5*Math.pow(1024,a-1):.5*(-Math.pow(2,-10*(a-1))+2)}},Circular:{In:function(a){return 1-Math.sqrt(1-a*a)},Out:function(a){return Math.sqrt(1- --a*a)},InOut:function(a){return(a*=2)<1?-.5*(Math.sqrt(1-a*a)-1):.5*(Math.sqrt(1-(a-=2)*a)+1)}},Elastic:{In:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),-(c*Math.pow(2,10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d)))},Out:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),c*Math.pow(2,-10*a)*Math.sin(2*(a-b)*Math.PI/d)+1)},InOut:function(a){var b,c=.1,d=.4;return 0===a?0:1===a?1:(!c||1>c?(c=1,b=d/4):b=d*Math.asin(1/c)/(2*Math.PI),(a*=2)<1?-.5*c*Math.pow(2,10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d):c*Math.pow(2,-10*(a-=1))*Math.sin(2*(a-b)*Math.PI/d)*.5+1)}},Back:{In:function(a){var b=1.70158;return a*a*((b+1)*a-b)},Out:function(a){var b=1.70158;return--a*a*((b+1)*a+b)+1},InOut:function(a){var b=2.5949095;return(a*=2)<1?.5*a*a*((b+1)*a-b):.5*((a-=2)*a*((b+1)*a+b)+2)}},Bounce:{In:function(a){return 1-c.Easing.Bounce.Out(1-a)},Out:function(a){return 1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375},InOut:function(a){return.5>a?.5*c.Easing.Bounce.In(2*a):.5*c.Easing.Bounce.Out(2*a-1)+.5}}},c.Easing.Default=c.Easing.Linear.None,c.Easing.Power0=c.Easing.Linear.None,c.Easing.Power1=c.Easing.Quadratic.Out,c.Easing.Power2=c.Easing.Cubic.Out,c.Easing.Power3=c.Easing.Quartic.Out,c.Easing.Power4=c.Easing.Quintic.Out,c.Time=function(a){this.game=a,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=0,this.physicsElapsedMS=0,this.desiredFps=60,this.suggestedFps=null,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.fps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new c.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},c.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start()},add:function(a){return this._timers.push(a),a},create:function(a){void 0===a&&(a=!0);var b=new c.Timer(this.game,a);return this._timers.push(b),b},removeAll:function(){for(var a=0;a<this._timers.length;a++)this._timers[a].destroy();this._timers=[],this.events.removeAll()},update:function(a){this.game.raf._isSetTimeOut?this.updateSetTimeout(a):this.updateRAF(a),this.advancedTiming&&this.updateAdvancedTiming(),this.game.paused||(this.events.update(this.time),this._timers.length&&this.updateTimers())},updateSetTimeout:function(a){var b=this.time;this.time=a,this.elapsedMS=this.time-b,this.prevTime=this.now,this.now=a,this.elapsed=this.now-this.prevTime,this.timeToCall=Math.floor(Math.max(0,1e3/this.desiredFps-(this.timeCallExpected-a))),this.timeCallExpected=a+this.timeToCall,this.physicsElapsed=1/this.desiredFps,this.physicsElapsedMS=1e3*this.physicsElapsed},updateRAF:function(a){var b=this.time;this.time=Date.now(),this.elapsedMS=this.time-b,this.prevTime=this.now,this.now=a,this.elapsed=this.now-this.prevTime,this.physicsElapsed=1/this.desiredFps,this.physicsElapsedMS=1e3*this.physicsElapsed},updateTimers:function(){for(var a=0,b=this._timers.length;b>a;)this._timers[a].update(this.time)?a++:(this._timers.splice(a,1),b--)},updateAdvancedTiming:function(){this._frameCount++,this._elapsedAccumulator+=this.elapsed,this._frameCount>=2*this.desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3&&(this.fps=Math.round(1e3*this.frames/(this.now-this._timeLastSecond)),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0)},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var a=this._timers.length;a--;)this._timers[a]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var a=this._timers.length;a--;)this._timers[a]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(a){return this.time-a},elapsedSecondsSince:function(a){return.001*(this.time-a)},reset:function(){this._started=this.time,this.removeAll()}},c.Time.prototype.constructor=c.Time,c.Timer=function(a,b){void 0===b&&(b=!0),this.game=a,this.running=!1,this.autoDestroy=b,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new c.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},c.Timer.MINUTE=6e4,c.Timer.SECOND=1e3,c.Timer.HALF=500,c.Timer.QUARTER=250,c.Timer.prototype={create:function(a,b,d,e,f,g){a=Math.round(a);var h=a;h+=0===this._now?this.game.time.time:this._now;var i=new c.TimerEvent(this,a,h,d,b,e,f,g);return this.events.push(i),this.order(),this.expired=!1,i},add:function(a,b,c){return this.create(a,!1,0,b,c,Array.prototype.splice.call(arguments,3))},repeat:function(a,b,c,d){return this.create(a,!1,b,c,d,Array.prototype.splice.call(arguments,4))},loop:function(a,b,c){return this.create(a,!0,0,b,c,Array.prototype.splice.call(arguments,3))},start:function(a){if(!this.running){this._started=this.game.time.time+(a||0),this.running=!0;for(var b=0;b<this.events.length;b++)this.events[b].tick=this.events[b].delay+this._started}},stop:function(a){this.running=!1,void 0===a&&(a=!0),a&&(this.events.length=0)},remove:function(a){for(var b=0;b<this.events.length;b++)if(this.events[b]===a)return this.events[b].pendingDelete=!0,!0;return!1},order:function(){this.events.length>0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(a,b){return a.tick<b.tick?-1:a.tick>b.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(a){if(this.paused)return!0;if(this.elapsed=a-this._now,this._now=a,this.elapsed>this.timeCap&&this.adjustEvents(a-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i<this._len&&this.running&&this._now>=this.events[this._i].tick&&!this.events[this._i].pendingDelete;)this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick),this._newTick<0&&(this._newTick=this._now+this.events[this._i].delay),this.events[this._i].loop===!0?(this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):this.events[this._i].repeatCount>0?(this.events[this._i].repeatCount--,this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):(this._marked++,this.events[this._i].pendingDelete=!0,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)),this._i++;this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return this.expired&&this.autoDestroy?!1:!0},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(a){for(var b=0;b<this.events.length;b++)if(!this.events[b].pendingDelete){var c=this.events[b].tick-a;0>c&&(c=0),this.events[b].tick=this._now+c}var d=this.nextTick-a;this.nextTick=0>d?this._now:this._now+d},resume:function(){if(this.paused){var a=this.game.time.time;this._pauseTotal+=a-this._now,this._now=a,this.adjustEvents(this._pauseStarted),this.paused=!1,this._codePaused=!1}},_resume:function(){this._codePaused||this.resume()},removeAll:function(){this.onComplete.removeAll(),this.events.length=0,this._len=0,this._i=0},destroy:function(){this.onComplete.removeAll(),this.running=!1,this.events=[],this._len=0,this._i=0}},Object.defineProperty(c.Timer.prototype,"next",{get:function(){return this.nextTick}}),Object.defineProperty(c.Timer.prototype,"duration",{get:function(){return this.running&&this.nextTick>this._now?this.nextTick-this._now:0}}),Object.defineProperty(c.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(c.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(c.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),c.Timer.prototype.constructor=c.Timer,c.TimerEvent=function(a,b,c,d,e,f,g,h){this.timer=a,this.delay=b,this.tick=c,this.repeatCount=d-1,this.loop=e,this.callback=f,this.callbackContext=g,this.args=h,this.pendingDelete=!1},c.TimerEvent.prototype.constructor=c.TimerEvent,c.AnimationManager=function(a){this.sprite=a,this.game=a.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},c.AnimationManager.prototype={loadFrameData:function(a,b){if(void 0===a)return!1;if(this.isLoaded)for(var c in this._anims)this._anims[c].updateFrameData(a);return this._frameData=a,void 0===b||null===b?this.frame=0:"string"==typeof b?this.frameName=b:this.frame=b,this.isLoaded=!0,!0},copyFrameData:function(a,b){if(this._frameData=a.clone(),this.isLoaded)for(var c in this._anims)this._anims[c].updateFrameData(this._frameData);return void 0===b||null===b?this.frame=0:"string"==typeof b?this.frameName=b:this.frame=b,this.isLoaded=!0,!0},add:function(a,b,d,e,f){return b=b||[],d=d||60,void 0===e&&(e=!1),void 0===f&&(f=b&&"number"==typeof b[0]?!0:!1),this._outputFrames=[],this._frameData.getFrameIndexes(b,f,this._outputFrames),this._anims[a]=new c.Animation(this.game,this.sprite,a,this._frameData,this._outputFrames,d,e),this.currentAnim=this._anims[a],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[a]},validateFrames:function(a,b){void 0===b&&(b=!0);for(var c=0;c<a.length;c++)if(b===!0){if(a[c]>this._frameData.total)return!1}else if(this._frameData.checkFrameName(a[c])===!1)return!1;return!0},play:function(a,b,c,d){return this._anims[a]?this.currentAnim===this._anims[a]?this.currentAnim.isPlaying===!1?(this.currentAnim.paused=!1,this.currentAnim.play(b,c,d)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[a],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(b,c,d)):void 0},stop:function(a,b){void 0===b&&(b=!1),"string"==typeof a?this._anims[a]&&(this.currentAnim=this._anims[a],this.currentAnim.stop(b)):this.currentAnim&&this.currentAnim.stop(b)},update:function(){return this.updateIfVisible&&!this.sprite.visible?!1:this.currentAnim&&this.currentAnim.update()?(this.currentFrame=this.currentAnim.currentFrame,!0):!1},next:function(a){this.currentAnim&&(this.currentAnim.next(a),this.currentFrame=this.currentAnim.currentFrame)},previous:function(a){this.currentAnim&&(this.currentAnim.previous(a),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(a){return"string"==typeof a&&this._anims[a]?this._anims[a]:null},refreshFrame:function(){this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid])},destroy:function(){var a=null;for(var a in this._anims)this._anims.hasOwnProperty(a)&&this._anims[a].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},c.AnimationManager.prototype.constructor=c.AnimationManager,Object.defineProperty(c.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(c.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(c.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(a){this.currentAnim.paused=a}}),Object.defineProperty(c.AnimationManager.prototype,"name",{get:function(){return this.currentAnim?this.currentAnim.name:void 0}}),Object.defineProperty(c.AnimationManager.prototype,"frame",{get:function(){return this.currentFrame?this.currentFrame.index:void 0},set:function(a){"number"==typeof a&&this._frameData&&null!==this._frameData.getFrame(a)&&(this.currentFrame=this._frameData.getFrame(a),this.currentFrame&&this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(c.AnimationManager.prototype,"frameName",{get:function(){return this.currentFrame?this.currentFrame.name:void 0},set:function(a){"string"==typeof a&&this._frameData&&null!==this._frameData.getFrameByName(a)?(this.currentFrame=this._frameData.getFrameByName(a),this.currentFrame&&(this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame))):console.warn("Cannot set frameName: "+a)}}),c.Animation=function(a,b,d,e,f,g,h){void 0===h&&(h=!1),this.game=a,this._parent=b,this._frameData=e,this.name=d,this._frames=[],this._frames=this._frames.concat(f),this.delay=1e3/g,this.loop=h,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new c.Signal,this.onUpdate=null,this.onComplete=new c.Signal,this.onLoop=new c.Signal,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},c.Animation.prototype={play:function(a,b,c){return"number"==typeof a&&(this.delay=1e3/a),"boolean"==typeof b&&(this.loop=b),"undefined"!=typeof c&&(this.killOnComplete=c),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},setFrame:function(a,b){var c;if(void 0===b&&(b=!1),"string"==typeof a)for(var d=0;d<this._frames.length;d++)this._frameData.getFrame(this._frames[d]).name===a&&(c=d);else if("number"==typeof a)if(b)c=a;else for(var d=0;d<this._frames.length;d++)this._frames[d]===c&&(c=d);c&&(this._frameIndex=c-1,this._timeNextFrame=this.game.time.time,this.update())},stop:function(a,b){void 0===a&&(a=!1),void 0===b&&(b=!1),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,a&&(this.currentFrame=this._frameData.getFrame(this._frames[0]),this._parent.setFrame(this.currentFrame)),b&&(this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this))},onPause:function(){this.isPlaying&&(this._frameDiff=this._timeNextFrame-this.game.time.time)},onResume:function(){this.isPlaying&&(this._timeNextFrame=this.game.time.time+this._frameDiff)},update:function(){return this.isPaused?!1:this.isPlaying&&this.game.time.time>=this._timeNextFrame?(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay&&(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay),this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this._frameIndex+=this._frameSkip,this._frameIndex>=this._frames.length?this.loop?(this._frameIndex%=this._frames.length,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),this.onUpdate?(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData):!0):(this.complete(),!1):this.updateCurrentFrame(!0)):!1},updateCurrentFrame:function(a,b){if(void 0===b&&(b=!1),!this._frameData)return!1;var c=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(b||!b&&c!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),this.onUpdate&&a?(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData):!0},next:function(a){void 0===a&&(a=1);var b=this._frameIndex+a;b>=this._frames.length&&(this.loop?b%=this._frames.length:b=this._frames.length-1),b!==this._frameIndex&&(this._frameIndex=b,this.updateCurrentFrame(!0))},previous:function(a){void 0===a&&(a=1);var b=this._frameIndex-a;0>b&&(this.loop?b=this._frames.length+b:b++),b!==this._frameIndex&&(this._frameIndex=b,this.updateCurrentFrame(!0))},updateFrameData:function(a){this._frameData=a,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(this.game.onPause.remove(this.onPause,this),this.game.onResume.remove(this.onResume,this),this.game=null,this._parent=null,this._frames=null,this._frameData=null,this.currentFrame=null,this.isPlaying=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},c.Animation.prototype.constructor=c.Animation,Object.defineProperty(c.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(a){this.isPaused=a,a?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(c.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(c.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(a){this.currentFrame=this._frameData.getFrame(this._frames[a]),null!==this.currentFrame&&(this._frameIndex=a,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(c.Animation.prototype,"speed",{get:function(){return Math.round(1e3/this.delay)},set:function(a){a>=1&&(this.delay=1e3/a)}}),Object.defineProperty(c.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(a){a&&null===this.onUpdate?this.onUpdate=new c.Signal:a||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),c.Animation.generateFrameNames=function(a,b,d,e,f){void 0===e&&(e="");var g=[],h="";if(d>b)for(var i=b;d>=i;i++)h="number"==typeof f?c.Utils.pad(i.toString(),f,"0",1):i.toString(),h=a+h+e,g.push(h);else for(var i=b;i>=d;i--)h="number"==typeof f?c.Utils.pad(i.toString(),f,"0",1):i.toString(),h=a+h+e,g.push(h);return g},c.Frame=function(a,b,d,e,f,g){this.index=a,this.x=b,this.y=d,this.width=e,this.height=f,this.name=g,this.centerX=Math.floor(e/2),this.centerY=Math.floor(f/2),this.distance=c.Math.distance(0,0,e,f),this.rotated=!1,this.rotationDirection="cw",this.trimmed=!1,this.sourceSizeW=e,this.sourceSizeH=f,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},c.Frame.prototype={resize:function(a,b){this.width=a,this.height=b,this.centerX=Math.floor(a/2),this.centerY=Math.floor(b/2),this.distance=c.Math.distance(0,0,a,b),this.sourceSizeW=a,this.sourceSizeH=b,this.right=this.x+a,this.bottom=this.y+b},setTrim:function(a,b,c,d,e,f,g){this.trimmed=a,a&&(this.sourceSizeW=b,this.sourceSizeH=c,this.centerX=Math.floor(b/2),this.centerY=Math.floor(c/2),this.spriteSourceSizeX=d,this.spriteSourceSizeY=e,this.spriteSourceSizeW=f,this.spriteSourceSizeH=g)},clone:function(){var a=new c.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var b in this)this.hasOwnProperty(b)&&(a[b]=this[b]);return a},getRect:function(a){return void 0===a?a=new c.Rectangle(this.x,this.y,this.width,this.height):a.setTo(this.x,this.y,this.width,this.height),a}},c.Frame.prototype.constructor=c.Frame,c.FrameData=function(){this._frames=[],this._frameNames=[]},c.FrameData.prototype={addFrame:function(a){return a.index=this._frames.length,this._frames.push(a),""!==a.name&&(this._frameNames[a.name]=a.index),a},getFrame:function(a){return a>=this._frames.length&&(a=0),this._frames[a]},getFrameByName:function(a){return"number"==typeof this._frameNames[a]?this._frames[this._frameNames[a]]:null},checkFrameName:function(a){return null==this._frameNames[a]?!1:!0},clone:function(){for(var a=new c.FrameData,b=0;b<this._frames.length;b++)a._frames.push(this._frames[b].clone());for(var d in this._frameNames)this._frameNames.hasOwnProperty(d)&&a._frameNames.push(this._frameNames[d]);return a},getFrameRange:function(a,b,c){void 0===c&&(c=[]);for(var d=a;b>=d;d++)c.push(this._frames[d]);return c},getFrames:function(a,b,c){if(void 0===b&&(b=!0),void 0===c&&(c=[]),void 0===a||0===a.length)for(var d=0;d<this._frames.length;d++)c.push(this._frames[d]);else for(var d=0;d<a.length;d++)c.push(b?this.getFrame(a[d]):this.getFrameByName(a[d]));return c},getFrameIndexes:function(a,b,c){if(void 0===b&&(b=!0),void 0===c&&(c=[]),void 0===a||0===a.length)for(var d=0;d<this._frames.length;d++)c.push(this._frames[d].index);else for(var d=0;d<a.length;d++)b?c.push(this._frames[a[d]].index):this.getFrameByName(a[d])&&c.push(this.getFrameByName(a[d]).index);return c}},c.FrameData.prototype.constructor=c.FrameData,Object.defineProperty(c.FrameData.prototype,"total",{get:function(){return this._frames.length}}),c.AnimationParser={spriteSheet:function(a,b,d,e,f,g,h){var i=b;if("string"==typeof b&&(i=a.cache.getImage(b)),null===i)return null;var j=i.width,k=i.height;0>=d&&(d=Math.floor(-j/Math.min(-1,d))),0>=e&&(e=Math.floor(-k/Math.min(-1,e)));var l=Math.floor((j-g)/(d+h)),m=Math.floor((k-g)/(e+h)),n=l*m;if(-1!==f&&(n=f),0===j||0===k||d>j||e>k||0===n)return console.warn("Phaser.AnimationParser.spriteSheet: '"+b+"'s width/height zero or width/height < given frameWidth/frameHeight"),null;for(var o=new c.FrameData,p=g,q=g,r=0;n>r;r++)o.addFrame(new c.Frame(r,p,q,d,e,"")),p+=d+h,p+d>j&&(p=g,q+=e+h);return o},JSONData:function(a,b){if(!b.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(b);for(var d,e=new c.FrameData,f=b.frames,g=0;g<f.length;g++)d=e.addFrame(new c.Frame(g,f[g].frame.x,f[g].frame.y,f[g].frame.w,f[g].frame.h,f[g].filename)),f[g].trimmed&&d.setTrim(f[g].trimmed,f[g].sourceSize.w,f[g].sourceSize.h,f[g].spriteSourceSize.x,f[g].spriteSourceSize.y,f[g].spriteSourceSize.w,f[g].spriteSourceSize.h);return e},JSONDataHash:function(a,b){if(!b.frames)return console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"),void console.log(b);var d,e=new c.FrameData,f=b.frames,g=0;for(var h in f)d=e.addFrame(new c.Frame(g,f[h].frame.x,f[h].frame.y,f[h].frame.w,f[h].frame.h,h)),f[h].trimmed&&d.setTrim(f[h].trimmed,f[h].sourceSize.w,f[h].sourceSize.h,f[h].spriteSourceSize.x,f[h].spriteSourceSize.y,f[h].spriteSourceSize.w,f[h].spriteSourceSize.h),g++;return e},XMLData:function(a,b){if(!b.getElementsByTagName("TextureAtlas"))return void console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");for(var d,e,f,g,h,i,j,k,l,m,n,o=new c.FrameData,p=b.getElementsByTagName("SubTexture"),q=0;q<p.length;q++)f=p[q].attributes,e=f.name.value,g=parseInt(f.x.value,10),h=parseInt(f.y.value,10),i=parseInt(f.width.value,10),j=parseInt(f.height.value,10),k=null,l=null,f.frameX&&(k=Math.abs(parseInt(f.frameX.value,10)),l=Math.abs(parseInt(f.frameY.value,10)),m=parseInt(f.frameWidth.value,10),n=parseInt(f.frameHeight.value,10)),d=o.addFrame(new c.Frame(q,g,h,i,j,e)),(null!==k||null!==l)&&d.setTrim(!0,i,j,k,l,m,n);return o}},c.Cache=function(a){this.game=a,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new c.Signal,this._cacheMap=[],this._cacheMap[c.Cache.CANVAS]=this._cache.canvas,this._cacheMap[c.Cache.IMAGE]=this._cache.image,this._cacheMap[c.Cache.TEXTURE]=this._cache.texture,this._cacheMap[c.Cache.SOUND]=this._cache.sound,this._cacheMap[c.Cache.TEXT]=this._cache.text,this._cacheMap[c.Cache.PHYSICS]=this._cache.physics,this._cacheMap[c.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[c.Cache.BINARY]=this._cache.binary,this._cacheMap[c.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[c.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[c.Cache.JSON]=this._cache.json,this._cacheMap[c.Cache.XML]=this._cache.xml,this._cacheMap[c.Cache.VIDEO]=this._cache.video,this._cacheMap[c.Cache.SHADER]=this._cache.shader,this._cacheMap[c.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this.addDefaultImage(),this.addMissingImage()},c.Cache.CANVAS=1,c.Cache.IMAGE=2,c.Cache.TEXTURE=3,c.Cache.SOUND=4,c.Cache.TEXT=5,c.Cache.PHYSICS=6,c.Cache.TILEMAP=7,c.Cache.BINARY=8,c.Cache.BITMAPDATA=9,c.Cache.BITMAPFONT=10,c.Cache.JSON=11,c.Cache.XML=12,c.Cache.VIDEO=13,c.Cache.SHADER=14,c.Cache.RENDER_TEXTURE=15,c.Cache.prototype={addCanvas:function(a,b,c){void 0===c&&(c=b.getContext("2d")),this._cache.canvas[a]={canvas:b,context:c}},addImage:function(a,b,d){this.checkImageKey(a)&&this.removeImage(a);var e={key:a,url:b,data:d,base:new PIXI.BaseTexture(d),frame:new c.Frame(0,0,0,d.width,d.height,a),frameData:new c.FrameData};return e.frameData.addFrame(new c.Frame(0,0,0,d.width,d.height,b)),this._cache.image[a]=e,this._resolveURL(b,e),e},addDefaultImage:function(){var a=new Image;a.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";var b=this.addImage("__default",null,a);PIXI.TextureCache.__default=new PIXI.Texture(b.base)},addMissingImage:function(){var a=new Image;a.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";var b=this.addImage("__missing",null,a);PIXI.TextureCache.__missing=new PIXI.Texture(b.base)},addSound:function(a,b,c,d,e){void 0===d&&(d=!0,e=!1),void 0===e&&(d=!1,e=!0);
+var f=!1;e&&(f=!0),this._cache.sound[a]={url:b,data:c,isDecoding:!1,decoded:f,webAudio:d,audioTag:e,locked:this.game.sound.touchLocked},this._resolveURL(b,this._cache.sound[a])},addText:function(a,b,c){this._cache.text[a]={url:b,data:c},this._resolveURL(b,this._cache.text[a])},addPhysicsData:function(a,b,c,d){this._cache.physics[a]={url:b,data:c,format:d},this._resolveURL(b,this._cache.physics[a])},addTilemap:function(a,b,c,d){this._cache.tilemap[a]={url:b,data:c,format:d},this._resolveURL(b,this._cache.tilemap[a])},addBinary:function(a,b){this._cache.binary[a]=b},addBitmapData:function(a,b,d){return b.key=a,void 0===d&&(d=new c.FrameData,d.addFrame(b.textureFrame)),this._cache.bitmapData[a]={data:b,frameData:d},b},addBitmapFont:function(a,b,d,e,f,g,h){var i={url:b,data:d,font:null,base:new PIXI.BaseTexture(d)};i.font="json"===f?c.LoaderParser.jsonBitmapFont(e,i.base,g,h):c.LoaderParser.xmlBitmapFont(e,i.base,g,h),this._cache.bitmapFont[a]=i,this._resolveURL(b,i)},addJSON:function(a,b,c){this._cache.json[a]={url:b,data:c},this._resolveURL(b,this._cache.json[a])},addXML:function(a,b,c){this._cache.xml[a]={url:b,data:c},this._resolveURL(b,this._cache.xml[a])},addVideo:function(a,b,c,d){this._cache.video[a]={url:b,data:c,isBlob:d,locked:!0},this._resolveURL(b,this._cache.video[a])},addShader:function(a,b,c){this._cache.shader[a]={url:b,data:c},this._resolveURL(b,this._cache.shader[a])},addRenderTexture:function(a,b){this._cache.renderTexture[a]={texture:b,frame:new c.Frame(0,0,0,b.width,b.height,"","")}},addSpriteSheet:function(a,b,d,e,f,g,h,i){var j={key:a,url:b,data:d,frameWidth:e,frameHeight:f,margin:h,spacing:i,base:new PIXI.BaseTexture(d),frameData:c.AnimationParser.spriteSheet(this.game,d,e,f,g,h,i)};this._cache.image[a]=j,this._resolveURL(b,j)},addTextureAtlas:function(a,b,d,e,f){var g={key:a,url:b,data:d,base:new PIXI.BaseTexture(d)};g.frameData=f===c.Loader.TEXTURE_ATLAS_XML_STARLING?c.AnimationParser.XMLData(this.game,e,a):Array.isArray(e.frames)?c.AnimationParser.JSONData(this.game,e,a):c.AnimationParser.JSONDataHash(this.game,e,a),this._cache.image[a]=g,this._resolveURL(b,g)},reloadSound:function(a){var b=this,c=this.getSound(a);c&&(c.data.src=c.url,c.data.addEventListener("canplaythrough",function(){return b.reloadSoundComplete(a)},!1),c.data.load())},reloadSoundComplete:function(a){var b=this.getSound(a);b&&(b.locked=!1,this.onSoundUnlock.dispatch(a))},updateSound:function(a,b,c){var d=this.getSound(a);d&&(d[b]=c)},decodedSound:function(a,b){var c=this.getSound(a);c.data=b,c.decoded=!0,c.isDecoding=!1},isSoundDecoded:function(a){var b=this.getItem(a,c.Cache.SOUND,"isSoundDecoded");return b?b.decoded:void 0},isSoundReady:function(a){var b=this.getItem(a,c.Cache.SOUND,"isSoundDecoded");return b?b.decoded&&!this.game.sound.touchLocked:void 0},checkKey:function(a,b){return this._cacheMap[a][b]?!0:!1},checkURL:function(a){return this._urlMap[this._resolveURL(a)]?!0:!1},checkCanvasKey:function(a){return this.checkKey(c.Cache.CANVAS,a)},checkImageKey:function(a){return this.checkKey(c.Cache.IMAGE,a)},checkTextureKey:function(a){return this.checkKey(c.Cache.TEXTURE,a)},checkSoundKey:function(a){return this.checkKey(c.Cache.SOUND,a)},checkTextKey:function(a){return this.checkKey(c.Cache.TEXT,a)},checkPhysicsKey:function(a){return this.checkKey(c.Cache.PHYSICS,a)},checkTilemapKey:function(a){return this.checkKey(c.Cache.TILEMAP,a)},checkBinaryKey:function(a){return this.checkKey(c.Cache.BINARY,a)},checkBitmapDataKey:function(a){return this.checkKey(c.Cache.BITMAPDATA,a)},checkBitmapFontKey:function(a){return this.checkKey(c.Cache.BITMAPFONT,a)},checkJSONKey:function(a){return this.checkKey(c.Cache.JSON,a)},checkXMLKey:function(a){return this.checkKey(c.Cache.XML,a)},checkVideoKey:function(a){return this.checkKey(c.Cache.VIDEO,a)},checkShaderKey:function(a){return this.checkKey(c.Cache.SHADER,a)},checkRenderTextureKey:function(a){return this.checkKey(c.Cache.RENDER_TEXTURE,a)},getItem:function(a,b,c,d){return this.checkKey(b,a)?void 0===d?this._cacheMap[b][a]:this._cacheMap[b][a][d]:(c&&console.warn("Phaser.Cache."+c+': Key "'+a+'" not found in Cache.'),null)},getCanvas:function(a){return this.getItem(a,c.Cache.CANVAS,"getCanvas","canvas")},getImage:function(a,b){(void 0===a||null===a)&&(a="__default"),void 0===b&&(b=!1);var d=this.getItem(a,c.Cache.IMAGE,"getImage");return null===d&&(d=this.getItem("__missing",c.Cache.IMAGE,"getImage")),b?d:d.data},getTextureFrame:function(a){return this.getItem(a,c.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(a){return this.getItem(a,c.Cache.SOUND,"getSound")},getSoundData:function(a){return this.getItem(a,c.Cache.SOUND,"getSoundData","data")},getText:function(a){return this.getItem(a,c.Cache.TEXT,"getText","data")},getPhysicsData:function(a,b,d){var e=this.getItem(a,c.Cache.PHYSICS,"getPhysicsData","data");if(null===e||void 0===b||null===b)return e;if(e[b]){var f=e[b];if(!f||!d)return f;for(var g in f)if(g=f[g],g.fixtureKey===d)return g;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+d+" in "+a+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+a+" / "+b+'"');return null},getTilemapData:function(a){return this.getItem(a,c.Cache.TILEMAP,"getTilemapData")},getBinary:function(a){return this.getItem(a,c.Cache.BINARY,"getBinary")},getBitmapData:function(a){return this.getItem(a,c.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(a){return this.getItem(a,c.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(a,b){var d=this.getItem(a,c.Cache.JSON,"getJSON","data");return d?b?c.Utils.extend(!0,d):d:null},getXML:function(a){return this.getItem(a,c.Cache.XML,"getXML","data")},getVideo:function(a){return this.getItem(a,c.Cache.VIDEO,"getVideo")},getShader:function(a){return this.getItem(a,c.Cache.SHADER,"getShader","data")},getRenderTexture:function(a){return this.getItem(a,c.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),this.getItem(a,b,"getBaseTexture","base")},getFrame:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),this.getItem(a,b,"getFrame","frame")},getFrameCount:function(a,b){var c=this.getFrameData(a,b);return c?c.total:0},getFrameData:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),this.getItem(a,b,"getFrameData","frameData")},hasFrameData:function(a,b){return void 0===b&&(b=c.Cache.IMAGE),null!==this.getItem(a,b,"","frameData")},updateFrameData:function(a,b,d){void 0===d&&(d=c.Cache.IMAGE),this._cacheMap[d][a]&&(this._cacheMap[d][a].frameData=b)},getFrameByIndex:function(a,b,c){var d=this.getFrameData(a,c);return d?d.getFrame(b):null},getFrameByName:function(a,b,c){var d=this.getFrameData(a,c);return d?d.getFrameByName(b):null},getPixiTexture:function(a){if(PIXI.TextureCache[a])return PIXI.TextureCache[a];var b=this.getPixiBaseTexture(a);return b?new PIXI.Texture(b):null},getPixiBaseTexture:function(a){if(PIXI.BaseTextureCache[a])return PIXI.BaseTextureCache[a];var b=this.getItem(a,c.Cache.IMAGE,"getPixiBaseTexture");return null!==b?b.base:null},getURL:function(a){var a=this._resolveURL(a);return a?this._urlMap[a]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+a+'" or Cache.autoResolveURL was false'),null)},getKeys:function(a){void 0===a&&(a=c.Cache.IMAGE);var b=[];if(this._cacheMap[a])for(var d in this._cacheMap[a])"__default"!==d&&"__missing"!==d&&b.push(d);return b},removeCanvas:function(a){delete this._cache.canvas[a]},removeImage:function(a,b){void 0===b&&(b=!0);var c=this.getImage(a,!0);b&&c.base&&c.base.destroy(),delete this._cache.image[a]},removeSound:function(a){delete this._cache.sound[a]},removeText:function(a){delete this._cache.text[a]},removePhysics:function(a){delete this._cache.physics[a]},removeTilemap:function(a){delete this._cache.tilemap[a]},removeBinary:function(a){delete this._cache.binary[a]},removeBitmapData:function(a){delete this._cache.bitmapData[a]},removeBitmapFont:function(a){delete this._cache.bitmapFont[a]},removeJSON:function(a){delete this._cache.json[a]},removeXML:function(a){delete this._cache.xml[a]},removeVideo:function(a){delete this._cache.video[a]},removeShader:function(a){delete this._cache.shader[a]},removeRenderTexture:function(a){delete this._cache.renderTexture[a]},removeSpriteSheet:function(a){delete this._cache.spriteSheet[a]},removeTextureAtlas:function(a){delete this._cache.atlas[a]},clearGLTextures:function(){for(var a in this.cache.image)this.cache.image[a].base._glTextures=[]},_resolveURL:function(a,b){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+a,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",b&&(this._urlMap[this._urlTemp]=b),this._urlTemp):null},destroy:function(){for(var a=0;a<this._cacheMap.length;a++){var b=this._cacheMap[a];for(var c in b)"__default"!==c&&"__missing"!==c&&(b[c].destroy&&b[c].destroy(),delete b[c])}this._urlMap=null,this._urlResolver=null,this._urlTemp=null}},c.Cache.prototype.constructor=c.Cache,c.Loader=function(a){this.game=a,this.cache=a.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.onLoadStart=new c.Signal,this.onLoadComplete=new c.Signal,this.onPackComplete=new c.Signal,this.onFileStart=new c.Signal,this.onFileComplete=new c.Signal,this.onFileError=new c.Signal,this.useXDomainRequest=!1,this._warnedAboutXDomainRequest=!1,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},c.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,c.Loader.TEXTURE_ATLAS_JSON_HASH=1,c.Loader.TEXTURE_ATLAS_XML_STARLING=2,c.Loader.PHYSICS_LIME_CORONA_JSON=3,c.Loader.PHYSICS_PHASER_JSON=4,c.Loader.prototype={setPreloadSprite:function(a,b){b=b||0,this.preloadSprite={sprite:a,direction:b,width:a.width,height:a.height,rect:null},this.preloadSprite.rect=0===b?new c.Rectangle(0,0,1,a.height):new c.Rectangle(0,0,a.width,1),a.crop(this.preloadSprite.rect),a.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(a,b){return this.getAssetIndex(a,b)>-1},getAssetIndex:function(a,b){for(var c=-1,d=0;d<this._fileList.length;d++){var e=this._fileList[d];if(e.type===a&&e.key===b&&(c=d,!e.loaded&&!e.loading))break}return c},getAsset:function(a,b){var c=this.getAssetIndex(a,b);return c>-1?{index:c,file:this._fileList[c]}:!1},reset:function(a,b){void 0===b&&(b=!1),this.resetLocked||(a&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,b&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(a,b,c,d,e,f){if(void 0===e&&(e=!1),void 0===b||""===b)return console.warn("Phaser.Loader: Invalid or no key given of type "+a),this;if(void 0===c||null===c){if(!f)return console.warn("Phaser.Loader: No URL given for file type: "+a+" key: "+b),this;c=b+f}var g={type:a,key:b,path:this.path,url:c,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(d)for(var h in d)g[h]=d[h];var i=this.getAssetIndex(a,b);if(e&&i>-1){var j=this._fileList[i];j.loading||j.loaded?(this._fileList.push(g),this._totalFileCount++):this._fileList[i]=g}else-1===i&&(this._fileList.push(g),this._totalFileCount++);return this},replaceInFileList:function(a,b,c,d){return this.addToFileList(a,b,c,d,!0)},pack:function(a,b,c,d){if(void 0===b&&(b=null),void 0===c&&(c=null),void 0===d&&(d=null),!b&&!c)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var e={type:"packfile",key:a,url:b,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:d};c&&("string"==typeof c&&(c=JSON.parse(c)),e.data=c||{},e.loaded=!0);for(var f=0;f<this._fileList.length+1;f++){var g=this._fileList[f];if(!g||!g.loaded&&!g.loading&&"packfile"!==g.type){this._fileList.splice(f,1,e),this._totalPackCount++;break}}return this},image:function(a,b,c){return this.addToFileList("image",a,b,void 0,c,".png")},text:function(a,b,c){return this.addToFileList("text",a,b,void 0,c,".txt")},json:function(a,b,c){return this.addToFileList("json",a,b,void 0,c,".json")},shader:function(a,b,c){return this.addToFileList("shader",a,b,void 0,c,".frag")},xml:function(a,b,c){return this.addToFileList("xml",a,b,void 0,c,".xml")},script:function(a,b,c,d){return void 0===c&&(c=!1),c!==!1&&void 0===d&&(d=this),this.addToFileList("script",a,b,{syncPoint:!0,callback:c,callbackContext:d},!1,".js")},binary:function(a,b,c,d){return void 0===c&&(c=!1),c!==!1&&void 0===d&&(d=c),this.addToFileList("binary",a,b,{callback:c,callbackContext:d},!1,".bin")},spritesheet:function(a,b,c,d,e,f,g){return void 0===e&&(e=-1),void 0===f&&(f=0),void 0===g&&(g=0),this.addToFileList("spritesheet",a,b,{frameWidth:c,frameHeight:d,frameMax:e,margin:f,spacing:g},!1,".png")},audio:function(a,b,c){return this.game.sound.noAudio?this:(void 0===c&&(c=!0),"string"==typeof b&&(b=[b]),this.addToFileList("audio",a,b,{buffer:null,autoDecode:c}))},audiosprite:function(a,b,c,d,e){return this.game.sound.noAudio?this:(void 0===c&&(c=null),void 0===d&&(d=null),void 0===e&&(e=!0),this.audio(a,b,e),c?this.json(a+"-audioatlas",c):d?("string"==typeof d&&(d=JSON.parse(d)),this.cache.addJSON(a+"-audioatlas","",d)):console.warn("Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object"),this)},video:function(a,b,c,d){return void 0===c&&(c=this.game.device.firefox?"loadeddata":"canplaythrough"),void 0===d&&(d=!1),"string"==typeof b&&(b=[b]),this.addToFileList("video",a,b,{buffer:null,asBlob:d,loadEvent:c})},tilemap:function(a,b,d,e){if(void 0===b&&(b=null),void 0===d&&(d=null),void 0===e&&(e=c.Tilemap.CSV),b||d||(b=e===c.Tilemap.CSV?a+".csv":a+".json"),d){switch(e){case c.Tilemap.CSV:break;case c.Tilemap.TILED_JSON:"string"==typeof d&&(d=JSON.parse(d))}this.cache.addTilemap(a,null,d,e)}else this.addToFileList("tilemap",a,b,{format:e});return this},physics:function(a,b,d,e){return void 0===b&&(b=null),void 0===d&&(d=null),void 0===e&&(e=c.Physics.LIME_CORONA_JSON),b||d||(b=a+".json"),d?("string"==typeof d&&(d=JSON.parse(d)),this.cache.addPhysicsData(a,null,d,e)):this.addToFileList("physics",a,b,{format:e}),this},bitmapFont:function(a,b,c,d,e,f){if((void 0===b||null===b)&&(b=a+".png"),void 0===c&&(c=null),void 0===d&&(d=null),void 0===e&&(e=0),void 0===f&&(f=0),c)this.addToFileList("bitmapfont",a,b,{atlasURL:c,xSpacing:e,ySpacing:f});else if("string"==typeof d){var g,h;try{g=JSON.parse(d)}catch(i){h=this.parseXml(d)}if(!h&&!g)throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");this.addToFileList("bitmapfont",a,b,{atlasURL:null,atlasData:g||h,atlasType:g?"json":"xml",xSpacing:e,ySpacing:f})}return this},atlasJSONArray:function(a,b,d,e){return this.atlas(a,b,d,e,c.Loader.TEXTURE_ATLAS_JSON_ARRAY)},atlasJSONHash:function(a,b,d,e){return this.atlas(a,b,d,e,c.Loader.TEXTURE_ATLAS_JSON_HASH)},atlasXML:function(a,b,d,e){return void 0===d&&(d=null),void 0===e&&(e=null),d||e||(d=a+".xml"),this.atlas(a,b,d,e,c.Loader.TEXTURE_ATLAS_XML_STARLING)},atlas:function(a,b,d,e,f){if((void 0===b||null===b)&&(b=a+".png"),void 0===d&&(d=null),void 0===e&&(e=null),void 0===f&&(f=c.Loader.TEXTURE_ATLAS_JSON_ARRAY),d||e||(d=f===c.Loader.TEXTURE_ATLAS_XML_STARLING?a+".xml":a+".json"),d)this.addToFileList("textureatlas",a,b,{atlasURL:d,format:f});else{switch(f){case c.Loader.TEXTURE_ATLAS_JSON_ARRAY:"string"==typeof e&&(e=JSON.parse(e));break;case c.Loader.TEXTURE_ATLAS_XML_STARLING:if("string"==typeof e){var g=this.parseXml(e);if(!g)throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");e=g}}this.addToFileList("textureatlas",a,b,{atlasURL:null,atlasData:e,format:f})}return this},withSyncPoint:function(a,b){this._withSyncPointDepth++;try{a.call(b||this,this)}finally{this._withSyncPointDepth--}return this},addSyncPoint:function(a,b){var c=this.getAsset(a,b);return c&&(c.file.syncPoint=!0),this},removeFile:function(a,b){var c=this.getAsset(a,b);c&&(c.loaded||c.loading||this._fileList.splice(c.index,1))},removeAll:function(){this._fileList.length=0,this._flightQueue.length=0},start:function(){this.isLoading||(this.hasLoaded=!1,this.isLoading=!0,this.updateProgress(),this.processLoadQueue())},processLoadQueue:function(){if(!this.isLoading)return console.warn("Phaser.Loader - active loading canceled / reset"),void this.finishedLoading(!0);for(var a=0;a<this._flightQueue.length;a++){var b=this._flightQueue[a];(b.loaded||b.error)&&(this._flightQueue.splice(a,1),a--,b.loading=!1,b.requestUrl=null,b.requestObject=null,b.error&&this.onFileError.dispatch(b.key,b),"packfile"!==b.type?(this._loadedFileCount++,this.onFileComplete.dispatch(this.progress,b.key,!b.error,this._loadedFileCount,this._totalFileCount)):"packfile"===b.type&&b.error&&(this._loadedPackCount++,this.onPackComplete.dispatch(b.key,!b.error,this._loadedPackCount,this._totalPackCount)))}for(var d=!1,e=this.enableParallel?c.Math.clamp(this.maxParallelDownloads,1,12):1,a=this._processingHead;a<this._fileList.length;a++){var b=this._fileList[a];if("packfile"===b.type&&!b.error&&b.loaded&&a===this._processingHead&&(this.processPack(b),this._loadedPackCount++,this.onPackComplete.dispatch(b.key,!b.error,this._loadedPackCount,this._totalPackCount)),b.loaded||b.error?a===this._processingHead&&(this._processingHead=a+1):!b.loading&&this._flightQueue.length<e&&("packfile"!==b.type||b.data?d||(this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this._flightQueue.push(b),b.loading=!0,this.onFileStart.dispatch(this.progress,b.key,b.url),this.loadFile(b)):(this._flightQueue.push(b),b.loading=!0,this.loadFile(b))),!b.loaded&&b.syncPoint&&(d=!0),this._flightQueue.length>=e||d&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var f=this;setTimeout(function(){f.finishedLoading(!0)},2e3)}},finishedLoading:function(a){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,a||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.onLoadComplete.dispatch(),this.reset(),this.game.state.loadComplete())},asyncComplete:function(a,b){void 0===b&&(b=""),a.loaded=!0,a.error=!!b,b&&(a.errorMessage=b,console.warn("Phaser.Loader - "+a.type+"["+a.key+"]: "+b)),this.processLoadQueue()},processPack:function(a){var b=a.data[a.key];if(!b)return void console.warn("Phaser.Loader - "+a.key+": pack has data, but not for pack key");for(var d=0;d<b.length;d++){var e=b[d];switch(e.type){case"image":this.image(e.key,e.url,e.overwrite);break;case"text":this.text(e.key,e.url,e.overwrite);break;case"json":this.json(e.key,e.url,e.overwrite);break;case"xml":this.xml(e.key,e.url,e.overwrite);break;case"script":this.script(e.key,e.url,e.callback,a.callbackContext||this);break;case"binary":this.binary(e.key,e.url,e.callback,a.callbackContext||this);break;case"spritesheet":this.spritesheet(e.key,e.url,e.frameWidth,e.frameHeight,e.frameMax,e.margin,e.spacing);break;case"video":this.video(e.key,e.urls);break;case"audio":this.audio(e.key,e.urls,e.autoDecode);break;case"audiosprite":this.audiosprite(e.key,e.urls,e.jsonURL,e.jsonData,e.autoDecode);break;case"tilemap":this.tilemap(e.key,e.url,e.data,c.Tilemap[e.format]);break;case"physics":this.physics(e.key,e.url,e.data,c.Loader[e.format]);break;case"bitmapFont":this.bitmapFont(e.key,e.textureURL,e.atlasURL,e.atlasData,e.xSpacing,e.ySpacing);break;case"atlasJSONArray":this.atlasJSONArray(e.key,e.textureURL,e.atlasURL,e.atlasData);break;case"atlasJSONHash":this.atlasJSONHash(e.key,e.textureURL,e.atlasURL,e.atlasData);break;case"atlasXML":this.atlasXML(e.key,e.textureURL,e.atlasURL,e.atlasData);break;case"atlas":this.atlas(e.key,e.textureURL,e.atlasURL,e.atlasData,c.Loader[e.format]);break;case"shader":this.shader(e.key,e.url,e.overwrite)}}},transformUrl:function(a,b){return a?"http"===a.substr(0,4)||"//"===a.substr(0,2)?a:this.baseURL+b.path+a:!1},loadFile:function(a){switch(a.type){case"packfile":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.fileComplete);break;case"image":case"spritesheet":case"textureatlas":case"bitmapfont":this.loadImageTag(a);break;case"audio":a.url=this.getAudioURL(a.url),a.url?this.game.sound.usingWebAudio?this.xhrLoad(a,this.transformUrl(a.url,a),"arraybuffer",this.fileComplete):this.game.sound.usingAudioTag&&this.loadAudioTag(a):this.fileError(a,null,"No supported audio URL specified or device does not have audio playback support");break;case"video":a.url=this.getVideoURL(a.url),a.url?a.asBlob?this.xhrLoad(a,this.transformUrl(a.url,a),"arraybuffer",this.fileComplete):this.loadVideoTag(a):this.fileError(a,null,"No supported video URL specified or device does not have video playback support");break;case"json":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.jsonLoadComplete);break;case"xml":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.xmlLoadComplete);break;case"tilemap":a.format===c.Tilemap.TILED_JSON?this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.jsonLoadComplete):a.format===c.Tilemap.CSV?this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.csvLoadComplete):this.asyncComplete(a,"invalid Tilemap format: "+a.format);break;case"text":case"script":case"shader":case"physics":this.xhrLoad(a,this.transformUrl(a.url,a),"text",this.fileComplete);break;case"binary":this.xhrLoad(a,this.transformUrl(a.url,a),"arraybuffer",this.fileComplete)}},loadImageTag:function(a){var b=this;a.data=new Image,a.data.name=a.key,this.crossOrigin&&(a.data.crossOrigin=this.crossOrigin),a.data.onload=function(){a.data.onload&&(a.data.onload=null,a.data.onerror=null,b.fileComplete(a))},a.data.onerror=function(){a.data.onload&&(a.data.onload=null,a.data.onerror=null,b.fileError(a))},a.data.src=this.transformUrl(a.url,a),a.data.complete&&a.data.width&&a.data.height&&(a.data.onload=null,a.data.onerror=null,this.fileComplete(a))},loadVideoTag:function(a){var b=this;a.data=document.createElement("video"),a.data.name=a.key,a.data.controls=!1,a.data.autoplay=!1;var d=function(){a.data.removeEventListener(a.loadEvent,d,!1),a.data.onerror=null,a.data.canplay=!0,c.GAMES[b.game.id].load.fileComplete(a)};a.data.onerror=function(){a.data.removeEventListener(a.loadEvent,d,!1),a.data.onerror=null,a.data.canplay=!1,b.fileError(a)},a.data.addEventListener(a.loadEvent,d,!1),a.data.src=this.transformUrl(a.url,a),a.data.load()},loadAudioTag:function(a){var b=this;if(this.game.sound.touchLocked)a.data=new Audio,a.data.name=a.key,a.data.preload="auto",a.data.src=this.transformUrl(a.url,a),this.fileComplete(a);else{a.data=new Audio,a.data.name=a.key;var d=function(){a.data.removeEventListener("canplaythrough",d,!1),a.data.onerror=null,c.GAMES[b.game.id].load.fileComplete(a)};a.data.onerror=function(){a.data.removeEventListener("canplaythrough",d,!1),a.data.onerror=null,b.fileError(a)},a.data.preload="auto",a.data.src=this.transformUrl(a.url,a),a.data.addEventListener("canplaythrough",d,!1),a.data.load()}},xhrLoad:function(a,b,c,d,e){if(this.useXDomainRequest&&window.XDomainRequest)return void this.xhrLoadWithXDR(a,b,c,d,e);var f=new XMLHttpRequest;f.open("GET",b,!0),f.responseType=c,e=e||this.fileError;var g=this;f.onload=function(){try{return d.call(g,a,f)}catch(b){g.hasLoaded?window.console&&console.error(b):g.asyncComplete(a,b.message||"Exception")}},f.onerror=function(){try{return e.call(g,a,f)}catch(b){g.hasLoaded?window.console&&console.error(b):g.asyncComplete(a,b.message||"Exception")}},a.requestObject=f,a.requestUrl=b,f.send()},xhrLoadWithXDR:function(a,b,c,d,e){this._warnedAboutXDomainRequest||this.game.device.ie&&!(this.game.device.ieVersion>=10)||(this._warnedAboutXDomainRequest=!0,console.warn("Phaser.Loader - using XDomainRequest outside of IE 9"));var f=new window.XDomainRequest;f.open("GET",b,!0),f.responseType=c,f.timeout=3e3,e=e||this.fileError;var g=this;f.onerror=function(){try{return e.call(g,a,f)}catch(b){g.asyncComplete(a,b.message||"Exception")}},f.ontimeout=function(){try{return e.call(g,a,f)}catch(b){g.asyncComplete(a,b.message||"Exception")}},f.onprogress=function(){},f.onload=function(){try{return d.call(g,a,f)}catch(b){g.asyncComplete(a,b.message||"Exception")}},a.requestObject=f,a.requestUrl=b,setTimeout(function(){f.send()},0)},getVideoURL:function(a){for(var b=0;b<a.length;b++){var c,d=a[b];if(d.uri)d=d.uri,c=d.type;else{if(0===d.indexOf("blob:")||0===d.indexOf("data:"))return d;d.indexOf("?")>=0&&(d=d.substr(0,d.indexOf("?")));var e=d.substr((Math.max(0,d.lastIndexOf("."))||1/0)+1);c=e.toLowerCase()}if(this.game.device.canPlayVideo(c))return a[b]}return null},getAudioURL:function(a){if(this.game.sound.noAudio)return null;for(var b=0;b<a.length;b++){var c,d=a[b];if(d.uri)d=d.uri,c=d.type;else{if(0===d.indexOf("blob:")||0===d.indexOf("data:"))return d;d.indexOf("?")>=0&&(d=d.substr(0,d.indexOf("?")));var e=d.substr((Math.max(0,d.lastIndexOf("."))||1/0)+1);c=e.toLowerCase()}if(this.game.device.canPlayAudio(c))return a[b]}return null},fileError:function(a,b,c){var d=a.requestUrl||this.transformUrl(a.url,a),e="error loading asset from URL "+d;!c&&b&&(c=b.status),c&&(e=e+" ("+c+")"),this.asyncComplete(a,e)},fileComplete:function(a,b){var d=!0;switch(a.type){case"packfile":var e=JSON.parse(b.responseText);a.data=e||{};break;case"image":this.cache.addImage(a.key,a.url,a.data);break;case"spritesheet":this.cache.addSpriteSheet(a.key,a.url,a.data,a.frameWidth,a.frameHeight,a.frameMax,a.margin,a.spacing);break;case"textureatlas":if(null==a.atlasURL)this.cache.addTextureAtlas(a.key,a.url,a.data,a.atlasData,a.format);else if(d=!1,a.format==c.Loader.TEXTURE_ATLAS_JSON_ARRAY||a.format==c.Loader.TEXTURE_ATLAS_JSON_HASH)this.xhrLoad(a,this.transformUrl(a.atlasURL,a),"text",this.jsonLoadComplete);else{if(a.format!=c.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+a.format);this.xhrLoad(a,this.transformUrl(a.atlasURL,a),"text",this.xmlLoadComplete)}break;case"bitmapfont":a.atlasURL?(d=!1,this.xhrLoad(a,this.transformUrl(a.atlasURL,a),"text",function(a,b){var c;try{c=JSON.parse(b.responseText)}catch(d){}c?(a.atlasType="json",this.jsonLoadComplete(a,b)):(a.atlasType="xml",this.xmlLoadComplete(a,b))})):this.cache.addBitmapFont(a.key,a.url,a.data,a.atlasData,a.atlasType,a.xSpacing,a.ySpacing);break;case"video":if(a.asBlob)try{a.data=new Blob([new Uint8Array(b.response)])}catch(f){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+a.key)}this.cache.addVideo(a.key,a.url,a.data,a.asBlob);break;case"audio":this.game.sound.usingWebAudio?(a.data=b.response,this.cache.addSound(a.key,a.url,a.data,!0,!1),a.autoDecode&&this.game.sound.decode(a.key)):this.cache.addSound(a.key,a.url,a.data,!1,!0);break;case"text":a.data=b.responseText,this.cache.addText(a.key,a.url,a.data);break;case"shader":a.data=b.responseText,this.cache.addShader(a.key,a.url,a.data);break;case"physics":var e=JSON.parse(b.responseText);this.cache.addPhysicsData(a.key,a.url,e,a.format);break;case"script":a.data=document.createElement("script"),a.data.language="javascript",a.data.type="text/javascript",a.data.defer=!1,a.data.text=b.responseText,document.head.appendChild(a.data),a.callback&&(a.data=a.callback.call(a.callbackContext,a.key,b.responseText));break;case"binary":a.data=a.callback?a.callback.call(a.callbackContext,a.key,b.response):b.response,this.cache.addBinary(a.key,a.data)}d&&this.asyncComplete(a)},jsonLoadComplete:function(a,b){var c=JSON.parse(b.responseText);"tilemap"===a.type?this.cache.addTilemap(a.key,a.url,c,a.format):"bitmapfont"===a.type?this.cache.addBitmapFont(a.key,a.url,a.data,c,a.atlasType,a.xSpacing,a.ySpacing):"json"===a.type?this.cache.addJSON(a.key,a.url,c):this.cache.addTextureAtlas(a.key,a.url,a.data,c,a.format),this.asyncComplete(a)},csvLoadComplete:function(a,b){var c=b.responseText;this.cache.addTilemap(a.key,a.url,c,a.format),this.asyncComplete(a)},xmlLoadComplete:function(a,b){var c=b.responseText,d=this.parseXml(c);if(!d){var e=b.responseType||b.contentType;return console.warn("Phaser.Loader - "+a.key+": invalid XML ("+e+")"),void this.asyncComplete(a,"invalid XML")}"bitmapfont"===a.type?this.cache.addBitmapFont(a.key,a.url,a.data,d,a.atlasType,a.xSpacing,a.ySpacing):"textureatlas"===a.type?this.cache.addTextureAtlas(a.key,a.url,a.data,d,a.format):"xml"===a.type&&this.cache.addXML(a.key,a.url,d),this.asyncComplete(a)},parseXml:function(a){var b;try{if(window.DOMParser){var c=new DOMParser;b=c.parseFromString(a,"text/xml")}else b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a)}catch(d){b=null}return b&&b.documentElement&&!b.getElementsByTagName("parsererror").length?b:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(c.Loader.prototype,"progressFloat",{get:function(){var a=this._loadedFileCount/this._totalFileCount*100;return c.Math.clamp(a||0,0,100)}}),Object.defineProperty(c.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),c.Loader.prototype.constructor=c.Loader,c.LoaderParser={bitmapFont:function(a,b,c,d){return this.xmlBitmapFont(a,b,c,d)},xmlBitmapFont:function(a,b,c,d){var e={},f=a.getElementsByTagName("info")[0],g=a.getElementsByTagName("common")[0];e.font=f.getAttribute("face"),e.size=parseInt(f.getAttribute("size"),10),e.lineHeight=parseInt(g.getAttribute("lineHeight"),10)+d,e.chars={};for(var h=a.getElementsByTagName("char"),i=0;i<h.length;i++){var j=parseInt(h[i].getAttribute("id"),10);e.chars[j]={x:parseInt(h[i].getAttribute("x"),10),y:parseInt(h[i].getAttribute("y"),10),width:parseInt(h[i].getAttribute("width"),10),height:parseInt(h[i].getAttribute("height"),10),xOffset:parseInt(h[i].getAttribute("xoffset"),10),yOffset:parseInt(h[i].getAttribute("yoffset"),10),xAdvance:parseInt(h[i].getAttribute("xadvance"),10)+c,kerning:{}}}var k=a.getElementsByTagName("kerning");for(i=0;i<k.length;i++){var l=parseInt(k[i].getAttribute("first"),10),m=parseInt(k[i].getAttribute("second"),10),n=parseInt(k[i].getAttribute("amount"),10);e.chars[m].kerning[l]=n}return this.finalizeBitmapFont(b,e)},jsonBitmapFont:function(a,b,c,d){var e={font:a.font.info._face,size:parseInt(a.font.info._size,10),lineHeight:parseInt(a.font.common._lineHeight,10)+d,chars:{}};return a.font.chars["char"].forEach(function(a){var b=parseInt(a._id,10);e.chars[b]={x:parseInt(a._x,10),y:parseInt(a._y,10),width:parseInt(a._width,10),height:parseInt(a._height,10),xOffset:parseInt(a._xoffset,10),yOffset:parseInt(a._yoffset,10),xAdvance:parseInt(a._xadvance,10)+c,kerning:{}}}),a.font.kernings&&a.font.kernings.kerning&&a.font.kernings.kerning.forEach(function(a){e.chars[a._second].kerning[a._first]=parseInt(a._amount,10)}),this.finalizeBitmapFont(b,e)},finalizeBitmapFont:function(a,b){return Object.keys(b.chars).forEach(function(d){var e=b.chars[d];e.texture=new PIXI.Texture(a,new c.Rectangle(e.x,e.y,e.width,e.height))
+}),b}},c.AudioSprite=function(a,b){this.game=a,this.key=b,this.config=this.game.cache.getJSON(b+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var c in this.config.spritemap){var d=this.config.spritemap[c],e=this.game.add.sound(this.key);e.addMarker(c,d.start,d.end-d.start,null,d.loop),this.sounds[c]=e}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},c.AudioSprite.prototype={play:function(a,b){return void 0===b&&(b=1),this.sounds[a].play(a,null,b)},stop:function(a){if(a)this.sounds[a].stop();else for(var b in this.sounds)this.sounds[b].stop()},get:function(a){return this.sounds[a]}},c.AudioSprite.prototype.constructor=c.AudioSprite,c.Sound=function(a,b,d,e,f){void 0===d&&(d=1),void 0===e&&(e=!1),void 0===f&&(f=a.sound.connectToMaster),this.game=a,this.name=b,this.key=b,this.loop=e,this.volume=d,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,this.gainNode=void 0===this.context.createGain?this.context.createGainNode():this.context.createGain(),this.gainNode.gain.value=d*this.game.sound.volume,f&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(b)&&this.game.cache.isSoundReady(b)?(this._sound=this.game.cache.getSoundData(b),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new c.Signal,this.onPlay=new c.Signal,this.onPause=new c.Signal,this.onResume=new c.Signal,this.onLoop=new c.Signal,this.onStop=new c.Signal,this.onMute=new c.Signal,this.onMarkerComplete=new c.Signal,this.onFadeComplete=new c.Signal,this._volume=d,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},c.Sound.prototype={soundHasUnlocked:function(a){a===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(a,b,c,d,e){(void 0===d||null===d)&&(d=1),void 0===e&&(e=!1),this.markers[a]={name:a,start:b,stop:b+c,volume:d,duration:c,durationMS:1e3*c,loop:e}},removeMarker:function(a){delete this.markers[a]},onEndedHandler:function(){this.isPlaying=!1,this.stop()},update:function(){return this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),void(this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop())))):void this.destroy()},loopFull:function(a){this.play(null,0,a,!0)},play:function(a,b,c,d,e){if((void 0===a||a===!1||null===a)&&(a=""),void 0===e&&(e=!0),this.isPlaying&&!this.allowMultiple&&!e&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||e))if(this.usingWebAudio)if(this._sound.disconnect(this.externalNode?this.externalNode:this.gainNode),void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(f){}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(""===a&&Object.keys(this.markers).length>0)return this;if(""!==a){if(this.currentMarker=a,!this.markers[a])return this;this.position=this.markers[a].start,this.volume=this.markers[a].volume,this.loop=this.markers[a].loop,this.duration=this.markers[a].duration,this.durationMS=this.markers[a].durationMS,"undefined"!=typeof c&&(this.volume=c),"undefined"!=typeof d&&(this.loop=d),this._tempMarker=a,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else b=b||0,void 0===c&&(c=this._volume),void 0===d&&(d=this.loop),this.position=b,this.volume=c,this.loop=d,this.duration=0,this.durationMS=0,this._tempMarker=a,this._tempPosition=b,this._tempVolume=c,this._tempLoop=d;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this._sound.connect(this.externalNode?this.externalNode:this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===a&&(this._sound.loop=!0),this.loop||""!==a||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===a?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).isDecoding===!1&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._sound.volume=this._muted?0:this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(a,b,c,d){a=a||"",b=b||0,c=c||1,void 0===d&&(d=!1),this.play(a,b,c,d,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var a=this.position+this.pausedPosition/1e3;this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this._sound.connect(this.externalNode?this.externalNode:this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var b=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,a,b):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,a):this._sound.start(0,a,b)}else this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio)if(this._sound.disconnect(this.externalNode?this.externalNode:this.gainNode),void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(a){}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.pendingPlayback=!1,this.isPlaying=!1;var b=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.paused||this.onStop.dispatch(this,b)},fadeIn:function(a,b,c){void 0===b&&(b=!1),void 0===c&&(c=this.currentMarker),this.paused||(this.play(c,0,0,b),this.fadeTo(a,1))},fadeOut:function(a){this.fadeTo(a,0)},fadeTo:function(a,b){if(this.isPlaying&&!this.paused&&b!==this.volume){if(void 0===a&&(a=1e3),void 0===b)return void console.warn("Phaser.Sound.fadeTo: No Volume Specified.");this.fadeTween=this.game.add.tween(this).to({volume:b},a,c.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)}},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},destroy:function(a){void 0===a&&(a=!0),this.stop(),a?this.game.sound.remove(this):(this.markers={},this.context=null,this._buffer=null,this.externalNode=null,this.onDecoded.dispose(),this.onPlay.dispose(),this.onPause.dispose(),this.onResume.dispose(),this.onLoop.dispose(),this.onStop.dispose(),this.onMute.dispose(),this.onMarkerComplete.dispose())}},c.Sound.prototype.constructor=c.Sound,Object.defineProperty(c.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(c.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(c.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(a){a=a||!1,a!==this._muted&&(a?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(c.Sound.prototype,"volume",{get:function(){return this._volume},set:function(a){return this.game.device.firefox&&this.usingAudioTag&&(a=this.game.math.clamp(a,0,1)),this._muted?void(this._muteVolume=a):(this._tempVolume=a,this._volume=a,void(this.usingWebAudio?this.gainNode.gain.value=a:this.usingAudioTag&&this._sound&&(this._sound.volume=a)))}}),c.SoundManager=function(a){this.game=a,this.onSoundDecode=new c.Signal,this.onVolumeChange=new c.Signal,this.onMute=new c.Signal,this.onUnMute=new c.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new c.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},c.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&this.game.device.webAudio===!1&&(this.channels=1),window.PhaserGlobal){if(window.PhaserGlobal.disableAudio===!0)return this.noAudio=!0,void(this.touchLocked=!1);if(window.PhaserGlobal.disableWebAudio===!0)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(window.PhaserGlobal&&window.PhaserGlobal.audioContext)this.context=window.PhaserGlobal.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(a){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(a){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,this.masterGain=void 0===this.context.createGain?this.context.createGainNode():this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||(!this.game.device.cocoonJS&&this.game.device.iOS||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)&&this.setTouchLock()},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.touchLocked=!1,this._unlockSource=null;else if(this.usingWebAudio){var a=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=a,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0)}return!0},stopAll:function(){if(!this.noAudio)for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].stop()},pauseAll:function(){if(!this.noAudio)for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].pause()},resumeAll:function(){if(!this.noAudio)for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].resume()},decode:function(a,b){b=b||null;var c=this.game.cache.getSoundData(a);if(c&&this.game.cache.isSoundDecoded(a)===!1){this.game.cache.updateSound(a,"isDecoding",!0);var d=this;try{this.context.decodeAudioData(c,function(c){c&&(d.game.cache.decodedSound(a,c),d.onSoundDecode.dispatch(a,b))})}catch(e){}}},setDecodedCallback:function(a,b,d){"string"==typeof a&&(a=[a]),this._watchList.reset();for(var e=0;e<a.length;e++)a[e]instanceof c.Sound?this.game.cache.isSoundDecoded(a[e].key)||this._watchList.add(a[e].key):this.game.cache.isSoundDecoded(a[e])||this._watchList.add(a[e]);0===this._watchList.total?(this._watching=!1,b.call(d)):(this._watching=!0,this._watchCallback=b,this._watchContext=d)},update:function(){if(!this.noAudio){!this.touchLocked||null===this._unlockSource||this._unlockSource.playbackState!==this._unlockSource.PLAYING_STATE&&this._unlockSource.playbackState!==this._unlockSource.FINISHED_STATE||(this.touchLocked=!1,this._unlockSource=null);for(var a=0;a<this._sounds.length;a++)this._sounds[a].update();if(this._watching){for(var b=this._watchList.first;b;)this.game.cache.isSoundDecoded(b)&&this._watchList.remove(b),b=this._watchList.next;0===this._watchList.total&&(this._watching=!1,this._watchCallback.call(this._watchContext))}}},add:function(a,b,d,e){void 0===b&&(b=1),void 0===d&&(d=!1),void 0===e&&(e=this.connectToMaster);var f=new c.Sound(this.game,a,b,d,e);return this._sounds.push(f),f},addSprite:function(a){var b=new c.AudioSprite(this.game,a);return b},remove:function(a){for(var b=this._sounds.length;b--;)if(this._sounds[b]===a)return this._sounds[b].destroy(!1),this._sounds.splice(b,1),!0;return!1},removeByKey:function(a){for(var b=this._sounds.length,c=0;b--;)this._sounds[b].key===a&&(this._sounds[b].destroy(!1),this._sounds.splice(b,1),c++);return c},play:function(a,b,c){if(!this.noAudio){var d=this.add(a,b,c);return d.play(),d}},setMute:function(){if(!this._muted){this._muted=!0,this.usingWebAudio&&(this._muteVolume=this.masterGain.gain.value,this.masterGain.gain.value=0);for(var a=0;a<this._sounds.length;a++)this._sounds[a].usingAudioTag&&(this._sounds[a].mute=!0);this.onMute.dispatch()}},unsetMute:function(){if(this._muted&&!this._codeMuted){this._muted=!1,this.usingWebAudio&&(this.masterGain.gain.value=this._muteVolume);for(var a=0;a<this._sounds.length;a++)this._sounds[a].usingAudioTag&&(this._sounds[a].mute=!1);this.onUnMute.dispatch()}},destroy:function(){this.stopAll();for(var a=0;a<this._sounds.length;a++)this._sounds[a]&&this._sounds[a].destroy();this._sounds=[],this.onSoundDecode.dispose(),this.context&&window.PhaserGlobal&&(window.PhaserGlobal.audioContext=this.context)}},c.SoundManager.prototype.constructor=c.SoundManager,Object.defineProperty(c.SoundManager.prototype,"mute",{get:function(){return this._muted},set:function(a){if(a=a||!1){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(c.SoundManager.prototype,"volume",{get:function(){return this._volume},set:function(a){if(0>a?a=0:a>1&&(a=1),this._volume!==a){if(this._volume=a,this.usingWebAudio)this.masterGain.gain.value=a;else for(var b=0;b<this._sounds.length;b++)this._sounds[b].usingAudioTag&&(this._sounds[b].volume=this._sounds[b].volume*a);this.onVolumeChange.dispatch(a)}}}),c.Utils.Debug=function(a){this.game=a,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.renderShadow=!0,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1},c.Utils.Debug.prototype={boot:function(){this.game.renderType===c.CANVAS?this.context=this.game.context:(this.bmd=this.game.make.bitmapData(this.game.width,this.game.height),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.canvas=c.Canvas.create(this.game.width,this.game.height,"",!0),this.context=this.canvas.getContext("2d"))},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(a,b,c,d){"number"!=typeof a&&(a=0),"number"!=typeof b&&(b=0),c=c||"rgb(255,255,255)",void 0===d&&(d=0),this.currentX=a,this.currentY=b,this.currentColor=c,this.columnWidth=d,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=c,this.context.fillStyle=c,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var a=this.currentX,b=0;b<arguments.length;b++)this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(arguments[b],a+1,this.currentY+1),this.context.fillStyle=this.currentColor),this.context.fillText(arguments[b],a,this.currentY),a+=this.columnWidth;this.currentY+=this.lineHeight},soundInfo:function(a,b,c,d){this.start(b,c,d),this.line("Sound: "+a.key+" Locked: "+a.game.sound.touchLocked),this.line("Is Ready?: "+this.game.cache.isSoundReady(a.key)+" Pending Playback: "+a.pendingPlayback),this.line("Decoded: "+a.isDecoded+" Decoding: "+a.isDecoding),this.line("Total Duration: "+a.totalDuration+" Playing: "+a.isPlaying),this.line("Time: "+a.currentTime),this.line("Volume: "+a.volume+" Muted: "+a.mute),this.line("WebAudio: "+a.usingWebAudio+" Audio: "+a.usingAudioTag),""!==a.currentMarker&&(this.line("Marker: "+a.currentMarker+" Duration: "+a.duration+" (ms: "+a.durationMS+")"),this.line("Start: "+a.markers[a.currentMarker].start+" Stop: "+a.markers[a.currentMarker].stop),this.line("Position: "+a.position)),this.stop()},cameraInfo:function(a,b,c,d){this.start(b,c,d),this.line("Camera ("+a.width+" x "+a.height+")"),this.line("X: "+a.x+" Y: "+a.y),a.bounds&&this.line("Bounds x: "+a.bounds.x+" Y: "+a.bounds.y+" w: "+a.bounds.width+" h: "+a.bounds.height),this.line("View x: "+a.view.x+" Y: "+a.view.y+" w: "+a.view.width+" h: "+a.view.height),this.line("Total in view: "+a.totalInView),this.stop()},timer:function(a,b,c,d){this.start(b,c,d),this.line("Timer (running: "+a.running+" expired: "+a.expired+")"),this.line("Next Tick: "+a.next+" Duration: "+a.duration),this.line("Paused: "+a.paused+" Length: "+a.length),this.stop()},pointer:function(a,b,c,d,e){null!=a&&(void 0===b&&(b=!1),c=c||"rgba(0,255,0,0.5)",d=d||"rgba(255,0,0,0.5)",(b!==!0||a.isUp!==!0)&&(this.start(a.x,a.y-100,e),this.context.beginPath(),this.context.arc(a.x,a.y,a.circle.radius,0,2*Math.PI),this.context.fillStyle=a.active?c:d,this.context.fill(),this.context.closePath(),this.context.beginPath(),this.context.moveTo(a.positionDown.x,a.positionDown.y),this.context.lineTo(a.position.x,a.position.y),this.context.lineWidth=2,this.context.stroke(),this.context.closePath(),this.line("ID: "+a.id+" Active: "+a.active),this.line("World X: "+a.worldX+" World Y: "+a.worldY),this.line("Screen X: "+a.x+" Screen Y: "+a.y),this.line("Duration: "+a.duration+" ms"),this.line("is Down: "+a.isDown+" is Up: "+a.isUp),this.stop()))},spriteInputInfo:function(a,b,c,d){this.start(b,c,d),this.line("Sprite Input: ("+a.width+" x "+a.height+")"),this.line("x: "+a.input.pointerX().toFixed(1)+" y: "+a.input.pointerY().toFixed(1)),this.line("over: "+a.input.pointerOver()+" duration: "+a.input.overDuration().toFixed(0)),this.line("down: "+a.input.pointerDown()+" duration: "+a.input.downDuration().toFixed(0)),this.line("just over: "+a.input.justOver()+" just out: "+a.input.justOut()),this.stop()},key:function(a,b,c,d){this.start(b,c,d,150),this.line("Key:",a.keyCode,"isDown:",a.isDown),this.line("justDown:",a.justDown,"justUp:",a.justUp),this.line("Time Down:",a.timeDown.toFixed(0),"duration:",a.duration.toFixed(0)),this.stop()},inputInfo:function(a,b,c){this.start(a,b,c),this.line("Input"),this.line("X: "+this.game.input.x+" Y: "+this.game.input.y),this.line("World X: "+this.game.input.worldX+" World Y: "+this.game.input.worldY),this.line("Scale X: "+this.game.input.scale.x.toFixed(1)+" Scale Y: "+this.game.input.scale.x.toFixed(1)),this.line("Screen X: "+this.game.input.activePointer.screenX+" Screen Y: "+this.game.input.activePointer.screenY),this.stop()},spriteBounds:function(a,b,c){var d=a.getBounds();d.x+=this.game.camera.x,d.y+=this.game.camera.y,this.rectangle(d,b,c)},ropeSegments:function(a,b,c){var d=a.segments,e=this;d.forEach(function(a){e.rectangle(a,b,c)},this)},spriteInfo:function(a,b,c,d){this.start(b,c,d),this.line("Sprite:  ("+a.width+" x "+a.height+") anchor: "+a.anchor.x+" x "+a.anchor.y),this.line("x: "+a.x.toFixed(1)+" y: "+a.y.toFixed(1)),this.line("angle: "+a.angle.toFixed(1)+" rotation: "+a.rotation.toFixed(1)),this.line("visible: "+a.visible+" in camera: "+a.inCamera),this.line("bounds x: "+a._bounds.x.toFixed(1)+" y: "+a._bounds.y.toFixed(1)+" w: "+a._bounds.width.toFixed(1)+" h: "+a._bounds.height.toFixed(1)),this.stop()},spriteCoords:function(a,b,c,d){this.start(b,c,d,100),a.name&&this.line(a.name),this.line("x:",a.x.toFixed(2),"y:",a.y.toFixed(2)),this.line("pos x:",a.position.x.toFixed(2),"pos y:",a.position.y.toFixed(2)),this.line("world x:",a.world.x.toFixed(2),"world y:",a.world.y.toFixed(2)),this.stop()},lineInfo:function(a,b,c,d){this.start(b,c,d,80),this.line("start.x:",a.start.x.toFixed(2),"start.y:",a.start.y.toFixed(2)),this.line("end.x:",a.end.x.toFixed(2),"end.y:",a.end.y.toFixed(2)),this.line("length:",a.length.toFixed(2),"angle:",a.angle),this.stop()},pixel:function(a,b,c,d){d=d||2,this.start(),this.context.fillStyle=c,this.context.fillRect(a,b,d,d),this.stop()},geom:function(a,b,d,e){void 0===d&&(d=!0),void 0===e&&(e=0),b=b||"rgba(0,255,0,0.4)",this.start(),this.context.fillStyle=b,this.context.strokeStyle=b,a instanceof c.Rectangle||1===e?d?this.context.fillRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height):this.context.strokeRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height):a instanceof c.Circle||2===e?(this.context.beginPath(),this.context.arc(a.x-this.game.camera.x,a.y-this.game.camera.y,a.radius,0,2*Math.PI,!1),this.context.closePath(),d?this.context.fill():this.context.stroke()):a instanceof c.Point||3===e?this.context.fillRect(a.x-this.game.camera.x,a.y-this.game.camera.y,4,4):(a instanceof c.Line||4===e)&&(this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(a.start.x+.5-this.game.camera.x,a.start.y+.5-this.game.camera.y),this.context.lineTo(a.end.x+.5-this.game.camera.x,a.end.y+.5-this.game.camera.y),this.context.closePath(),this.context.stroke()),this.stop()},rectangle:function(a,b,c){void 0===c&&(c=!0),b=b||"rgba(0, 255, 0, 0.4)",this.start(),c?(this.context.fillStyle=b,this.context.fillRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height)):(this.context.strokeStyle=b,this.context.strokeRect(a.x-this.game.camera.x,a.y-this.game.camera.y,a.width,a.height)),this.stop()},text:function(a,b,c,d,e){d=d||"rgb(255,255,255)",e=e||"16px Courier",this.start(),this.context.font=e,this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(a,b+1,c+1)),this.context.fillStyle=d,this.context.fillText(a,b,c),this.stop()},quadTree:function(a,b){b=b||"rgba(255,0,0,0.3)",this.start();var c=a.bounds;if(0===a.nodes.length){this.context.strokeStyle=b,this.context.strokeRect(c.x,c.y,c.width,c.height),this.text("size: "+a.objects.length,c.x+4,c.y+16,"rgb(0,200,0)","12px Courier"),this.context.strokeStyle="rgb(0,255,0)";for(var d=0;d<a.objects.length;d++)this.context.strokeRect(a.objects[d].x,a.objects[d].y,a.objects[d].width,a.objects[d].height)}else for(var d=0;d<a.nodes.length;d++)this.quadTree(a.nodes[d]);this.stop()},body:function(a,b,d){a.body&&(this.start(),a.body.type===c.Physics.ARCADE?c.Physics.Arcade.Body.render(this.context,a.body,b,d):a.body.type===c.Physics.NINJA?c.Physics.Ninja.Body.render(this.context,a.body,b,d):a.body.type===c.Physics.BOX2D&&c.Physics.Box2D.renderBody(this.context,a.body,b),this.stop())},bodyInfo:function(a,b,d,e){a.body&&(this.start(b,d,e,210),a.body.type===c.Physics.ARCADE?c.Physics.Arcade.Body.renderBodyInfo(this,a.body):a.body.type===c.Physics.BOX2D&&this.game.physics.box2d.renderBodyInfo(this,a.body),this.stop())},box2dWorld:function(){this.start(),this.context.translate(-this.game.camera.view.x,-this.game.camera.view.y,0),this.game.physics.box2d.renderDebugDraw(this.context),this.stop()},box2dBody:function(a,b){this.start(),c.Physics.Box2D.renderBody(this.context,a,b),this.stop()}},c.Utils.Debug.prototype.constructor=c.Utils.Debug,c.ArraySet=function(a){this.position=0,this.list=a||[]},c.ArraySet.prototype={add:function(a){return this.exists(a)||this.list.push(a),a},getIndex:function(a){return this.list.indexOf(a)},getByKey:function(a,b){for(var c=this.list.length;c--;)if(this.list[c][a]===b)return this.list[c];return null},exists:function(a){return this.list.indexOf(a)>-1},reset:function(){this.list.length=0},remove:function(a){var b=this.list.indexOf(a);return b>-1?(this.list.splice(b,1),a):void 0},setAll:function(a,b){for(var c=this.list.length;c--;)this.list[c]&&(this.list[c][a]=b)},callAll:function(a){for(var b=Array.prototype.splice.call(arguments,1),c=this.list.length;c--;)this.list[c]&&this.list[c][a]&&this.list[c][a].apply(this.list[c],b)},removeAll:function(a){void 0===a&&(a=!1);for(var b=this.list.length;b--;)if(this.list[b]){var c=this.remove(this.list[b]);a&&c.destroy()}this.position=0,this.list=[]}},Object.defineProperty(c.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(c.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(c.ArraySet.prototype,"next",{get:function(){return this.position<this.list.length?(this.position++,this.list[this.position]):null}}),c.ArraySet.prototype.constructor=c.ArraySet,c.ArrayUtils={getRandomItem:function(a,b,c){if(null==a)return null;void 0===b&&(b=0),void 0===c&&(c=a.length);var d=b+Math.floor(Math.random()*c);return void 0===a[d]?null:a[d]},removeRandomItem:function(a,b,c){if(null==a)return null;void 0===b&&(b=0),void 0===c&&(c=a.length);var d=b+Math.floor(Math.random()*c);if(d<a.length){var e=a.splice(d,1);return void 0===e[0]?null:e[0]}return null},shuffle:function(a){for(var b=a.length-1;b>0;b--){var c=Math.floor(Math.random()*(b+1)),d=a[b];a[b]=a[c],a[c]=d}return a},transposeMatrix:function(a){for(var b=a.length,c=a[0].length,d=new Array(c),e=0;c>e;e++){d[e]=new Array(b);for(var f=b-1;f>-1;f--)d[e][f]=a[f][e]}return d},rotateMatrix:function(a,b){if("string"!=typeof b&&(b=(b%360+360)%360),90===b||-270===b||"rotateLeft"===b)a=c.ArrayUtils.transposeMatrix(a),a=a.reverse();else if(-90===b||270===b||"rotateRight"===b)a=a.reverse(),a=c.ArrayUtils.transposeMatrix(a);else if(180===Math.abs(b)||"rotate180"===b){for(var d=0;d<a.length;d++)a[d].reverse();a=a.reverse()}return a},findClosest:function(a,b){if(!b.length)return 0/0;if(1===b.length||a<b[0])return b[0];for(var c=1;b[c]<a;)c++;var d=b[c-1],e=c<b.length?b[c]:Number.POSITIVE_INFINITY;return a-d>=e-a?e:d},rotate:function(a){var b=a.shift();return a.push(b),b},numberArray:function(a,b){for(var c=[],d=a;b>=d;d++)c.push(d);return c},numberArrayStep:function(a,b,d){a=+a||0;var e=typeof b;"number"!==e&&"string"!==e||!d||d[b]!==a||(b=d=null),d=null==d?1:+d||0,null===b?(b=a,a=0):b=+b||0;for(var f=-1,g=Math.max(c.Math.roundAwayFromZero((b-a)/(d||1)),0),h=new Array(g);++f<g;)h[f]=a,a+=d;return h}},c.Color={packPixel:function(a,b,d,e){return c.Device.LITTLE_ENDIAN?(e<<24|d<<16|b<<8|a)>>>0:(a<<24|b<<16|d<<8|e)>>>0},unpackPixel:function(a,b,d,e){return(void 0===b||null===b)&&(b=c.Color.createColor()),(void 0===d||null===d)&&(d=!1),(void 0===e||null===e)&&(e=!1),c.Device.LITTLE_ENDIAN?(b.a=(4278190080&a)>>>24,b.b=(16711680&a)>>>16,b.g=(65280&a)>>>8,b.r=255&a):(b.r=(4278190080&a)>>>24,b.g=(16711680&a)>>>16,b.b=(65280&a)>>>8,b.a=255&a),b.color=a,b.rgba="rgba("+b.r+","+b.g+","+b.b+","+b.a/255+")",d&&c.Color.RGBtoHSL(b.r,b.g,b.b,b),e&&c.Color.RGBtoHSV(b.r,b.g,b.b,b),b},fromRGBA:function(a,b){return b||(b=c.Color.createColor()),b.r=(4278190080&a)>>>24,b.g=(16711680&a)>>>16,b.b=(65280&a)>>>8,b.a=255&a,b.rgba="rgba("+b.r+","+b.g+","+b.b+","+b.a+")",b},toRGBA:function(a,b,c,d){return a<<24|b<<16|c<<8|d},RGBtoHSL:function(a,b,d,e){e||(e=c.Color.createColor(a,b,d,1)),a/=255,b/=255,d/=255;var f=Math.min(a,b,d),g=Math.max(a,b,d);if(e.h=0,e.s=0,e.l=(g+f)/2,g!==f){var h=g-f;e.s=e.l>.5?h/(2-g-f):h/(g+f),g===a?e.h=(b-d)/h+(d>b?6:0):g===b?e.h=(d-a)/h+2:g===d&&(e.h=(a-b)/h+4),e.h/=6}return e},HSLtoRGB:function(a,b,d,e){if(e?(e.r=d,e.g=d,e.b=d):e=c.Color.createColor(d,d,d),0!==b){var f=.5>d?d*(1+b):d+b-d*b,g=2*d-f;e.r=c.Color.hueToColor(g,f,a+1/3),e.g=c.Color.hueToColor(g,f,a),e.b=c.Color.hueToColor(g,f,a-1/3)}return e.r=Math.floor(255*e.r|0),e.g=Math.floor(255*e.g|0),e.b=Math.floor(255*e.b|0),c.Color.updateColor(e),e},RGBtoHSV:function(a,b,d,e){e||(e=c.Color.createColor(a,b,d,255)),a/=255,b/=255,d/=255;var f=Math.min(a,b,d),g=Math.max(a,b,d),h=g-f;return e.h=0,e.s=0===g?0:h/g,e.v=g,g!==f&&(g===a?e.h=(b-d)/h+(d>b?6:0):g===b?e.h=(d-a)/h+2:g===d&&(e.h=(a-b)/h+4),e.h/=6),e},HSVtoRGB:function(a,b,d,e){void 0===e&&(e=c.Color.createColor(0,0,0,1,a,b,0,d));var f,g,h,i=Math.floor(6*a),j=6*a-i,k=d*(1-b),l=d*(1-j*b),m=d*(1-(1-j)*b);switch(i%6){case 0:f=d,g=m,h=k;break;case 1:f=l,g=d,h=k;break;case 2:f=k,g=d,h=m;break;case 3:f=k,g=l,h=d;break;case 4:f=m,g=k,h=d;break;case 5:f=d,g=k,h=l}return e.r=Math.floor(255*f),e.g=Math.floor(255*g),e.b=Math.floor(255*h),c.Color.updateColor(e),e},hueToColor:function(a,b,c){return 0>c&&(c+=1),c>1&&(c-=1),1/6>c?a+6*(b-a)*c:.5>c?b:2/3>c?a+(b-a)*(2/3-c)*6:a},createColor:function(a,b,d,e,f,g,h,i){var j={r:a||0,g:b||0,b:d||0,a:e||1,h:f||0,s:g||0,l:h||0,v:i||0,color:0,color32:0,rgba:""};return c.Color.updateColor(j)},updateColor:function(a){return a.rgba="rgba("+a.r.toString()+","+a.g.toString()+","+a.b.toString()+","+a.a.toString()+")",a.color=c.Color.getColor(a.r,a.g,a.b),a.color32=c.Color.getColor32(a.a,a.r,a.g,a.b),a},getColor32:function(a,b,c,d){return a<<24|b<<16|c<<8|d},getColor:function(a,b,c){return a<<16|b<<8|c},RGBtoString:function(a,b,d,e,f){return void 0===e&&(e=255),void 0===f&&(f="#"),"#"===f?"#"+((1<<24)+(a<<16)+(b<<8)+d).toString(16).slice(1):"0x"+c.Color.componentToHex(e)+c.Color.componentToHex(a)+c.Color.componentToHex(b)+c.Color.componentToHex(d)},hexToRGB:function(a){var b=c.Color.hexToColor(a);return b?c.Color.getColor32(b.a,b.r,b.g,b.b):void 0},hexToColor:function(a,b){a=a.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(a,b,c,d){return b+b+c+c+d+d});var d=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);if(d){var e=parseInt(d[1],16),f=parseInt(d[2],16),g=parseInt(d[3],16);b?(b.r=e,b.g=f,b.b=g):b=c.Color.createColor(e,f,g)}return b},webToColor:function(a,b){b||(b=c.Color.createColor());var d=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(a);return d&&(b.r=parseInt(d[1],10),b.g=parseInt(d[2],10),b.b=parseInt(d[3],10),b.a=void 0!==d[4]?parseFloat(d[4]):1,c.Color.updateColor(b)),b
+},valueToColor:function(a,b){if(b||(b=c.Color.createColor()),"string"==typeof a)return 0===a.indexOf("rgb")?c.Color.webToColor(a,b):(b.a=1,c.Color.hexToColor(a,b));if("number"==typeof a){var d=c.Color.getRGB(a);return b.r=d.r,b.g=d.g,b.b=d.b,b.a=d.a/255,b}return b},componentToHex:function(a){var b=a.toString(16);return 1==b.length?"0"+b:b},HSVColorWheel:function(a,b){void 0===a&&(a=1),void 0===b&&(b=1);for(var d=[],e=0;359>=e;e++)d.push(c.Color.HSVtoRGB(e/359,a,b));return d},HSLColorWheel:function(a,b){void 0===a&&(a=.5),void 0===b&&(b=.5);for(var d=[],e=0;359>=e;e++)d.push(c.Color.HSLtoRGB(e/359,a,b));return d},interpolateColor:function(a,b,d,e,f){void 0===f&&(f=255);var g=c.Color.getRGB(a),h=c.Color.getRGB(b),i=(h.red-g.red)*e/d+g.red,j=(h.green-g.green)*e/d+g.green,k=(h.blue-g.blue)*e/d+g.blue;return c.Color.getColor32(f,i,j,k)},interpolateColorWithRGB:function(a,b,d,e,f,g){var h=c.Color.getRGB(a),i=(b-h.red)*g/f+h.red,j=(d-h.green)*g/f+h.green,k=(e-h.blue)*g/f+h.blue;return c.Color.getColor(i,j,k)},interpolateRGB:function(a,b,d,e,f,g,h,i){var j=(e-a)*i/h+a,k=(f-b)*i/h+b,l=(g-d)*i/h+d;return c.Color.getColor(j,k,l)},getRandomColor:function(a,b,d){if(void 0===a&&(a=0),void 0===b&&(b=255),void 0===d&&(d=255),b>255||a>b)return c.Color.getColor(255,255,255);var e=a+Math.round(Math.random()*(b-a)),f=a+Math.round(Math.random()*(b-a)),g=a+Math.round(Math.random()*(b-a));return c.Color.getColor32(d,e,f,g)},getRGB:function(a){return a>16777215?{alpha:a>>>24,red:a>>16&255,green:a>>8&255,blue:255&a,a:a>>>24,r:a>>16&255,g:a>>8&255,b:255&a}:{alpha:255,red:a>>16&255,green:a>>8&255,blue:255&a,a:255,r:a>>16&255,g:a>>8&255,b:255&a}},getWebRGB:function(a){if("object"==typeof a)return"rgba("+a.r.toString()+","+a.g.toString()+","+a.b.toString()+","+(a.a/255).toString()+")";var b=c.Color.getRGB(a);return"rgba("+b.r.toString()+","+b.g.toString()+","+b.b.toString()+","+(b.a/255).toString()+")"},getAlpha:function(a){return a>>>24},getAlphaFloat:function(a){return(a>>>24)/255},getRed:function(a){return a>>16&255},getGreen:function(a){return a>>8&255},getBlue:function(a){return 255&a},blendNormal:function(a){return a},blendLighten:function(a,b){return b>a?b:a},blendDarken:function(a,b){return b>a?a:b},blendMultiply:function(a,b){return a*b/255},blendAverage:function(a,b){return(a+b)/2},blendAdd:function(a,b){return Math.min(255,a+b)},blendSubtract:function(a,b){return Math.max(0,a+b-255)},blendDifference:function(a,b){return Math.abs(a-b)},blendNegation:function(a,b){return 255-Math.abs(255-a-b)},blendScreen:function(a,b){return 255-((255-a)*(255-b)>>8)},blendExclusion:function(a,b){return a+b-2*a*b/255},blendOverlay:function(a,b){return 128>b?2*a*b/255:255-2*(255-a)*(255-b)/255},blendSoftLight:function(a,b){return 128>b?2*((a>>1)+64)*(b/255):255-2*(255-((a>>1)+64))*(255-b)/255},blendHardLight:function(a,b){return c.Color.blendOverlay(b,a)},blendColorDodge:function(a,b){return 255===b?b:Math.min(255,(a<<8)/(255-b))},blendColorBurn:function(a,b){return 0===b?b:Math.max(0,255-(255-a<<8)/b)},blendLinearDodge:function(a,b){return c.Color.blendAdd(a,b)},blendLinearBurn:function(a,b){return c.Color.blendSubtract(a,b)},blendLinearLight:function(a,b){return 128>b?c.Color.blendLinearBurn(a,2*b):c.Color.blendLinearDodge(a,2*(b-128))},blendVividLight:function(a,b){return 128>b?c.Color.blendColorBurn(a,2*b):c.Color.blendColorDodge(a,2*(b-128))},blendPinLight:function(a,b){return 128>b?c.Color.blendDarken(a,2*b):c.Color.blendLighten(a,2*(b-128))},blendHardMix:function(a,b){return c.Color.blendVividLight(a,b)<128?0:255},blendReflect:function(a,b){return 255===b?b:Math.min(255,a*a/(255-b))},blendGlow:function(a,b){return c.Color.blendReflect(b,a)},blendPhoenix:function(a,b){return Math.min(a,b)-Math.max(a,b)+255}},c.LinkedList=function(){this.next=null,this.prev=null,this.first=null,this.last=null,this.total=0},c.LinkedList.prototype={add:function(a){return 0===this.total&&null===this.first&&null===this.last?(this.first=a,this.last=a,this.next=a,a.prev=this,this.total++,a):(this.last.next=a,a.prev=this.last,this.last=a,this.total++,a)},reset:function(){this.first=null,this.last=null,this.next=null,this.prev=null,this.total=0},remove:function(a){return 1===this.total?(this.reset(),void(a.next=a.prev=null)):(a===this.first?this.first=this.first.next:a===this.last&&(this.last=this.last.prev),a.prev&&(a.prev.next=a.next),a.next&&(a.next.prev=a.prev),a.next=a.prev=null,null===this.first&&(this.last=null),void this.total--)},callAll:function(a){if(this.first&&this.last){var b=this.first;do b&&b[a]&&b[a].call(b),b=b.next;while(b!=this.last.next)}}},c.LinkedList.prototype.constructor=c.LinkedList,c.Physics=function(a,b){b=b||{},this.game=a,this.config=b,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},c.Physics.ARCADE=0,c.Physics.P2JS=1,c.Physics.NINJA=2,c.Physics.BOX2D=3,c.Physics.CHIPMUNK=4,c.Physics.MATTERJS=5,c.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&this.config.arcade!==!0||!c.Physics.hasOwnProperty("Arcade")||(this.arcade=new c.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&this.config.ninja===!0&&c.Physics.hasOwnProperty("Ninja")&&(this.ninja=new c.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&this.config.p2===!0&&c.Physics.hasOwnProperty("P2")&&(this.p2=new c.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&this.config.box2d===!0&&c.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new c.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&this.config.matter===!0&&c.Physics.hasOwnProperty("Matter")&&(this.matter=new c.Physics.Matter(this.game,this.config))},startSystem:function(a){a===c.Physics.ARCADE?this.arcade=new c.Physics.Arcade(this.game):a===c.Physics.P2JS?null===this.p2?this.p2=new c.Physics.P2(this.game,this.config):this.p2.reset():a===c.Physics.NINJA?this.ninja=new c.Physics.Ninja(this.game):a===c.Physics.BOX2D?null===this.box2d?this.box2d=new c.Physics.Box2D(this.game,this.config):this.box2d.reset():a===c.Physics.MATTERJS&&(null===this.matter?this.matter=new c.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(a,b,d){void 0===b&&(b=c.Physics.ARCADE),void 0===d&&(d=!1),b===c.Physics.ARCADE?this.arcade.enable(a):b===c.Physics.P2JS&&this.p2?this.p2.enable(a,d):b===c.Physics.NINJA&&this.ninja?this.ninja.enableAABB(a):b===c.Physics.BOX2D&&this.box2d?this.box2d.enable(a):b===c.Physics.MATTERJS&&this.matter&&this.matter.enable(a)},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},c.Physics.prototype.constructor=c.Physics,c.Physics.Arcade=function(a){this.game=a,this.gravity=new c.Point,this.bounds=new c.Rectangle(0,0,a.world.width,a.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=c.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new c.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this._total=0,this.setBoundsToWorld()},c.Physics.Arcade.prototype.constructor=c.Physics.Arcade,c.Physics.Arcade.SORT_NONE=0,c.Physics.Arcade.LEFT_RIGHT=1,c.Physics.Arcade.RIGHT_LEFT=2,c.Physics.Arcade.TOP_BOTTOM=3,c.Physics.Arcade.BOTTOM_TOP=4,c.Physics.Arcade.prototype={setBounds:function(a,b,c,d){this.bounds.setTo(a,b,c,d)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(a,b){void 0===b&&(b=!0);var d=1;if(Array.isArray(a))for(d=a.length;d--;)a[d]instanceof c.Group?this.enable(a[d].children,b):(this.enableBody(a[d]),b&&a[d].hasOwnProperty("children")&&a[d].children.length>0&&this.enable(a[d],!0));else a instanceof c.Group?this.enable(a.children,b):(this.enableBody(a),b&&a.hasOwnProperty("children")&&a.children.length>0&&this.enable(a.children,!0))},enableBody:function(a){a.hasOwnProperty("body")&&null===a.body&&(a.body=new c.Physics.Arcade.Body(a),a.parent&&a.parent instanceof c.Group&&a.parent.addToHash(a))},updateMotion:function(a){var b=this.computeVelocity(0,a,a.angularVelocity,a.angularAcceleration,a.angularDrag,a.maxAngular)-a.angularVelocity;a.angularVelocity+=b,a.rotation+=a.angularVelocity*this.game.time.physicsElapsed,a.velocity.x=this.computeVelocity(1,a,a.velocity.x,a.acceleration.x,a.drag.x,a.maxVelocity.x),a.velocity.y=this.computeVelocity(2,a,a.velocity.y,a.acceleration.y,a.drag.y,a.maxVelocity.y)},computeVelocity:function(a,b,c,d,e,f){return void 0===f&&(f=1e4),1===a&&b.allowGravity?c+=(this.gravity.x+b.gravity.x)*this.game.time.physicsElapsed:2===a&&b.allowGravity&&(c+=(this.gravity.y+b.gravity.y)*this.game.time.physicsElapsed),d?c+=d*this.game.time.physicsElapsed:e&&(e*=this.game.time.physicsElapsed,c-e>0?c-=e:0>c+e?c+=e:c=0),c>f?c=f:-f>c&&(c=-f),c},overlap:function(a,b,c,d,e){if(c=c||null,d=d||null,e=e||c,this._total=0,!Array.isArray(a)&&Array.isArray(b))for(var f=0;f<b.length;f++)this.collideHandler(a,b[f],c,d,e,!0);else if(Array.isArray(a)&&!Array.isArray(b))for(var f=0;f<a.length;f++)this.collideHandler(a[f],b,c,d,e,!0);else if(Array.isArray(a)&&Array.isArray(b))for(var f=0;f<a.length;f++)for(var g=0;g<b.length;g++)this.collideHandler(a[f],b[g],c,d,e,!0);else this.collideHandler(a,b,c,d,e,!0);return this._total>0},collide:function(a,b,c,d,e){if(c=c||null,d=d||null,e=e||c,this._total=0,!Array.isArray(a)&&Array.isArray(b))for(var f=0;f<b.length;f++)this.collideHandler(a,b[f],c,d,e,!1);else if(Array.isArray(a)&&!Array.isArray(b))for(var f=0;f<a.length;f++)this.collideHandler(a[f],b,c,d,e,!1);else if(Array.isArray(a)&&Array.isArray(b))for(var f=0;f<a.length;f++)for(var g=0;g<b.length;g++)this.collideHandler(a[f],b[g],c,d,e,!1);else this.collideHandler(a,b,c,d,e,!1);return this._total>0},sortLeftRight:function(a,b){return a.body&&b.body?a.body.x-b.body.x:0},sortRightLeft:function(a,b){return a.body&&b.body?b.body.x-a.body.x:0},sortTopBottom:function(a,b){return a.body&&b.body?a.body.y-b.body.y:0},sortBottomTop:function(a,b){return a.body&&b.body?b.body.y-a.body.y:0},sort:function(a,b){null!==a.physicsSortDirection?b=a.physicsSortDirection:void 0===b&&(b=this.sortDirection),b===c.Physics.Arcade.LEFT_RIGHT?a.hash.sort(this.sortLeftRight):b===c.Physics.Arcade.RIGHT_LEFT?a.hash.sort(this.sortRightLeft):b===c.Physics.Arcade.TOP_BOTTOM?a.hash.sort(this.sortTopBottom):b===c.Physics.Arcade.BOTTOM_TOP&&a.hash.sort(this.sortBottomTop)},collideHandler:function(a,b,d,e,f,g){return void 0===b&&a.physicsType===c.GROUP?(this.sort(a),void this.collideGroupVsSelf(a,d,e,f,g)):void(a&&b&&a.exists&&b.exists&&(this.sortDirection!==c.Physics.Arcade.SORT_NONE&&(a.physicsType===c.GROUP&&this.sort(a),b.physicsType===c.GROUP&&this.sort(b)),a.physicsType===c.SPRITE?b.physicsType===c.SPRITE?this.collideSpriteVsSprite(a,b,d,e,f,g):b.physicsType===c.GROUP?this.collideSpriteVsGroup(a,b,d,e,f,g):b.physicsType===c.TILEMAPLAYER&&this.collideSpriteVsTilemapLayer(a,b,d,e,f,g):a.physicsType===c.GROUP?b.physicsType===c.SPRITE?this.collideSpriteVsGroup(b,a,d,e,f,g):b.physicsType===c.GROUP?this.collideGroupVsGroup(a,b,d,e,f,g):b.physicsType===c.TILEMAPLAYER&&this.collideGroupVsTilemapLayer(a,b,d,e,f,g):a.physicsType===c.TILEMAPLAYER&&(b.physicsType===c.SPRITE?this.collideSpriteVsTilemapLayer(b,a,d,e,f,g):b.physicsType===c.GROUP&&this.collideGroupVsTilemapLayer(b,a,d,e,f,g))))},collideSpriteVsSprite:function(a,b,c,d,e,f){return a.body&&b.body?(this.separate(a.body,b.body,d,e,f)&&(c&&c.call(e,a,b),this._total++),!0):!1},collideSpriteVsGroup:function(a,b,d,e,f,g){if(0!==b.length&&a.body){var h;if(this.skipQuadTree||a.body.skipQuadTree){for(var i=0;i<b.hash.length;i++)if(b.hash[i]&&b.hash[i].exists&&b.hash[i].body){if(h=b.hash[i].body,this.sortDirection===c.Physics.Arcade.LEFT_RIGHT){if(a.body.right<h.x)break;if(h.right<a.body.x)continue}else if(this.sortDirection===c.Physics.Arcade.RIGHT_LEFT){if(a.body.x>h.right)break;if(h.x>a.body.right)continue}else if(this.sortDirection===c.Physics.Arcade.TOP_BOTTOM){if(a.body.bottom<h.y)break;if(h.bottom<a.body.y)continue}else if(this.sortDirection===c.Physics.Arcade.BOTTOM_TOP){if(a.body.y>h.bottom)break;if(h.y>a.body.bottom)continue}this.collideSpriteVsSprite(a,b.hash[i],d,e,f,g)}}else{this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(b);for(var j=this.quadTree.retrieve(a),i=0;i<j.length;i++)this.separate(a.body,j[i],e,f,g)&&(d&&d.call(f,a,j[i].sprite),this._total++)}}},collideGroupVsSelf:function(a,b,d,e,f){if(0!==a.length)for(var g=0;g<a.hash.length;g++)if(a.hash[g]&&a.hash[g].exists&&a.hash[g].body)for(var h=a.hash[g],i=g+1;i<a.hash.length;i++)if(a.hash[i]&&a.hash[i].exists&&a.hash[i].body){var j=a.hash[i];if(this.sortDirection===c.Physics.Arcade.LEFT_RIGHT){if(h.body.right<j.body.x)break;if(j.body.right<h.body.x)continue}else if(this.sortDirection===c.Physics.Arcade.RIGHT_LEFT){if(h.body.x>j.body.right)continue;if(j.body.x>h.body.right)break}else if(this.sortDirection===c.Physics.Arcade.TOP_BOTTOM){if(h.body.bottom<j.body.y)continue;if(j.body.bottom<h.body.y)break}else if(this.sortDirection===c.Physics.Arcade.BOTTOM_TOP){if(h.body.y>j.body.bottom)continue;if(j.body.y>h.body.bottom)break}this.collideSpriteVsSprite(h,j,b,d,e,f)}},collideGroupVsGroup:function(a,b,d,e,f,g){if(0!==a.length&&0!==b.length)for(var h=0;h<a.children.length;h++)a.children[h].exists&&(a.children[h].physicsType===c.GROUP?this.collideGroupVsGroup(a.children[h],b,d,e,f,g):this.collideSpriteVsGroup(a.children[h],b,d,e,f,g))},separate:function(a,b,c,d,e){if(!a.enable||!b.enable||!this.intersects(a,b))return!1;if(c&&c.call(d,a.sprite,b.sprite)===!1)return!1;var f=!1;return f=this.forceX||Math.abs(this.gravity.y+a.gravity.y)<Math.abs(this.gravity.x+a.gravity.x)?this.separateX(a,b,e)||this.separateY(a,b,e):this.separateY(a,b,e)||this.separateX(a,b,e),e?!0:f},intersects:function(a,b){return a.right<=b.position.x?!1:a.bottom<=b.position.y?!1:a.position.x>=b.right?!1:a.position.y>=b.bottom?!1:!0},separateX:function(a,b,c){if(a.immovable&&b.immovable)return!1;var d=0;if(this.intersects(a,b)){var e=a.deltaAbsX()+b.deltaAbsX()+this.OVERLAP_BIAS;if(0===a.deltaX()&&0===b.deltaX()?(a.embedded=!0,b.embedded=!0):a.deltaX()>b.deltaX()?(d=a.right-b.x,d>e||a.checkCollision.right===!1||b.checkCollision.left===!1?d=0:(a.touching.none=!1,a.touching.right=!0,b.touching.none=!1,b.touching.left=!0)):a.deltaX()<b.deltaX()&&(d=a.x-b.width-b.x,-d>e||a.checkCollision.left===!1||b.checkCollision.right===!1?d=0:(a.touching.none=!1,a.touching.left=!0,b.touching.none=!1,b.touching.right=!0)),a.overlapX=d,b.overlapX=d,0!==d){if(c||a.customSeparateX||b.customSeparateX)return!0;var f=a.velocity.x,g=b.velocity.x;if(a.immovable||b.immovable)a.immovable?b.immovable||(b.x+=d,b.velocity.x=f-g*b.bounce.x,a.moves&&(b.y+=(a.y-a.prev.y)*a.friction.y)):(a.x=a.x-d,a.velocity.x=g-f*a.bounce.x,b.moves&&(a.y+=(b.y-b.prev.y)*b.friction.y));else{d*=.5,a.x=a.x-d,b.x+=d;var h=Math.sqrt(g*g*b.mass/a.mass)*(g>0?1:-1),i=Math.sqrt(f*f*a.mass/b.mass)*(f>0?1:-1),j=.5*(h+i);h-=j,i-=j,a.velocity.x=j+h*a.bounce.x,b.velocity.x=j+i*b.bounce.x}return!0}}return!1},separateY:function(a,b,c){if(a.immovable&&b.immovable)return!1;var d=0;if(this.intersects(a,b)){var e=a.deltaAbsY()+b.deltaAbsY()+this.OVERLAP_BIAS;if(0===a.deltaY()&&0===b.deltaY()?(a.embedded=!0,b.embedded=!0):a.deltaY()>b.deltaY()?(d=a.bottom-b.y,d>e||a.checkCollision.down===!1||b.checkCollision.up===!1?d=0:(a.touching.none=!1,a.touching.down=!0,b.touching.none=!1,b.touching.up=!0)):a.deltaY()<b.deltaY()&&(d=a.y-b.bottom,-d>e||a.checkCollision.up===!1||b.checkCollision.down===!1?d=0:(a.touching.none=!1,a.touching.up=!0,b.touching.none=!1,b.touching.down=!0)),a.overlapY=d,b.overlapY=d,0!==d){if(c||a.customSeparateY||b.customSeparateY)return!0;var f=a.velocity.y,g=b.velocity.y;if(a.immovable||b.immovable)a.immovable?b.immovable||(b.y+=d,b.velocity.y=f-g*b.bounce.y,a.moves&&(b.x+=(a.x-a.prev.x)*a.friction.x)):(a.y=a.y-d,a.velocity.y=g-f*a.bounce.y,b.moves&&(a.x+=(b.x-b.prev.x)*b.friction.x));else{d*=.5,a.y=a.y-d,b.y+=d;var h=Math.sqrt(g*g*b.mass/a.mass)*(g>0?1:-1),i=Math.sqrt(f*f*a.mass/b.mass)*(f>0?1:-1),j=.5*(h+i);h-=j,i-=j,a.velocity.y=j+h*a.bounce.y,b.velocity.y=j+i*b.bounce.y}return!0}}return!1},getObjectsUnderPointer:function(a,b,c,d){return 0!==b.length&&a.exists?this.getObjectsAtLocation(a.x,a.y,b,c,d,a):void 0},getObjectsAtLocation:function(a,b,d,e,f,g){this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(d);for(var h=new c.Rectangle(a,b,1,1),i=[],j=this.quadTree.retrieve(h),k=0;k<j.length;k++)j[k].hitTest(a,b)&&(e&&e.call(f,g,j[k].sprite),i.push(j[k].sprite));return i},moveToObject:function(a,b,c,d){void 0===c&&(c=60),void 0===d&&(d=0);var e=Math.atan2(b.y-a.y,b.x-a.x);return d>0&&(c=this.distanceBetween(a,b)/(d/1e3)),a.body.velocity.x=Math.cos(e)*c,a.body.velocity.y=Math.sin(e)*c,e},moveToPointer:function(a,b,c,d){void 0===b&&(b=60),c=c||this.game.input.activePointer,void 0===d&&(d=0);var e=this.angleToPointer(a,c);return d>0&&(b=this.distanceToPointer(a,c)/(d/1e3)),a.body.velocity.x=Math.cos(e)*b,a.body.velocity.y=Math.sin(e)*b,e},moveToXY:function(a,b,c,d,e){void 0===d&&(d=60),void 0===e&&(e=0);var f=Math.atan2(c-a.y,b-a.x);return e>0&&(d=this.distanceToXY(a,b,c)/(e/1e3)),a.body.velocity.x=Math.cos(f)*d,a.body.velocity.y=Math.sin(f)*d,f},velocityFromAngle:function(a,b,d){return void 0===b&&(b=60),d=d||new c.Point,d.setTo(Math.cos(this.game.math.degToRad(a))*b,Math.sin(this.game.math.degToRad(a))*b)},velocityFromRotation:function(a,b,d){return void 0===b&&(b=60),d=d||new c.Point,d.setTo(Math.cos(a)*b,Math.sin(a)*b)},accelerationFromRotation:function(a,b,d){return void 0===b&&(b=60),d=d||new c.Point,d.setTo(Math.cos(a)*b,Math.sin(a)*b)},accelerateToObject:function(a,b,c,d,e){void 0===c&&(c=60),void 0===d&&(d=1e3),void 0===e&&(e=1e3);var f=this.angleBetween(a,b);return a.body.acceleration.setTo(Math.cos(f)*c,Math.sin(f)*c),a.body.maxVelocity.setTo(d,e),f},accelerateToPointer:function(a,b,c,d,e){void 0===c&&(c=60),void 0===b&&(b=this.game.input.activePointer),void 0===d&&(d=1e3),void 0===e&&(e=1e3);var f=this.angleToPointer(a,b);return a.body.acceleration.setTo(Math.cos(f)*c,Math.sin(f)*c),a.body.maxVelocity.setTo(d,e),f},accelerateToXY:function(a,b,c,d,e,f){void 0===d&&(d=60),void 0===e&&(e=1e3),void 0===f&&(f=1e3);var g=this.angleToXY(a,b,c);return a.body.acceleration.setTo(Math.cos(g)*d,Math.sin(g)*d),a.body.maxVelocity.setTo(e,f),g},distanceBetween:function(a,b){var c=a.x-b.x,d=a.y-b.y;return Math.sqrt(c*c+d*d)},distanceToXY:function(a,b,c){var d=a.x-b,e=a.y-c;return Math.sqrt(d*d+e*e)},distanceToPointer:function(a,b){b=b||this.game.input.activePointer;var c=a.x-b.worldX,d=a.y-b.worldY;return Math.sqrt(c*c+d*d)},angleBetween:function(a,b){var c=b.x-a.x,d=b.y-a.y;return Math.atan2(d,c)},angleToXY:function(a,b,c){var d=b-a.x,e=c-a.y;return Math.atan2(e,d)},angleToPointer:function(a,b){b=b||this.game.input.activePointer;var c=b.worldX-a.x,d=b.worldY-a.y;return Math.atan2(d,c)}},c.Physics.Arcade.Body=function(a){this.sprite=a,this.game=a.game,this.type=c.Physics.ARCADE,this.enable=!0,this.offset=new c.Point,this.position=new c.Point(a.x,a.y),this.prev=new c.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=a.rotation,this.preRotation=a.rotation,this.width=a.width,this.height=a.height,this.sourceWidth=a.width,this.sourceHeight=a.height,a.texture&&(this.sourceWidth=a.texture.frame.width,this.sourceHeight=a.texture.frame.height),this.halfWidth=Math.abs(a.width/2),this.halfHeight=Math.abs(a.height/2),this.center=new c.Point(a.x+this.halfWidth,a.y+this.halfHeight),this.velocity=new c.Point,this.newVelocity=new c.Point(0,0),this.deltaMax=new c.Point(0,0),this.acceleration=new c.Point,this.drag=new c.Point,this.allowGravity=!0,this.gravity=new c.Point(0,0),this.bounce=new c.Point,this.maxVelocity=new c.Point(1e4,1e4),this.friction=new c.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=c.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,any:!0,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={up:!1,down:!1,left:!1,right:!1},this.tilePadding=new c.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this._reset=!0,this._sx=a.scale.x,this._sy=a.scale.y,this._dx=0,this._dy=0},c.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var a=this.sprite.getBounds();a.ceilAll(),(a.width!==this.width||a.height!==this.height)&&(this.width=a.width,this.height=a.height,this._reset=!0)}else{var b=Math.abs(this.sprite.scale.x),c=Math.abs(this.sprite.scale.y);(b!==this._sx||c!==this._sy)&&(this.width=this.sourceWidth*b,this.height=this.sourceHeight*c,this._sx=b,this._sy=c,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight))},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,this.wasTouching.none=this.touching.none,this.wasTouching.up=this.touching.up,this.wasTouching.down=this.touching.down,this.wasTouching.left=this.touching.left,this.wasTouching.right=this.touching.right,this.touching.none=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.width+this.offset.x,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.height+this.offset.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),this.moves&&(this.game.physics.arcade.updateMotion(this),this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed),this.position.x+=this.newVelocity.x,this.position.y+=this.newVelocity.y,(this.position.x!==this.prev.x||this.position.y!==this.prev.y)&&(this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.angle=Math.atan2(this.velocity.y,this.velocity.x)),this.collideWorldBounds&&this.checkWorldBounds()),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},postUpdate:function(){this.enable&&this.dirty&&(this.dirty=!1,this.deltaX()<0?this.facing=c.LEFT:this.deltaX()>0&&(this.facing=c.RIGHT),this.deltaY()<0?this.facing=c.UP:this.deltaY()>0&&(this.facing=c.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof c.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null},checkWorldBounds:function(){var a=this.position,b=this.game.physics.arcade.bounds,c=this.game.physics.arcade.checkCollision;a.x<b.x&&c.left?(a.x=b.x,this.velocity.x*=-this.bounce.x,this.blocked.left=!0):this.right>b.right&&c.right&&(a.x=b.right-this.width,this.velocity.x*=-this.bounce.x,this.blocked.right=!0),a.y<b.y&&c.up?(a.y=b.y,this.velocity.y*=-this.bounce.y,this.blocked.up=!0):this.bottom>b.bottom&&c.down&&(a.y=b.bottom-this.height,this.velocity.y*=-this.bounce.y,this.blocked.down=!0)},setSize:function(a,b,c,d){void 0===c&&(c=this.offset.x),void 0===d&&(d=this.offset.y),this.sourceWidth=a,this.sourceHeight=b,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(c,d),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(a,b){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this.position.x=a-this.sprite.anchor.x*this.width+this.offset.x,this.position.y=b-this.sprite.anchor.y*this.height+this.offset.y,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this._sx=this.sprite.scale.x,this._sy=this.sprite.scale.y,this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},hitTest:function(a,b){return c.Rectangle.contains(this,a,b)},onFloor:function(){return this.blocked.down},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation}},Object.defineProperty(c.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(c.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(c.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(a){this.position.x=a}}),Object.defineProperty(c.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(a){this.position.y=a}}),c.Physics.Arcade.Body.render=function(a,b,c,d){void 0===d&&(d=!0),c=c||"rgba(0,255,0,0.4)",d?(a.fillStyle=c,a.fillRect(b.position.x-b.game.camera.x,b.position.y-b.game.camera.y,b.width,b.height)):(a.strokeStyle=c,a.strokeRect(b.position.x-b.game.camera.x,b.position.y-b.game.camera.y,b.width,b.height))},c.Physics.Arcade.Body.renderBodyInfo=function(a,b){a.line("x: "+b.x.toFixed(2),"y: "+b.y.toFixed(2),"width: "+b.width,"height: "+b.height),a.line("velocity x: "+b.velocity.x.toFixed(2),"y: "+b.velocity.y.toFixed(2),"deltaX: "+b._dx.toFixed(2),"deltaY: "+b._dy.toFixed(2)),a.line("acceleration x: "+b.acceleration.x.toFixed(2),"y: "+b.acceleration.y.toFixed(2),"speed: "+b.speed.toFixed(2),"angle: "+b.angle.toFixed(2)),a.line("gravity x: "+b.gravity.x,"y: "+b.gravity.y,"bounce x: "+b.bounce.x.toFixed(2),"y: "+b.bounce.y.toFixed(2)),a.line("touching left: "+b.touching.left,"right: "+b.touching.right,"up: "+b.touching.up,"down: "+b.touching.down),a.line("blocked left: "+b.blocked.left,"right: "+b.blocked.right,"up: "+b.blocked.up,"down: "+b.blocked.down)},c.Physics.Arcade.Body.prototype.constructor=c.Physics.Arcade.Body,c.Physics.Arcade.TilemapCollision=function(){},c.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(a,b,c,d,e,f){if(a.body){var g=b.getTiles(a.body.position.x-a.body.tilePadding.x,a.body.position.y-a.body.tilePadding.y,a.body.width+a.body.tilePadding.x,a.body.height+a.body.tilePadding.y,!1,!1);if(0!==g.length)for(var h=0;h<g.length;h++)d?d.call(e,a,g[h])&&this.separateTile(h,a.body,g[h],f)&&(this._total++,c&&c.call(e,a,g[h])):this.separateTile(h,a.body,g[h],f)&&(this._total++,c&&c.call(e,a,g[h]))}},collideGroupVsTilemapLayer:function(a,b,c,d,e,f){if(0!==a.length)for(var g=0;g<a.children.length;g++)a.children[g].exists&&this.collideSpriteVsTilemapLayer(a.children[g],b,c,d,e,f)},separateTile:function(a,b,c,d){if(!b.enable)return!1;if(!c.intersects(b.position.x,b.position.y,b.right,b.bottom))return!1;if(d)return!0;if(c.collisionCallback&&!c.collisionCallback.call(c.collisionCallbackContext,b.sprite,c))return!1;if(c.layer.callbacks[c.index]&&!c.layer.callbacks[c.index].callback.call(c.layer.callbacks[c.index].callbackContext,b.sprite,c))return!1;if(!(c.faceLeft||c.faceRight||c.faceTop||c.faceBottom))return!1;var e=0,f=0,g=0,h=1;if(b.deltaAbsX()>b.deltaAbsY()?g=-1:b.deltaAbsX()<b.deltaAbsY()&&(h=-1),0!==b.deltaX()&&0!==b.deltaY()&&(c.faceLeft||c.faceRight)&&(c.faceTop||c.faceBottom)&&(g=Math.min(Math.abs(b.position.x-c.right),Math.abs(b.right-c.left)),h=Math.min(Math.abs(b.position.y-c.bottom),Math.abs(b.bottom-c.top))),h>g){if((c.faceLeft||c.faceRight)&&(e=this.tileCheckX(b,c),0!==e&&!c.intersects(b.position.x,b.position.y,b.right,b.bottom)))return!0;(c.faceTop||c.faceBottom)&&(f=this.tileCheckY(b,c))}else{if((c.faceTop||c.faceBottom)&&(f=this.tileCheckY(b,c),0!==f&&!c.intersects(b.position.x,b.position.y,b.right,b.bottom)))return!0;(c.faceLeft||c.faceRight)&&(e=this.tileCheckX(b,c))}return 0!==e||0!==f},tileCheckX:function(a,b){var c=0;return a.deltaX()<0&&!a.blocked.left&&b.collideRight&&a.checkCollision.left?b.faceRight&&a.x<b.right&&(c=a.x-b.right,c<-this.TILE_BIAS&&(c=0)):a.deltaX()>0&&!a.blocked.right&&b.collideLeft&&a.checkCollision.right&&b.faceLeft&&a.right>b.left&&(c=a.right-b.left,c>this.TILE_BIAS&&(c=0)),0!==c&&(a.customSeparateX?a.overlapX=c:this.processTileSeparationX(a,c)),c},tileCheckY:function(a,b){var c=0;return a.deltaY()<0&&!a.blocked.up&&b.collideDown&&a.checkCollision.up?b.faceBottom&&a.y<b.bottom&&(c=a.y-b.bottom,c<-this.TILE_BIAS&&(c=0)):a.deltaY()>0&&!a.blocked.down&&b.collideUp&&a.checkCollision.down&&b.faceTop&&a.bottom>b.top&&(c=a.bottom-b.top,c>this.TILE_BIAS&&(c=0)),0!==c&&(a.customSeparateY?a.overlapY=c:this.processTileSeparationY(a,c)),c},processTileSeparationX:function(a,b){0>b?a.blocked.left=!0:b>0&&(a.blocked.right=!0),a.position.x-=b,a.velocity.x=0===a.bounce.x?0:-a.velocity.x*a.bounce.x},processTileSeparationY:function(a,b){0>b?a.blocked.up=!0:b>0&&(a.blocked.down=!0),a.position.y-=b,a.velocity.y=0===a.bounce.y?0:-a.velocity.y*a.bounce.y}},c.Utils.mixinPrototype(c.Physics.Arcade.prototype,c.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,c.Physics.P2=function(a,b){this.game=a,void 0===b?b={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(b.hasOwnProperty("gravity")||(b.gravity=[0,0]),b.hasOwnProperty("broadphase")||(b.broadphase=new p2.SAPBroadphase)),this.config=b,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new c.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new c.Signal,this.onBodyRemoved=new c.Signal,this.onSpringAdded=new c.Signal,this.onSpringRemoved=new c.Signal,this.onConstraintAdded=new c.Signal,this.onConstraintRemoved=new c.Signal,this.onContactMaterialAdded=new c.Signal,this.onContactMaterialRemoved=new c.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new c.Signal,this.onEndContact=new c.Signal,b.hasOwnProperty("mpx")&&b.hasOwnProperty("pxm")&&b.hasOwnProperty("mpxi")&&b.hasOwnProperty("pxmi")&&(this.mpx=b.mpx,this.mpxi=b.mpxi,this.pxm=b.pxm,this.pxmi=b.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new c.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new c.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new c.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)
+},c.Physics.P2.prototype={removeBodyNextStep:function(a){this._toRemove.push(a)},preUpdate:function(){for(var a=this._toRemove.length;a--;)this.removeBody(this._toRemove[a]);this._toRemove.length=0},enable:function(a,b,d){void 0===b&&(b=!1),void 0===d&&(d=!0);var e=1;if(Array.isArray(a))for(e=a.length;e--;)a[e]instanceof c.Group?this.enable(a[e].children,b,d):(this.enableBody(a[e],b),d&&a[e].hasOwnProperty("children")&&a[e].children.length>0&&this.enable(a[e],b,!0));else a instanceof c.Group?this.enable(a.children,b,d):(this.enableBody(a,b),d&&a.hasOwnProperty("children")&&a.children.length>0&&this.enable(a.children,b,!0))},enableBody:function(a,b){a.hasOwnProperty("body")&&null===a.body&&(a.body=new c.Physics.P2.Body(this.game,a,a.x,a.y,1),a.body.debug=b,"undefined"!=typeof a.anchor&&a.anchor.set(.5))},setImpactEvents:function(a){a?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(a,b){this.postBroadphaseCallback=a,this.callbackContext=b,null!==a?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(a){if(this.postBroadphaseCallback&&0!==a.pairs.length)for(var b=a.pairs.length-2;b>=0;b-=2)a.pairs[b].parent&&a.pairs[b+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,a.pairs[b].parent,a.pairs[b+1].parent)&&a.pairs.splice(b,2)},impactHandler:function(a){if(a.bodyA.parent&&a.bodyB.parent){var b=a.bodyA.parent,c=a.bodyB.parent;b._bodyCallbacks[a.bodyB.id]&&b._bodyCallbacks[a.bodyB.id].call(b._bodyCallbackContext[a.bodyB.id],b,c,a.shapeA,a.shapeB),c._bodyCallbacks[a.bodyA.id]&&c._bodyCallbacks[a.bodyA.id].call(c._bodyCallbackContext[a.bodyA.id],c,b,a.shapeB,a.shapeA),b._groupCallbacks[a.shapeB.collisionGroup]&&b._groupCallbacks[a.shapeB.collisionGroup].call(b._groupCallbackContext[a.shapeB.collisionGroup],b,c,a.shapeA,a.shapeB),c._groupCallbacks[a.shapeA.collisionGroup]&&c._groupCallbacks[a.shapeA.collisionGroup].call(c._groupCallbackContext[a.shapeA.collisionGroup],c,b,a.shapeB,a.shapeA)}},beginContactHandler:function(a){a.bodyA&&a.bodyB&&(this.onBeginContact.dispatch(a.bodyA,a.bodyB,a.shapeA,a.shapeB,a.contactEquations),a.bodyA.parent&&a.bodyA.parent.onBeginContact.dispatch(a.bodyB.parent,a.bodyB,a.shapeA,a.shapeB,a.contactEquations),a.bodyB.parent&&a.bodyB.parent.onBeginContact.dispatch(a.bodyA.parent,a.bodyA,a.shapeB,a.shapeA,a.contactEquations))},endContactHandler:function(a){a.bodyA&&a.bodyB&&(this.onEndContact.dispatch(a.bodyA,a.bodyB,a.shapeA,a.shapeB),a.bodyA.parent&&a.bodyA.parent.onEndContact.dispatch(a.bodyB.parent,a.bodyB,a.shapeA,a.shapeB),a.bodyB.parent&&a.bodyB.parent.onEndContact.dispatch(a.bodyA.parent,a.bodyA,a.shapeB,a.shapeA))},setBoundsToWorld:function(a,b,c,d,e){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,a,b,c,d,e)},setWorldMaterial:function(a,b,c,d,e){void 0===b&&(b=!0),void 0===c&&(c=!0),void 0===d&&(d=!0),void 0===e&&(e=!0),b&&this.walls.left&&(this.walls.left.shapes[0].material=a),c&&this.walls.right&&(this.walls.right.shapes[0].material=a),d&&this.walls.top&&(this.walls.top.shapes[0].material=a),e&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=a)},updateBoundsCollisionGroup:function(a){var b=this.everythingCollisionGroup.mask;void 0===a&&(b=this.boundsCollisionGroup.mask),this.walls.left&&(this.walls.left.shapes[0].collisionGroup=b),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=b),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=b),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=b)},setBounds:function(a,b,c,d,e,f,g,h,i){void 0===e&&(e=this._boundsLeft),void 0===f&&(f=this._boundsRight),void 0===g&&(g=this._boundsTop),void 0===h&&(h=this._boundsBottom),void 0===i&&(i=this._boundsOwnGroup),this.walls.left&&this.world.removeBody(this.walls.left),this.walls.right&&this.world.removeBody(this.walls.right),this.walls.top&&this.world.removeBody(this.walls.top),this.walls.bottom&&this.world.removeBody(this.walls.bottom),e&&(this.walls.left=new p2.Body({mass:0,position:[this.pxmi(a),this.pxmi(b)],angle:1.5707963267948966}),this.walls.left.addShape(new p2.Plane),i&&(this.walls.left.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.left)),f&&(this.walls.right=new p2.Body({mass:0,position:[this.pxmi(a+c),this.pxmi(b)],angle:-1.5707963267948966}),this.walls.right.addShape(new p2.Plane),i&&(this.walls.right.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.right)),g&&(this.walls.top=new p2.Body({mass:0,position:[this.pxmi(a),this.pxmi(b)],angle:-3.141592653589793}),this.walls.top.addShape(new p2.Plane),i&&(this.walls.top.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.top)),h&&(this.walls.bottom=new p2.Body({mass:0,position:[this.pxmi(a),this.pxmi(b+d)]}),this.walls.bottom.addShape(new p2.Plane),i&&(this.walls.bottom.shapes[0].collisionGroup=this.boundsCollisionGroup.mask),this.world.addBody(this.walls.bottom)),this._boundsLeft=e,this._boundsRight=f,this._boundsTop=g,this._boundsBottom=h,this._boundsOwnGroup=i},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||this.world.step(this.useElapsedTime?this.game.time.physicsElapsed:this.frameRate)},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new c.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new c.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new c.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var a=this.world.constraints,b=a.length-1;b>=0;b--)this.world.removeConstraint(a[b]);for(var c=this.world.bodies,b=c.length-1;b>=0;b--)this.world.removeBody(c[b]);for(var d=this.world.springs,b=d.length-1;b>=0;b--)this.world.removeSpring(d[b]);for(var e=this.world.contactMaterials,b=e.length-1;b>=0;b--)this.world.removeContactMaterial(e[b]);this.world.off("beginContact",this.beginContactHandler,this),this.world.off("endContact",this.endContactHandler,this),this.postBroadphaseCallback=null,this.callbackContext=null,this.impactCallback=null,this.collisionGroups=[],this._toRemove=[],this.boundsCollidesWith=[]},destroy:function(){this.clear(),this.game=null},addBody:function(a){return a.data.world?!1:(this.world.addBody(a.data),this.onBodyAdded.dispatch(a),!0)},removeBody:function(a){return a.data.world==this.world&&(this.world.removeBody(a.data),this.onBodyRemoved.dispatch(a)),a},addSpring:function(a){return this.world.addSpring(a instanceof c.Physics.P2.Spring||a instanceof c.Physics.P2.RotationalSpring?a.data:a),this.onSpringAdded.dispatch(a),a},removeSpring:function(a){return this.world.removeSpring(a instanceof c.Physics.P2.Spring||a instanceof c.Physics.P2.RotationalSpring?a.data:a),this.onSpringRemoved.dispatch(a),a},createDistanceConstraint:function(a,b,d,e,f,g){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.DistanceConstraint(this,a,b,d,e,f,g)):void console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(a,b,d,e){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.GearConstraint(this,a,b,d,e)):void console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(a,b,d,e,f,g){return a=this.getBody(a),d=this.getBody(d),a&&d?this.addConstraint(new c.Physics.P2.RevoluteConstraint(this,a,b,d,e,f,g)):void console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(a,b,d,e,f){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.LockConstraint(this,a,b,d,e,f)):void console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(a,b,d,e,f,g,h){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addConstraint(new c.Physics.P2.PrismaticConstraint(this,a,b,d,e,f,g,h)):void console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(a){return this.world.addConstraint(a),this.onConstraintAdded.dispatch(a),a},removeConstraint:function(a){return this.world.removeConstraint(a),this.onConstraintRemoved.dispatch(a),a},addContactMaterial:function(a){return this.world.addContactMaterial(a),this.onContactMaterialAdded.dispatch(a),a},removeContactMaterial:function(a){return this.world.removeContactMaterial(a),this.onContactMaterialRemoved.dispatch(a),a},getContactMaterial:function(a,b){return this.world.getContactMaterial(a,b)},setMaterial:function(a,b){for(var c=b.length;c--;)b[c].setMaterial(a)},createMaterial:function(a,b){a=a||"";var d=new c.Physics.P2.Material(a);return this.materials.push(d),"undefined"!=typeof b&&b.setMaterial(d),d},createContactMaterial:function(a,b,d){void 0===a&&(a=this.createMaterial()),void 0===b&&(b=this.createMaterial());var e=new c.Physics.P2.ContactMaterial(a,b,d);return this.addContactMaterial(e)},getBodies:function(){for(var a=[],b=this.world.bodies.length;b--;)a.push(this.world.bodies[b].parent);return a},getBody:function(a){return a instanceof p2.Body?a:a instanceof c.Physics.P2.Body?a.data:a.body&&a.body.type===c.Physics.P2JS?a.body.data:null},getSprings:function(){for(var a=[],b=this.world.springs.length;b--;)a.push(this.world.springs[b].parent);return a},getConstraints:function(){for(var a=[],b=this.world.constraints.length;b--;)a.push(this.world.constraints[b]);return a},hitTest:function(a,b,d,e){void 0===b&&(b=this.world.bodies),void 0===d&&(d=5),void 0===e&&(e=!1);for(var f=[this.pxmi(a.x),this.pxmi(a.y)],g=[],h=b.length;h--;)b[h]instanceof c.Physics.P2.Body&&(!e||b[h].data.type!==p2.Body.STATIC)?g.push(b[h].data):b[h]instanceof p2.Body&&b[h].parent&&(!e||b[h].type!==p2.Body.STATIC)?g.push(b[h]):b[h]instanceof c.Sprite&&b[h].hasOwnProperty("body")&&(!e||b[h].body.data.type!==p2.Body.STATIC)&&g.push(b[h].body.data);return this.world.hitTest(f,g,d)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(a){var b=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|b),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|b),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|b),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|b),this._collisionGroupID++;var d=new c.Physics.P2.CollisionGroup(b);return this.collisionGroups.push(d),a&&this.setCollisionGroup(a,d),d},setCollisionGroup:function(a,b){if(a instanceof c.Group)for(var d=0;d<a.total;d++)a.children[d].body&&a.children[d].body.type===c.Physics.P2JS&&a.children[d].body.setCollisionGroup(b);else a.body.setCollisionGroup(b)},createSpring:function(a,b,d,e,f,g,h,i,j){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addSpring(new c.Physics.P2.Spring(this,a,b,d,e,f,g,h,i,j)):void console.warn("Cannot create Spring, invalid body objects given")},createRotationalSpring:function(a,b,d,e,f){return a=this.getBody(a),b=this.getBody(b),a&&b?this.addSpring(new c.Physics.P2.RotationalSpring(this,a,b,d,e,f)):void console.warn("Cannot create Rotational Spring, invalid body objects given")},createBody:function(a,b,d,e,f,g){void 0===e&&(e=!1);var h=new c.Physics.P2.Body(this.game,null,a,b,d);if(g){var i=h.addPolygon(f,g);if(!i)return!1}return e&&this.world.addBody(h.data),h},createParticle:function(a,b,d,e,f,g){void 0===e&&(e=!1);var h=new c.Physics.P2.Body(this.game,null,a,b,d);if(g){var i=h.addPolygon(f,g);if(!i)return!1}return e&&this.world.addBody(h.data),h},convertCollisionObjects:function(a,b,c){void 0===c&&(c=!0);for(var d=[],e=0,f=a.collision[b].length;f>e;e++){var g=a.collision[b][e],h=this.createBody(g.x,g.y,0,c,{},g.polyline);h&&d.push(h)}return d},clearTilemapLayerBodies:function(a,b){b=a.getLayer(b);for(var c=a.layers[b].bodies.length;c--;)a.layers[b].bodies[c].destroy();a.layers[b].bodies.length=0},convertTilemap:function(a,b,c,d){b=a.getLayer(b),void 0===c&&(c=!0),void 0===d&&(d=!0),this.clearTilemapLayerBodies(a,b);for(var e=0,f=0,g=0,h=0,i=a.layers[b].height;i>h;h++){e=0;for(var j=0,k=a.layers[b].width;k>j;j++){var l=a.layers[b].data[h][j];if(l&&l.index>-1&&l.collides)if(d){var m=a.getTileRight(b,j,h);if(0===e&&(f=l.x*l.width,g=l.y*l.height,e=l.width),m&&m.collides)e+=l.width;else{var n=this.createBody(f,g,0,!1);n.addRectangle(e,l.height,e/2,l.height/2,0),c&&this.addBody(n),a.layers[b].bodies.push(n),e=0}}else{var n=this.createBody(l.x*l.width,l.y*l.height,0,!1);n.addRectangle(l.width,l.height,l.width/2,l.height/2,0),c&&this.addBody(n),a.layers[b].bodies.push(n)}}}return a.layers[b].bodies},mpx:function(a){return a*=20},pxm:function(a){return.05*a},mpxi:function(a){return a*=-20},pxmi:function(a){return a*-.05}},Object.defineProperty(c.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(a){this.world.defaultContactMaterial.friction=a}}),Object.defineProperty(c.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(a){this.world.defaultContactMaterial.restitution=a}}),Object.defineProperty(c.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(a){this.world.defaultContactMaterial=a}}),Object.defineProperty(c.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(a){this.world.applySpringForces=a}}),Object.defineProperty(c.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(a){this.world.applyDamping=a}}),Object.defineProperty(c.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(a){this.world.applyGravity=a}}),Object.defineProperty(c.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(a){this.world.solveConstraints=a}}),Object.defineProperty(c.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(c.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(a){this.world.emitImpactEvent=a}}),Object.defineProperty(c.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(a){this.world.sleepMode=a}}),Object.defineProperty(c.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),c.Physics.P2.FixtureList=function(a){Array.isArray(a)||(a=[a]),this.rawList=a,this.init(),this.parse(this.rawList)},c.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(a,b){var c=function(b){b.collisionGroup=a};this.getFixtures(b).forEach(c)},setMask:function(a,b){var c=function(b){b.collisionMask=a};this.getFixtures(b).forEach(c)},setSensor:function(a,b){var c=function(b){b.sensor=a};this.getFixtures(b).forEach(c)},setMaterial:function(a,b){var c=function(b){b.material=a};this.getFixtures(b).forEach(c)},getFixtures:function(a){var b=[];if(a){a instanceof Array||(a=[a]);var c=this;return a.forEach(function(a){c.namedFixtures[a]&&b.push(c.namedFixtures[a])}),this.flatten(b)}return this.allFixtures},getFixtureByKey:function(a){return this.namedFixtures[a]},getGroup:function(a){return this.groupedFixtures[a]},parse:function(){var a,b,c,d;c=this.rawList,d=[];for(a in c)b=c[a],isNaN(a-0)?this.namedFixtures[a]=this.flatten(b):(this.groupedFixtures[a]=this.groupedFixtures[a]||[],this.groupedFixtures[a]=this.groupedFixtures[a].concat(b)),d.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(a){var b,c;return b=[],c=arguments.callee,a.forEach(function(a){return Array.prototype.push.apply(b,Array.isArray(a)?c(a):[a])}),b}},c.Physics.P2.PointProxy=function(a,b){this.world=a,this.destination=b},c.Physics.P2.PointProxy.prototype.constructor=c.Physics.P2.PointProxy,Object.defineProperty(c.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(a){this.destination[0]=this.world.pxm(a)}}),Object.defineProperty(c.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(a){this.destination[1]=this.world.pxm(a)}}),Object.defineProperty(c.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(a){this.destination[0]=a}}),Object.defineProperty(c.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(a){this.destination[1]=a}}),c.Physics.P2.InversePointProxy=function(a,b){this.world=a,this.destination=b},c.Physics.P2.InversePointProxy.prototype.constructor=c.Physics.P2.InversePointProxy,Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(a){this.destination[0]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(a){this.destination[1]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(a){this.destination[0]=-a}}),Object.defineProperty(c.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(a){this.destination[1]=-a}}),c.Physics.P2.Body=function(a,b,d,e,f){b=b||null,d=d||0,e=e||0,void 0===f&&(f=1),this.game=a,this.world=a.physics.p2,this.sprite=b,this.type=c.Physics.P2JS,this.offset=new c.Point,this.data=new p2.Body({position:[this.world.pxmi(d),this.world.pxmi(e)],mass:f}),this.data.parent=this,this.velocity=new c.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new c.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new c.Point,this.onBeginContact=new c.Signal,this.onEndContact=new c.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,b&&(this.setRectangleFromSprite(b),b.exists&&this.game.physics.p2.addBody(this))},c.Physics.P2.Body.prototype={createBodyCallback:function(a,b,c){var d=-1;a.id?d=a.id:a.body&&(d=a.body.id),d>-1&&(null===b?(delete this._bodyCallbacks[d],delete this._bodyCallbackContext[d]):(this._bodyCallbacks[d]=b,this._bodyCallbackContext[d]=c))},createGroupCallback:function(a,b,c){null===b?(delete this._groupCallbacks[a.mask],delete this._groupCallbackContext[a.mask]):(this._groupCallbacks[a.mask]=b,this._groupCallbackContext[a.mask]=c)},getCollisionMask:function(){var a=0;this._collideWorldBounds&&(a=this.game.physics.p2.boundsCollisionGroup.mask);for(var b=0;b<this.collidesWith.length;b++)a|=this.collidesWith[b].mask;return a},updateCollisionMask:function(a){var b=this.getCollisionMask();if(void 0===a)for(var c=this.data.shapes.length-1;c>=0;c--)this.data.shapes[c].collisionMask=b;else a.collisionMask=b},setCollisionGroup:function(a,b){var c=this.getCollisionMask();if(void 0===b)for(var d=this.data.shapes.length-1;d>=0;d--)this.data.shapes[d].collisionGroup=a.mask,this.data.shapes[d].collisionMask=c;else b.collisionGroup=a.mask,b.collisionMask=c},clearCollision:function(a,b,c){if(void 0===a&&(a=!0),void 0===b&&(b=!0),void 0===c)for(var d=this.data.shapes.length-1;d>=0;d--)a&&(this.data.shapes[d].collisionGroup=null),b&&(this.data.shapes[d].collisionMask=null);else a&&(c.collisionGroup=null),b&&(c.collisionMask=null);a&&(this.collidesWith.length=0)},collides:function(a,b,c,d){if(Array.isArray(a))for(var e=0;e<a.length;e++)-1===this.collidesWith.indexOf(a[e])&&(this.collidesWith.push(a[e]),b&&this.createGroupCallback(a[e],b,c));else-1===this.collidesWith.indexOf(a)&&(this.collidesWith.push(a),b&&this.createGroupCallback(a,b,c));var f=this.getCollisionMask();if(void 0===d)for(var e=this.data.shapes.length-1;e>=0;e--)this.data.shapes[e].collisionMask=f;else d.collisionMask=f},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(a,b){return this.data.getVelocityAtPoint(a,b)},applyDamping:function(a){this.data.applyDamping(a)},applyImpulse:function(a,b,c){this.data.applyImpulse(a,[this.world.pxmi(b),this.world.pxmi(c)])},applyImpulseLocal:function(a,b,c){this.data.applyImpulseLocal(a,[this.world.pxmi(b),this.world.pxmi(c)])},applyForce:function(a,b,c){this.data.applyForce(a,[this.world.pxmi(b),this.world.pxmi(c)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0,this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0,this.data.angularDamping=0},toLocalFrame:function(a,b){return this.data.toLocalFrame(a,b)},toWorldFrame:function(a,b){return this.data.toWorldFrame(a,b)},rotateLeft:function(a){this.data.angularVelocity=this.world.pxm(-a)},rotateRight:function(a){this.data.angularVelocity=this.world.pxm(a)},moveForward:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.velocity[0]=b*Math.cos(c),this.data.velocity[1]=b*Math.sin(c)},moveBackward:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.velocity[0]=-(b*Math.cos(c)),this.data.velocity[1]=-(b*Math.sin(c))},thrust:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.force[0]+=b*Math.cos(c),this.data.force[1]+=b*Math.sin(c)},reverse:function(a){var b=this.world.pxmi(-a),c=this.data.angle+Math.PI/2;this.data.force[0]-=b*Math.cos(c),this.data.force[1]-=b*Math.sin(c)},moveLeft:function(a){this.data.velocity[0]=this.world.pxmi(-a)},moveRight:function(a){this.data.velocity[0]=this.world.pxmi(a)},moveUp:function(a){this.data.velocity[1]=this.world.pxmi(-a)},moveDown:function(a){this.data.velocity[1]=this.world.pxmi(a)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0]),this.sprite.y=this.world.mpxi(this.data.position[1]),this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(a,b,c,d){void 0===c&&(c=!1),void 0===d&&(d=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),c&&this.setZeroDamping(),d&&(this.mass=1),this.x=a,this.y=b},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var a=0;a<this.game.physics.p2._toRemove.length;a++)this.game.physics.p2._toRemove[a]===this&&this.game.physics.p2._toRemove.splice(a,1);this.data.world!==this.game.physics.p2.world&&this.game.physics.p2.addBody(this)},removeFromWorld:function(){this.data.world===this.game.physics.p2.world&&this.game.physics.p2.removeBodyNextStep(this)},destroy:function(){this.removeFromWorld(),this.clearShapes(),this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this.debugBody&&this.debugBody.destroy(!0,!0),this.debugBody=null,this.sprite&&(this.sprite.body=null,this.sprite=null)},clearShapes:function(){for(var a=this.data.shapes.length;a--;)this.data.removeShape(this.data.shapes[a]);this.shapeChanged()},addShape:function(a,b,c,d){return void 0===b&&(b=0),void 0===c&&(c=0),void 0===d&&(d=0),this.data.addShape(a,[this.world.pxmi(b),this.world.pxmi(c)],d),this.shapeChanged(),a},addCircle:function(a,b,c,d){var e=new p2.Circle({radius:this.world.pxm(a)});return this.addShape(e,b,c,d)},addRectangle:function(a,b,c,d,e){var f=new p2.Box({width:this.world.pxm(a),height:this.world.pxm(b)});return this.addShape(f,c,d,e)},addPlane:function(a,b,c){var d=new p2.Plane;return this.addShape(d,a,b,c)},addParticle:function(a,b,c){var d=new p2.Particle;return this.addShape(d,a,b,c)},addLine:function(a,b,c,d){var e=new p2.Line({length:this.world.pxm(a)});return this.addShape(e,b,c,d)},addCapsule:function(a,b,c,d,e){var f=new p2.Capsule({length:this.world.pxm(a),radius:this.world.pxm(b)});return this.addShape(f,c,d,e)},addPolygon:function(a,b){a=a||{},Array.isArray(b)||(b=Array.prototype.slice.call(arguments,1));var c=[];if(1===b.length&&Array.isArray(b[0]))c=b[0].slice(0);else if(Array.isArray(b[0]))c=b.slice();else if("number"==typeof b[0])for(var d=0,e=b.length;e>d;d+=2)c.push([b[d],b[d+1]]);var f=c.length-1;c[f][0]===c[0][0]&&c[f][1]===c[0][1]&&c.pop();for(var g=0;g<c.length;g++)c[g][0]=this.world.pxmi(c[g][0]),c[g][1]=this.world.pxmi(c[g][1]);var h=this.data.fromPolygon(c,a);return this.shapeChanged(),h},removeShape:function(a){var b=this.data.removeShape(a);return this.shapeChanged(),b},setCircle:function(a,b,c,d){return this.clearShapes(),this.addCircle(a,b,c,d)},setRectangle:function(a,b,c,d,e){return void 0===a&&(a=16),void 0===b&&(b=16),this.clearShapes(),this.addRectangle(a,b,c,d,e)},setRectangleFromSprite:function(a){return void 0===a&&(a=this.sprite),this.clearShapes(),this.addRectangle(a.width,a.height,0,0,a.rotation)},setMaterial:function(a,b){if(void 0===b)for(var c=this.data.shapes.length-1;c>=0;c--)this.data.shapes[c].material=a;else b.material=a},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(a,b){for(var c=this.game.cache.getPhysicsData(a,b),d=[],e=0;e<c.length;e++){var f=c[e],g=this.addFixture(f);d[f.filter.group]=d[f.filter.group]||[],d[f.filter.group]=d[f.filter.group].concat(g),f.fixtureKey&&(d[f.fixtureKey]=g)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),d},addFixture:function(a){var b=[];if(a.circle){var c=new p2.Circle({radius:this.world.pxm(a.circle.radius)});c.collisionGroup=a.filter.categoryBits,c.collisionMask=a.filter.maskBits,c.sensor=a.isSensor;var d=p2.vec2.create();d[0]=this.world.pxmi(a.circle.position[0]-this.sprite.width/2),d[1]=this.world.pxmi(a.circle.position[1]-this.sprite.height/2),this.data.addShape(c,d),b.push(c)}else for(var e=a.polygons,f=p2.vec2.create(),g=0;g<e.length;g++){for(var h=e[g],i=[],j=0;j<h.length;j+=2)i.push([this.world.pxmi(h[j]),this.world.pxmi(h[j+1])]);for(var c=new p2.Convex({vertices:i}),k=0;k!==c.vertices.length;k++){var l=c.vertices[k];p2.vec2.sub(l,l,c.centerOfMass)}p2.vec2.scale(f,c.centerOfMass,1),f[0]-=this.world.pxmi(this.sprite.width/2),f[1]-=this.world.pxmi(this.sprite.height/2),c.updateTriangles(),c.updateCenterOfMass(),c.updateBoundingRadius(),c.collisionGroup=a.filter.categoryBits,c.collisionMask=a.filter.maskBits,c.sensor=a.isSensor,this.data.addShape(c,f),b.push(c)}return b},loadPolygon:function(a,b){if(null===a)var c=b;else var c=this.game.cache.getPhysicsData(a,b);for(var d=p2.vec2.create(),e=0;e<c.length;e++){for(var f=[],g=0;g<c[e].shape.length;g+=2)f.push([this.world.pxmi(c[e].shape[g]),this.world.pxmi(c[e].shape[g+1])]);for(var h=new p2.Convex({vertices:f}),i=0;i!==h.vertices.length;i++){var j=h.vertices[i];p2.vec2.sub(j,j,h.centerOfMass)}p2.vec2.scale(d,h.centerOfMass,1),d[0]-=this.world.pxmi(this.sprite.width/2),d[1]-=this.world.pxmi(this.sprite.height/2),h.updateTriangles(),h.updateCenterOfMass(),h.updateBoundingRadius(),this.data.addShape(h,d)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),!0}},c.Physics.P2.Body.prototype.constructor=c.Physics.P2.Body,c.Physics.P2.Body.DYNAMIC=1,c.Physics.P2.Body.STATIC=2,c.Physics.P2.Body.KINEMATIC=4,Object.defineProperty(c.Physics.P2.Body.prototype,"static",{get:function(){return this.data.type===c.Physics.P2.Body.STATIC},set:function(a){a&&this.data.type!==c.Physics.P2.Body.STATIC?(this.data.type=c.Physics.P2.Body.STATIC,this.mass=0):a||this.data.type!==c.Physics.P2.Body.STATIC||(this.data.type=c.Physics.P2.Body.DYNAMIC,0===this.mass&&(this.mass=1))}}),Object.defineProperty(c.Physics.P2.Body.prototype,"dynamic",{get:function(){return this.data.type===c.Physics.P2.Body.DYNAMIC},set:function(a){a&&this.data.type!==c.Physics.P2.Body.DYNAMIC?(this.data.type=c.Physics.P2.Body.DYNAMIC,0===this.mass&&(this.mass=1)):a||this.data.type!==c.Physics.P2.Body.DYNAMIC||(this.data.type=c.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"kinematic",{get:function(){return this.data.type===c.Physics.P2.Body.KINEMATIC},set:function(a){a&&this.data.type!==c.Physics.P2.Body.KINEMATIC?(this.data.type=c.Physics.P2.Body.KINEMATIC,this.mass=4):a||this.data.type!==c.Physics.P2.Body.KINEMATIC||(this.data.type=c.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"allowSleep",{get:function(){return this.data.allowSleep},set:function(a){a!==this.data.allowSleep&&(this.data.allowSleep=a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angle",{get:function(){return c.Math.wrapAngle(c.Math.radToDeg(this.data.angle))},set:function(a){this.data.angle=c.Math.degToRad(c.Math.wrapAngle(a))}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angularDamping",{get:function(){return this.data.angularDamping},set:function(a){this.data.angularDamping=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angularForce",{get:function(){return this.data.angularForce},set:function(a){this.data.angularForce=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"angularVelocity",{get:function(){return this.data.angularVelocity},set:function(a){this.data.angularVelocity=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"damping",{get:function(){return this.data.damping},set:function(a){this.data.damping=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"fixedRotation",{get:function(){return this.data.fixedRotation},set:function(a){a!==this.data.fixedRotation&&(this.data.fixedRotation=a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"inertia",{get:function(){return this.data.inertia},set:function(a){this.data.inertia=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"mass",{get:function(){return this.data.mass},set:function(a){a!==this.data.mass&&(this.data.mass=a,this.data.updateMassProperties())}}),Object.defineProperty(c.Physics.P2.Body.prototype,"motionState",{get:function(){return this.data.type},set:function(a){a!==this.data.type&&(this.data.type=a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"rotation",{get:function(){return this.data.angle},set:function(a){this.data.angle=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"sleepSpeedLimit",{get:function(){return this.data.sleepSpeedLimit},set:function(a){this.data.sleepSpeedLimit=a}}),Object.defineProperty(c.Physics.P2.Body.prototype,"x",{get:function(){return this.world.mpxi(this.data.position[0])},set:function(a){this.data.position[0]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"y",{get:function(){return this.world.mpxi(this.data.position[1])},set:function(a){this.data.position[1]=this.world.pxmi(a)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"id",{get:function(){return this.data.id}}),Object.defineProperty(c.Physics.P2.Body.prototype,"debug",{get:function(){return null!==this.debugBody},set:function(a){a&&!this.debugBody?this.debugBody=new c.Physics.P2.BodyDebug(this.game,this.data):!a&&this.debugBody&&(this.debugBody.destroy(),this.debugBody=null)}}),Object.defineProperty(c.Physics.P2.Body.prototype,"collideWorldBounds",{get:function(){return this._collideWorldBounds},set:function(a){a&&!this._collideWorldBounds?(this._collideWorldBounds=!0,this.updateCollisionMask()):!a&&this._collideWorldBounds&&(this._collideWorldBounds=!1,this.updateCollisionMask())}}),c.Physics.P2.BodyDebug=function(a,b,d){c.Group.call(this,a);
+var e={pixelsPerLengthUnit:20,debugPolygons:!1,lineWidth:1,alpha:.5};this.settings=c.Utils.extend(e,d),this.ppu=this.settings.pixelsPerLengthUnit,this.ppu=-1*this.ppu,this.body=b,this.canvas=new c.Graphics(a),this.canvas.alpha=this.settings.alpha,this.add(this.canvas),this.draw(),this.updateSpriteTransform()},c.Physics.P2.BodyDebug.prototype=Object.create(c.Group.prototype),c.Physics.P2.BodyDebug.prototype.constructor=c.Physics.P2.BodyDebug,c.Utils.extend(c.Physics.P2.BodyDebug.prototype,{updateSpriteTransform:function(){this.position.x=this.body.position[0]*this.ppu,this.position.y=this.body.position[1]*this.ppu,this.rotation=this.body.angle},draw:function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o;if(h=this.body,j=this.canvas,j.clear(),c=parseInt(this.randomPastelHex(),16),f=16711680,g=this.lineWidth,h instanceof p2.Body&&h.shapes.length){var p=h.shapes.length;for(d=0;d!==p;){if(b=h.shapes[d],i=b.position||0,a=b.angle||0,b instanceof p2.Circle)this.drawCircle(j,i[0]*this.ppu,i[1]*this.ppu,a,b.radius*this.ppu,c,g);else if(b instanceof p2.Capsule)this.drawCapsule(j,i[0]*this.ppu,i[1]*this.ppu,a,b.length*this.ppu,b.radius*this.ppu,f,c,g);else if(b instanceof p2.Plane)this.drawPlane(j,i[0]*this.ppu,-i[1]*this.ppu,c,f,5*g,10*g,10*g,100*this.ppu,a);else if(b instanceof p2.Line)this.drawLine(j,b.length*this.ppu,f,g);else if(b instanceof p2.Box)this.drawRectangle(j,i[0]*this.ppu,i[1]*this.ppu,a,b.width*this.ppu,b.height*this.ppu,f,c,g);else if(b instanceof p2.Convex){for(l=[],m=p2.vec2.create(),e=n=0,o=b.vertices.length;o>=0?o>n:n>o;e=o>=0?++n:--n)k=b.vertices[e],p2.vec2.rotate(m,k,a),l.push([(m[0]+i[0])*this.ppu,-(m[1]+i[1])*this.ppu]);this.drawConvex(j,l,b.triangles,f,c,g,this.settings.debugPolygons,[i[0]*this.ppu,-i[1]*this.ppu])}d++}}},drawRectangle:function(a,b,c,d,e,f,g,h,i){void 0===i&&(i=1),void 0===g&&(g=0),a.lineStyle(i,g,1),a.beginFill(h),a.drawRect(b-e/2,c-f/2,e,f)},drawCircle:function(a,b,c,d,e,f,g){void 0===g&&(g=1),void 0===f&&(f=16777215),a.lineStyle(g,0,1),a.beginFill(f,1),a.drawCircle(b,c,2*-e),a.endFill(),a.moveTo(b,c),a.lineTo(b+e*Math.cos(-d),c+e*Math.sin(-d))},drawLine:function(a,b,c,d){void 0===d&&(d=1),void 0===c&&(c=0),a.lineStyle(5*d,c,1),a.moveTo(-b/2,0),a.lineTo(b/2,0)},drawConvex:function(a,b,c,d,e,f,g,h){var i,j,k,l,m,n,o,p,q,r,s;if(void 0===f&&(f=1),void 0===d&&(d=0),g){for(i=[16711680,65280,255],j=0;j!==b.length+1;)l=b[j%b.length],m=b[(j+1)%b.length],o=l[0],r=l[1],p=m[0],s=m[1],a.lineStyle(f,i[j%i.length],1),a.moveTo(o,-r),a.lineTo(p,-s),a.drawCircle(o,-r,2*f),j++;return a.lineStyle(f,0,1),a.drawCircle(h[0],h[1],2*f)}for(a.lineStyle(f,d,1),a.beginFill(e),j=0;j!==b.length;)k=b[j],n=k[0],q=k[1],0===j?a.moveTo(n,-q):a.lineTo(n,-q),j++;return a.endFill(),b.length>2?(a.moveTo(b[b.length-1][0],-b[b.length-1][1]),a.lineTo(b[0][0],-b[0][1])):void 0},drawPath:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r;for(void 0===e&&(e=1),void 0===c&&(c=0),a.lineStyle(e,c,1),"number"==typeof d&&a.beginFill(d),h=null,i=null,g=0;g<b.length;)p=b[g],q=p[0],r=p[1],(q!==h||r!==i)&&(0===g?a.moveTo(q,r):(j=h,k=i,l=q,m=r,n=b[(g+1)%b.length][0],o=b[(g+1)%b.length][1],f=(l-j)*(o-k)-(n-j)*(m-k),0!==f&&a.lineTo(q,r)),h=q,i=r),g++;"number"==typeof d&&a.endFill(),b.length>2&&"number"==typeof d&&(a.moveTo(b[b.length-1][0],b[b.length-1][1]),a.lineTo(b[0][0],b[0][1]))},drawPlane:function(a,b,c,d,e,f,g,h,i,j){var k,l,m;void 0===f&&(f=1),void 0===d&&(d=16777215),a.lineStyle(f,e,11),a.beginFill(d),k=i,a.moveTo(b,-c),l=b+Math.cos(j)*this.game.width,m=c+Math.sin(j)*this.game.height,a.lineTo(l,-m),a.moveTo(b,-c),l=b+Math.cos(j)*-this.game.width,m=c+Math.sin(j)*-this.game.height,a.lineTo(l,-m)},drawCapsule:function(a,b,c,d,e,f,g,h,i){void 0===i&&(i=1),void 0===g&&(g=0),a.lineStyle(i,g,1);var j=Math.cos(d),k=Math.sin(d);a.beginFill(h,1),a.drawCircle(-e/2*j+b,-e/2*k+c,2*-f),a.drawCircle(e/2*j+b,e/2*k+c,2*-f),a.endFill(),a.lineStyle(i,g,0),a.beginFill(h,1),a.moveTo(-e/2*j+f*k+b,-e/2*k+f*j+c),a.lineTo(e/2*j+f*k+b,e/2*k+f*j+c),a.lineTo(e/2*j-f*k+b,e/2*k-f*j+c),a.lineTo(-e/2*j-f*k+b,-e/2*k-f*j+c),a.endFill(),a.lineStyle(i,g,1),a.moveTo(-e/2*j+f*k+b,-e/2*k+f*j+c),a.lineTo(e/2*j+f*k+b,e/2*k+f*j+c),a.moveTo(-e/2*j-f*k+b,-e/2*k-f*j+c),a.lineTo(e/2*j-f*k+b,e/2*k-f*j+c)},randomPastelHex:function(){var a,b,c,d;return c=[255,255,255],d=Math.floor(256*Math.random()),b=Math.floor(256*Math.random()),a=Math.floor(256*Math.random()),d=Math.floor((d+3*c[0])/4),b=Math.floor((b+3*c[1])/4),a=Math.floor((a+3*c[2])/4),this.rgbToHex(d,b,a)},rgbToHex:function(a,b,c){return this.componentToHex(a)+this.componentToHex(b)+this.componentToHex(c)},componentToHex:function(a){var b;return b=a.toString(16),2===b.len?b:b+"0"}}),c.Physics.P2.Spring=function(a,b,c,d,e,f,g,h,i,j){this.game=a.game,this.world=a,void 0===d&&(d=1),void 0===e&&(e=100),void 0===f&&(f=1),d=a.pxm(d);var k={restLength:d,stiffness:e,damping:f};"undefined"!=typeof g&&null!==g&&(k.worldAnchorA=[a.pxm(g[0]),a.pxm(g[1])]),"undefined"!=typeof h&&null!==h&&(k.worldAnchorB=[a.pxm(h[0]),a.pxm(h[1])]),"undefined"!=typeof i&&null!==i&&(k.localAnchorA=[a.pxm(i[0]),a.pxm(i[1])]),"undefined"!=typeof j&&null!==j&&(k.localAnchorB=[a.pxm(j[0]),a.pxm(j[1])]),this.data=new p2.LinearSpring(b,c,k),this.data.parent=this},c.Physics.P2.Spring.prototype.constructor=c.Physics.P2.Spring,c.Physics.P2.RotationalSpring=function(a,b,c,d,e,f){this.game=a.game,this.world=a,void 0===d&&(d=null),void 0===e&&(e=100),void 0===f&&(f=1),d&&(d=a.pxm(d));var g={restAngle:d,stiffness:e,damping:f};this.data=new p2.RotationalSpring(b,c,g),this.data.parent=this},c.Physics.P2.Spring.prototype.constructor=c.Physics.P2.Spring,c.Physics.P2.Material=function(a){this.name=a,p2.Material.call(this)},c.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),c.Physics.P2.Material.prototype.constructor=c.Physics.P2.Material,c.Physics.P2.ContactMaterial=function(a,b,c){p2.ContactMaterial.call(this,a,b,c)},c.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),c.Physics.P2.ContactMaterial.prototype.constructor=c.Physics.P2.ContactMaterial,c.Physics.P2.CollisionGroup=function(a){this.mask=a},c.Physics.P2.DistanceConstraint=function(a,b,c,d,e,f,g){void 0===d&&(d=100),void 0===e&&(e=[0,0]),void 0===f&&(f=[0,0]),void 0===g&&(g=Number.MAX_VALUE),this.game=a.game,this.world=a,d=a.pxm(d),e=[a.pxmi(e[0]),a.pxmi(e[1])],f=[a.pxmi(f[0]),a.pxmi(f[1])];var h={distance:d,localAnchorA:e,localAnchorB:f,maxForce:g};p2.DistanceConstraint.call(this,b,c,h)},c.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),c.Physics.P2.DistanceConstraint.prototype.constructor=c.Physics.P2.DistanceConstraint,c.Physics.P2.GearConstraint=function(a,b,c,d,e){void 0===d&&(d=0),void 0===e&&(e=1),this.game=a.game,this.world=a;var f={angle:d,ratio:e};p2.GearConstraint.call(this,b,c,f)},c.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),c.Physics.P2.GearConstraint.prototype.constructor=c.Physics.P2.GearConstraint,c.Physics.P2.LockConstraint=function(a,b,c,d,e,f){void 0===d&&(d=[0,0]),void 0===e&&(e=0),void 0===f&&(f=Number.MAX_VALUE),this.game=a.game,this.world=a,d=[a.pxm(d[0]),a.pxm(d[1])];var g={localOffsetB:d,localAngleB:e,maxForce:f};p2.LockConstraint.call(this,b,c,g)},c.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),c.Physics.P2.LockConstraint.prototype.constructor=c.Physics.P2.LockConstraint,c.Physics.P2.PrismaticConstraint=function(a,b,c,d,e,f,g,h){void 0===d&&(d=!0),void 0===e&&(e=[0,0]),void 0===f&&(f=[0,0]),void 0===g&&(g=[0,0]),void 0===h&&(h=Number.MAX_VALUE),this.game=a.game,this.world=a,e=[a.pxmi(e[0]),a.pxmi(e[1])],f=[a.pxmi(f[0]),a.pxmi(f[1])];var i={localAnchorA:e,localAnchorB:f,localAxisA:g,maxForce:h,disableRotationalLock:!d};p2.PrismaticConstraint.call(this,b,c,i)},c.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),c.Physics.P2.PrismaticConstraint.prototype.constructor=c.Physics.P2.PrismaticConstraint,c.Physics.P2.RevoluteConstraint=function(a,b,c,d,e,f,g){void 0===f&&(f=Number.MAX_VALUE),void 0===g&&(g=null),this.game=a.game,this.world=a,c=[a.pxmi(c[0]),a.pxmi(c[1])],e=[a.pxmi(e[0]),a.pxmi(e[1])],g&&(g=[a.pxmi(g[0]),a.pxmi(g[1])]);var h={worldPivot:g,localPivotA:c,localPivotB:e,maxForce:f};p2.RevoluteConstraint.call(this,b,d,h)},c.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),c.Physics.P2.RevoluteConstraint.prototype.constructor=c.Physics.P2.RevoluteConstraint,c.ImageCollection=function(a,b,c,d,e,f,g){(void 0===c||0>=c)&&(c=32),(void 0===d||0>=d)&&(d=32),void 0===e&&(e=0),void 0===f&&(f=0),this.name=a,this.firstgid=0|b,this.imageWidth=0|c,this.imageHeight=0|d,this.imageMargin=0|e,this.imageSpacing=0|f,this.properties=g||{},this.images=[],this.total=0},c.ImageCollection.prototype={containsImageIndex:function(a){return a>=this.firstgid&&a<this.firstgid+this.total},addImage:function(a,b){this.images.push({gid:a,image:b}),this.total++}},c.ImageCollection.prototype.constructor=c.ImageCollection,c.Tile=function(a,b,c,d,e,f){this.layer=a,this.index=b,this.x=c,this.y=d,this.rotation=0,this.flipped=!1,this.worldX=c*e,this.worldY=d*f,this.width=e,this.height=f,this.centerX=Math.abs(e/2),this.centerY=Math.abs(f/2),this.alpha=1,this.properties={},this.scanned=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.collisionCallback=null,this.collisionCallbackContext=this},c.Tile.prototype={containsPoint:function(a,b){return!(a<this.worldX||b<this.worldY||a>this.right||b>this.bottom)},intersects:function(a,b,c,d){return c<=this.worldX?!1:d<=this.worldY?!1:a>=this.worldX+this.width?!1:b>=this.worldY+this.height?!1:!0},setCollisionCallback:function(a,b){this.collisionCallback=a,this.collisionCallbackContext=b},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(a,b,c,d){this.collideLeft=a,this.collideRight=b,this.collideUp=c,this.collideDown=d,this.faceLeft=a,this.faceRight=b,this.faceTop=c,this.faceBottom=d},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(a,b){return a&&b?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:a?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:b?this.faceTop||this.faceBottom||this.faceLeft||this.faceRight:!1},copy:function(a){this.index=a.index,this.alpha=a.alpha,this.properties=a.properties,this.collideUp=a.collideUp,this.collideDown=a.collideDown,this.collideLeft=a.collideLeft,this.collideRight=a.collideRight,this.collisionCallback=a.collisionCallback,this.collisionCallbackContext=a.collisionCallbackContext}},c.Tile.prototype.constructor=c.Tile,Object.defineProperty(c.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(c.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(c.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(c.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(c.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(c.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),c.Tilemap=function(a,b,d,e,f,g){this.game=a,this.key=b;var h=c.TilemapParser.parse(this.game,b,d,e,f,g);null!==h&&(this.width=h.width,this.height=h.height,this.tileWidth=h.tileWidth,this.tileHeight=h.tileHeight,this.orientation=h.orientation,this.format=h.format,this.version=h.version,this.properties=h.properties,this.widthInPixels=h.widthInPixels,this.heightInPixels=h.heightInPixels,this.layers=h.layers,this.tilesets=h.tilesets,this.imagecollections=h.imagecollections,this.tiles=h.tiles,this.objects=h.objects,this.collideIndexes=[],this.collision=h.collision,this.images=h.images,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},c.Tilemap.CSV=0,c.Tilemap.TILED_JSON=1,c.Tilemap.NORTH=0,c.Tilemap.EAST=1,c.Tilemap.SOUTH=2,c.Tilemap.WEST=3,c.Tilemap.prototype={create:function(a,b,c,d,e,f){return void 0===f&&(f=this.game.world),this.width=b,this.height=c,this.setTileSize(d,e),this.layers.length=0,this.createBlankLayer(a,b,c,d,e,f)},setTileSize:function(a,b){this.tileWidth=a,this.tileHeight=b,this.widthInPixels=this.width*a,this.heightInPixels=this.height*b},addTilesetImage:function(a,b,d,e,f,g,h){if(void 0===a)return null;void 0===d&&(d=this.tileWidth),void 0===e&&(e=this.tileHeight),void 0===f&&(f=0),void 0===g&&(g=0),void 0===h&&(h=0),0===d&&(d=32),0===e&&(e=32);var i=null;if((void 0===b||null===b)&&(b=a),b instanceof c.BitmapData)i=b.canvas;else{if(!this.game.cache.checkImageKey(b))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+b+'"'),null;i=this.game.cache.getImage(b)}var j=this.getTilesetIndex(a);if(null===j&&this.format===c.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+b+'"'),null;if(this.tilesets[j])return this.tilesets[j].setImage(i),this.tilesets[j];var k=new c.Tileset(a,h,d,e,f,g,{});k.setImage(i),this.tilesets.push(k);for(var l=this.tilesets.length-1,m=f,n=f,o=0,p=0,q=0,r=h;r<h+k.total&&(this.tiles[r]=[m,n,l],m+=d+g,o++,o!==k.total)&&(p++,p!==k.columns||(m=f,n+=e+g,p=0,q++,q!==k.rows));r++);return k},createFromObjects:function(a,b,d,e,f,g,h,i,j){if(void 0===f&&(f=!0),void 0===g&&(g=!1),void 0===h&&(h=this.game.world),void 0===i&&(i=c.Sprite),void 0===j&&(j=!0),!this.objects[a])return void console.warn("Tilemap.createFromObjects: Invalid objectgroup name given: "+a);for(var k,l=!1,m=0,n=this.objects[a].length;n>m;m++)if("undefined"!=typeof this.objects[a][m].gid&&"number"==typeof b&&this.objects[a][m].gid===b&&(l=!0),"undefined"!=typeof this.objects[a][m].id&&"number"==typeof b&&this.objects[a][m].id===b&&(l=!0),"undefined"!=typeof this.objects[a][m].name&&"string"==typeof b&&this.objects[a][m].name===b&&(l=!0),l){k=new i(this.game,this.objects[a][m].x,this.objects[a][m].y,d,e),k.name=this.objects[a][m].name,k.visible=this.objects[a][m].visible,k.autoCull=g,k.exists=f,k.width=this.objects[a][m].width,k.height=this.objects[a][m].height,this.objects[a][m].rotation&&(k.angle=this.objects[a][m].rotation),j&&(k.y-=k.height),h.add(k);for(var o in this.objects[a][m].properties)h.set(k,o,this.objects[a][m].properties[o],!1,!1,0,!0)}},createFromTiles:function(a,b,d,e,f,g){"number"==typeof a&&(a=[a]),void 0===b||null===b?b=[]:"number"==typeof b&&(b=[b]),e=this.getLayer(e),void 0===f&&(f=this.game.world),void 0===g&&(g={}),void 0===g.customClass&&(g.customClass=c.Sprite),void 0===g.adjustY&&(g.adjustY=!0);var h=this.layers[e].width,i=this.layers[e].height;if(this.copy(0,0,h,i,e),this._results.length<2)return 0;for(var j,k=0,l=1,m=this._results.length;m>l;l++)if(-1!==a.indexOf(this._results[l].index)){j=new g.customClass(this.game,this._results[l].worldX,this._results[l].worldY,d);for(var n in g)j[n]=g[n];f.add(j),k++}if(1===b.length)for(l=0;l<a.length;l++)this.replace(a[l],b[0],0,0,h,i,e);else if(b.length>1)for(l=0;l<a.length;l++)this.replace(a[l],b[l],0,0,h,i,e);return k},createLayer:function(a,b,d,e){void 0===b&&(b=this.game.width),void 0===d&&(d=this.game.height),void 0===e&&(e=this.game.world);var f=a;return"string"==typeof a&&(f=this.getLayerIndex(a)),null===f||f>this.layers.length?void console.warn("Tilemap.createLayer: Invalid layer ID given: "+f):e.add(new c.TilemapLayer(this.game,this,f,b,d))},createBlankLayer:function(a,b,d,e,f,g){if(void 0===g&&(g=this.game.world),null!==this.getLayerIndex(a))return void console.warn("Tilemap.createBlankLayer: Layer with matching name already exists");for(var h,i={name:a,x:0,y:0,width:b,height:d,widthInPixels:b*e,heightInPixels:d*f,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},j=[],k=0;d>k;k++){h=[];for(var l=0;b>l;l++)h.push(new c.Tile(i,-1,l,k,e,f));j.push(h)}i.data=j,this.layers.push(i),this.currentLayer=this.layers.length-1;var m=i.widthInPixels,n=i.heightInPixels;m>this.game.width&&(m=this.game.width),n>this.game.height&&(n=this.game.height);var j=new c.TilemapLayer(this.game,this,this.layers.length-1,m,n);return j.name=a,g.add(j)},getIndex:function(a,b){for(var c=0;c<a.length;c++)if(a[c].name===b)return c;return null},getLayerIndex:function(a){return this.getIndex(this.layers,a)},getTilesetIndex:function(a){return this.getIndex(this.tilesets,a)},getImageIndex:function(a){return this.getIndex(this.images,a)},getObjectIndex:function(a){return this.getIndex(this.objects,a)},setTileIndexCallback:function(a,b,c,d){if(d=this.getLayer(d),"number"==typeof a)this.layers[d].callbacks[a]={callback:b,callbackContext:c};else for(var e=0,f=a.length;f>e;e++)this.layers[d].callbacks[a[e]]={callback:b,callbackContext:c}},setTileLocationCallback:function(a,b,c,d,e,f,g){if(g=this.getLayer(g),this.copy(a,b,c,d,g),!(this._results.length<2))for(var h=1;h<this._results.length;h++)this._results[h].setCollisionCallback(e,f)},setCollision:function(a,b,c,d){if(void 0===b&&(b=!0),void 0===d&&(d=!0),c=this.getLayer(c),"number"==typeof a)return this.setCollisionByIndex(a,b,c,!0);if(Array.isArray(a)){for(var e=0;e<a.length;e++)this.setCollisionByIndex(a[e],b,c,!1);d&&this.calculateFaces(c)}},setCollisionBetween:function(a,b,c,d,e){if(void 0===c&&(c=!0),void 0===e&&(e=!0),d=this.getLayer(d),!(a>b)){for(var f=a;b>=f;f++)this.setCollisionByIndex(f,c,d,!1);e&&this.calculateFaces(d)}},setCollisionByExclusion:function(a,b,c,d){void 0===b&&(b=!0),void 0===d&&(d=!0),c=this.getLayer(c);for(var e=0,f=this.tiles.length;f>e;e++)-1===a.indexOf(e)&&this.setCollisionByIndex(e,b,c,!1);d&&this.calculateFaces(c)},setCollisionByIndex:function(a,b,c,d){if(void 0===b&&(b=!0),void 0===c&&(c=this.currentLayer),void 0===d&&(d=!0),b)this.collideIndexes.push(a);else{var e=this.collideIndexes.indexOf(a);e>-1&&this.collideIndexes.splice(e,1)}for(var f=0;f<this.layers[c].height;f++)for(var g=0;g<this.layers[c].width;g++){var h=this.layers[c].data[f][g];h&&h.index===a&&(b?h.setCollision(!0,!0,!0,!0):h.resetCollision(),h.faceTop=b,h.faceBottom=b,h.faceLeft=b,h.faceRight=b)}return d&&this.calculateFaces(c),c},getLayer:function(a){return void 0===a?a=this.currentLayer:"string"==typeof a?a=this.getLayerIndex(a):a instanceof c.TilemapLayer&&(a=a.index),a},setPreventRecalculate:function(a){if(a===!0&&this.preventingRecalculate!==!0&&(this.preventingRecalculate=!0,this.needToRecalculate={}),a===!1&&this.preventingRecalculate===!0){this.preventingRecalculate=!1;for(var b in this.needToRecalculate)this.calculateFaces(b);this.needToRecalculate=!1}},calculateFaces:function(a){if(this.preventingRecalculate)return void(this.needToRecalculate[a]=!0);for(var b=null,c=null,d=null,e=null,f=0,g=this.layers[a].height;g>f;f++)for(var h=0,i=this.layers[a].width;i>h;h++){var j=this.layers[a].data[f][h];j&&(b=this.getTileAbove(a,h,f),c=this.getTileBelow(a,h,f),d=this.getTileLeft(a,h,f),e=this.getTileRight(a,h,f),j.collides&&(j.faceTop=!0,j.faceBottom=!0,j.faceLeft=!0,j.faceRight=!0),b&&b.collides&&(j.faceTop=!1),c&&c.collides&&(j.faceBottom=!1),d&&d.collides&&(j.faceLeft=!1),e&&e.collides&&(j.faceRight=!1))}},getTileAbove:function(a,b,c){return c>0?this.layers[a].data[c-1][b]:null},getTileBelow:function(a,b,c){return c<this.layers[a].height-1?this.layers[a].data[c+1][b]:null},getTileLeft:function(a,b,c){return b>0?this.layers[a].data[c][b-1]:null},getTileRight:function(a,b,c){return b<this.layers[a].width-1?this.layers[a].data[c][b+1]:null},setLayer:function(a){a=this.getLayer(a),this.layers[a]&&(this.currentLayer=a)},hasTile:function(a,b,c){return c=this.getLayer(c),this.layers[c].data[b][a].index>-1},removeTile:function(a,b,d){if(d=this.getLayer(d),a>=0&&a<this.layers[d].width&&b>=0&&b<this.layers[d].height&&this.hasTile(a,b,d)){var e=this.layers[d].data[b][a];return this.layers[d].data[b][a]=new c.Tile(this.layers[d],-1,a,b,this.tileWidth,this.tileHeight),this.layers[d].dirty=!0,this.calculateFaces(d),e}},removeTileWorldXY:function(a,b,c,d,e){return e=this.getLayer(e),a=this.game.math.snapToFloor(a,c)/c,b=this.game.math.snapToFloor(b,d)/d,this.removeTile(a,b,e)},putTile:function(a,b,d,e){if(null===a)return this.removeTile(b,d,e);if(e=this.getLayer(e),b>=0&&b<this.layers[e].width&&d>=0&&d<this.layers[e].height){var f;return a instanceof c.Tile?(f=a.index,this.hasTile(b,d,e)?this.layers[e].data[d][b].copy(a):this.layers[e].data[d][b]=new c.Tile(e,f,b,d,a.width,a.height)):(f=a,this.hasTile(b,d,e)?this.layers[e].data[d][b].index=f:this.layers[e].data[d][b]=new c.Tile(this.layers[e],f,b,d,this.tileWidth,this.tileHeight)),this.collideIndexes.indexOf(f)>-1?this.layers[e].data[d][b].setCollision(!0,!0,!0,!0):this.layers[e].data[d][b].resetCollision(),this.layers[e].dirty=!0,this.calculateFaces(e),this.layers[e].data[d][b]}return null},putTileWorldXY:function(a,b,c,d,e,f){return f=this.getLayer(f),b=this.game.math.snapToFloor(b,d)/d,c=this.game.math.snapToFloor(c,e)/e,this.putTile(a,b,c,f)},searchTileIndex:function(a,b,c,d){void 0===b&&(b=0),void 0===c&&(c=!1),d=this.getLayer(d);var e=0;if(c){for(var f=this.layers[d].height-1;f>=0;f--)for(var g=this.layers[d].width-1;g>=0;g--)if(this.layers[d].data[f][g].index===a){if(e===b)return this.layers[d].data[f][g];e++}}else for(var f=0;f<this.layers[d].height;f++)for(var g=0;g<this.layers[d].width;g++)if(this.layers[d].data[f][g].index===a){if(e===b)return this.layers[d].data[f][g];e++}return null},getTile:function(a,b,c,d){return void 0===d&&(d=!1),c=this.getLayer(c),a>=0&&a<this.layers[c].width&&b>=0&&b<this.layers[c].height?-1===this.layers[c].data[b][a].index?d?this.layers[c].data[b][a]:null:this.layers[c].data[b][a]:null},getTileWorldXY:function(a,b,c,d,e,f){return void 0===c&&(c=this.tileWidth),void 0===d&&(d=this.tileHeight),e=this.getLayer(e),a=this.game.math.snapToFloor(a,c)/c,b=this.game.math.snapToFloor(b,d)/d,this.getTile(a,b,e,f)},copy:function(a,b,c,d,e){if(e=this.getLayer(e),!this.layers[e])return void(this._results.length=0);void 0===a&&(a=0),void 0===b&&(b=0),void 0===c&&(c=this.layers[e].width),void 0===d&&(d=this.layers[e].height),0>a&&(a=0),0>b&&(b=0),c>this.layers[e].width&&(c=this.layers[e].width),d>this.layers[e].height&&(d=this.layers[e].height),this._results.length=0,this._results.push({x:a,y:b,width:c,height:d,layer:e});for(var f=b;b+d>f;f++)for(var g=a;a+c>g;g++)this._results.push(this.layers[e].data[f][g]);return this._results},paste:function(a,b,c,d){if(void 0===a&&(a=0),void 0===b&&(b=0),d=this.getLayer(d),c&&!(c.length<2)){for(var e=a-c[1].x,f=b-c[1].y,g=1;g<c.length;g++)this.layers[d].data[f+c[g].y][e+c[g].x].copy(c[g]);this.layers[d].dirty=!0,this.calculateFaces(d)}},swap:function(a,b,c,d,e,f,g){g=this.getLayer(g),this.copy(c,d,e,f,g),this._results.length<2||(this._tempA=a,this._tempB=b,this._results.forEach(this.swapHandler,this),this.paste(c,d,this._results,g))},swapHandler:function(a){a.index===this._tempA?a.index=this._tempB:a.index===this._tempB&&(a.index=this._tempA)},forEach:function(a,b,c,d,e,f,g){g=this.getLayer(g),this.copy(c,d,e,f,g),this._results.length<2||(this._results.forEach(a,b),this.paste(c,d,this._results,g))},replace:function(a,b,c,d,e,f,g){if(g=this.getLayer(g),this.copy(c,d,e,f,g),!(this._results.length<2)){for(var h=1;h<this._results.length;h++)this._results[h].index===a&&(this._results[h].index=b);this.paste(c,d,this._results,g)}},random:function(a,b,c,d,e){if(e=this.getLayer(e),this.copy(a,b,c,d,e),!(this._results.length<2)){for(var f=[],g=1;g<this._results.length;g++)if(this._results[g].index){var h=this._results[g].index;-1===f.indexOf(h)&&f.push(h)}for(var i=1;i<this._results.length;i++)this._results[i].index=this.game.rnd.pick(f);this.paste(a,b,this._results,e)}},shuffle:function(a,b,d,e,f){if(f=this.getLayer(f),this.copy(a,b,d,e,f),!(this._results.length<2)){for(var g=[],h=1;h<this._results.length;h++)this._results[h].index&&g.push(this._results[h].index);c.Utils.shuffle(g);for(var i=1;i<this._results.length;i++)this._results[i].index=g[i-1];this.paste(a,b,this._results,f)}},fill:function(a,b,c,d,e,f){if(f=this.getLayer(f),this.copy(b,c,d,e,f),!(this._results.length<2)){for(var g=1;g<this._results.length;g++)this._results[g].index=a;this.paste(b,c,this._results,f)}},removeAllLayers:function(){this.layers.length=0,this.currentLayer=0},dump:function(){for(var a="",b=[""],c=0;c<this.layers[this.currentLayer].height;c++){for(var d=0;d<this.layers[this.currentLayer].width;d++)a+="%c  ",b.push(this.layers[this.currentLayer].data[c][d]>1?this.debugMap[this.layers[this.currentLayer].data[c][d]]?"background: "+this.debugMap[this.layers[this.currentLayer].data[c][d]]:"background: #ffffff":"background: rgb(0, 0, 0)");a+="\n"}b[0]=a,console.log.apply(console,b)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},c.Tilemap.prototype.constructor=c.Tilemap,Object.defineProperty(c.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(a){a!==this.currentLayer&&this.setLayer(a)}}),c.TilemapLayer=function(a,b,d,e,f){e|=0,f|=0,c.Sprite.call(this,a,0,0),this.map=b,this.index=d,this.layer=b.layers[d],this.canvas=c.Canvas.create(e,f),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas))),this.type=c.TILEMAPLAYER,this.physicsType=c.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!1,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:b.tileWidth,tileHeight:b.tileHeight,cw:b.tileWidth,ch:b.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this._results=[],a.device.canvasBitBltShift||(this.renderSettings.copyCanvas=c.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},c.TilemapLayer.prototype=Object.create(c.Sprite.prototype),c.TilemapLayer.prototype.constructor=c.TilemapLayer,c.TilemapLayer.prototype.preUpdateCore=c.Component.Core.preUpdate,c.TilemapLayer.sharedCopyCanvas=null,c.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=c.Canvas.create(2,2)),this.sharedCopyCanvas},c.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},c.TilemapLayer.prototype.postUpdate=function(){c.Component.FixedToCamera.postUpdate.call(this);var a=this.game.camera;this.scrollX=a.x*this.scrollFactorX/this.scale.x,this.scrollY=a.y*this.scrollFactorY/this.scale.y,this.render()},c.TilemapLayer.prototype.resize=function(a,b){this.canvas.width=a,this.canvas.height=b,this.texture.frame.resize(a,b),this.texture.width=a,this.texture.height=b,this.texture.crop.width=a,this.texture.crop.height=b,this.texture.baseTexture.width=a,this.texture.baseTexture.height=b,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},c.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},c.TilemapLayer.prototype._fixX=function(a){return 0>a&&(a=0),1===this.scrollFactorX?a:this._scrollX+(a-this._scrollX/this.scrollFactorX)},c.TilemapLayer.prototype._unfixX=function(a){return 1===this.scrollFactorX?a:this._scrollX/this.scrollFactorX+(a-this._scrollX)},c.TilemapLayer.prototype._fixY=function(a){return 0>a&&(a=0),1===this.scrollFactorY?a:this._scrollY+(a-this._scrollY/this.scrollFactorY)},c.TilemapLayer.prototype._unfixY=function(a){return 1===this.scrollFactorY?a:this._scrollY/this.scrollFactorY+(a-this._scrollY)},c.TilemapLayer.prototype.getTileX=function(a){return Math.floor(this._fixX(a)/this._mc.tileWidth)},c.TilemapLayer.prototype.getTileY=function(a){return Math.floor(this._fixY(a)/this._mc.tileHeight)},c.TilemapLayer.prototype.getTileXY=function(a,b,c){return c.x=this.getTileX(a),c.y=this.getTileY(b),c},c.TilemapLayer.prototype.getRayCastTiles=function(a,b,c,d){b||(b=this.rayStepRate),void 0===c&&(c=!1),void 0===d&&(d=!1);var e=this.getTiles(a.x,a.y,a.width,a.height,c,d);if(0===e.length)return[];for(var f=a.coordinatesOnLine(b),g=[],h=0;h<e.length;h++)for(var i=0;i<f.length;i++){var j=e[h],k=f[i];if(j.containsPoint(k[0],k[1])){g.push(j);break}}return g},c.TilemapLayer.prototype.getTiles=function(a,b,c,d,e,f){void 0===e&&(e=!1),void 0===f&&(f=!1);var g=!(e||f);a=this._fixX(a),b=this._fixY(b);for(var h=Math.floor(a/(this._mc.cw*this.scale.x)),i=Math.floor(b/(this._mc.ch*this.scale.y)),j=Math.ceil((a+c)/(this._mc.cw*this.scale.x))-h,k=Math.ceil((b+d)/(this._mc.ch*this.scale.y))-i;this._results.length;)this._results.pop();for(var l=i;i+k>l;l++)for(var m=h;h+j>m;m++){var n=this.layer.data[l];n&&n[m]&&(g||n[m].isInteresting(e,f))&&this._results.push(n[m])}return this._results.slice()},c.TilemapLayer.prototype.resolveTileset=function(a){var b=this._mc.tilesets;if(2e3>a)for(;b.length<a;)b.push(void 0);var c=this.map.tiles[a]&&this.map.tiles[a][2];if(null!=c){var d=this.map.tilesets[c];if(d&&d.containsTileIndex(a))return b[a]=d}return b[a]=null},c.TilemapLayer.prototype.resetTilesetCache=function(){for(var a=this._mc.tilesets;a.length;)a.pop()},c.TilemapLayer.prototype.setScale=function(a,b){a=a||1,b=b||a;for(var c=0;c<this.layer.data.length;c++)for(var d=this.layer.data[c],e=0;e<d.length;e++){var f=d[e];f.width=this.map.tileWidth*a,f.height=this.map.tileHeight*b,f.worldX=f.x*f.width,f.worldY=f.y*f.height}this.scale.setTo(a,b)},c.TilemapLayer.prototype.shiftCanvas=function(a,b,c){var d=a.canvas,e=d.width-Math.abs(b),f=d.height-Math.abs(c),g=0,h=0,i=b,j=c;0>b&&(g=-b,i=0),0>c&&(h=-c,j=0);var k=this.renderSettings.copyCanvas;if(k){(k.width<e||k.height<f)&&(k.width=e,k.height=f);var l=k.getContext("2d");l.clearRect(0,0,e,f),l.drawImage(d,g,h,e,f,0,0,e,f),a.clearRect(i,j,e,f),a.drawImage(k,0,0,e,f,i,j,e,f)}else a.save(),a.globalCompositeOperation="copy",a.drawImage(d,g,h,e,f,i,j,e,f),a.restore()},c.TilemapLayer.prototype.renderRegion=function(a,b,c,d,e,f){var g=this.context,h=this.layer.width,i=this.layer.height,j=this._mc.tileWidth,k=this._mc.tileHeight,l=this._mc.tilesets,m=0/0;this._wrap||(e>=c&&(c=Math.max(0,c),e=Math.min(h-1,e)),f>=d&&(d=Math.max(0,d),f=Math.min(i-1,f)));var n,o,p,q,r,s,t=c*j-a,u=d*k-b,v=(c+(1<<20)*h)%h,w=(d+(1<<20)*i)%i;for(g.fillStyle=this.tileColor,q=w,s=f-d,o=u;s>=0;q++,s--,o+=k){q>=i&&(q-=i);var x=this.layer.data[q];for(p=v,r=e-c,n=t;r>=0;p++,r--,n+=j){p>=h&&(p-=h);var y=x[p];if(y&&!(y.index<0)){var z=y.index,A=l[z];void 0===A&&(A=this.resolveTileset(z)),y.alpha===m||this.debug||(g.globalAlpha=y.alpha,m=y.alpha),A?y.rotation||y.flipped?(g.save(),g.translate(n+y.centerX,o+y.centerY),g.rotate(y.rotation),y.flipped&&g.scale(-1,1),A.draw(g,-y.centerX,-y.centerY,z),g.restore()):A.draw(g,n,o,z):this.debugSettings.missingImageFill&&(g.fillStyle=this.debugSettings.missingImageFill,g.fillRect(n,o,j,k)),y.debug&&this.debugSettings.debuggedTileOverfill&&(g.fillStyle=this.debugSettings.debuggedTileOverfill,g.fillRect(n,o,j,k))}}}},c.TilemapLayer.prototype.renderDeltaScroll=function(a,b){var c=this._mc.scrollX,d=this._mc.scrollY,e=this.canvas.width,f=this.canvas.height,g=this._mc.tileWidth,h=this._mc.tileHeight,i=0,j=-g,k=0,l=-h;if(0>a?(i=e+a,j=e-1):a>0&&(j=a),0>b?(k=f+b,l=f-1):b>0&&(l=b),this.shiftCanvas(this.context,a,b),i=Math.floor((i+c)/g),j=Math.floor((j+c)/g),k=Math.floor((k+d)/h),l=Math.floor((l+d)/h),j>=i){this.context.clearRect(i*g-c,0,(j-i+1)*g,f);var m=Math.floor((0+d)/h),n=Math.floor((f-1+d)/h);
+this.renderRegion(c,d,i,m,j,n)}if(l>=k){this.context.clearRect(0,k*h-d,e,(l-k+1)*h);var o=Math.floor((0+c)/g),p=Math.floor((e-1+c)/g);this.renderRegion(c,d,o,k,p,l)}},c.TilemapLayer.prototype.renderFull=function(){var a=this._mc.scrollX,b=this._mc.scrollY,c=this.canvas.width,d=this.canvas.height,e=this._mc.tileWidth,f=this._mc.tileHeight,g=Math.floor(a/e),h=Math.floor((c-1+a)/e),i=Math.floor(b/f),j=Math.floor((d-1+b)/f);this.context.clearRect(0,0,c,d),this.renderRegion(a,b,g,i,h,j)},c.TilemapLayer.prototype.render=function(){var a=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,a=!0);var b=this.canvas.width,c=this.canvas.height,d=0|this._scrollX,e=0|this._scrollY,f=this._mc,g=f.scrollX-d,h=f.scrollY-e;if(a||0!==g||0!==h||f.renderWidth!==b||f.renderHeight!==c)return this.context.save(),f.scrollX=d,f.scrollY=e,(f.renderWidth!==b||f.renderHeight!==c)&&(f.renderWidth=b,f.renderHeight=c),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(a=!0)),!a&&this.renderSettings.enableScrollDelta&&Math.abs(g)+Math.abs(h)<Math.min(b,c)?this.renderDeltaScroll(g,h):this.renderFull(),this.debug&&(this.context.globalAlpha=1,this.renderDebug()),this.texture.baseTexture.dirty(),this.dirty=!1,this.context.restore(),!0}},c.TilemapLayer.prototype.renderDebug=function(){var a,b,c,d,e,f,g=this._mc.scrollX,h=this._mc.scrollY,i=this.context,j=this.canvas.width,k=this.canvas.height,l=this.layer.width,m=this.layer.height,n=this._mc.tileWidth,o=this._mc.tileHeight,p=Math.floor(g/n),q=Math.floor((j-1+g)/n),r=Math.floor(h/o),s=Math.floor((k-1+h)/o),t=p*n-g,u=r*o-h,v=(p+(1<<20)*l)%l,w=(r+(1<<20)*m)%m;for(i.strokeStyle=this.debugSettings.facingEdgeStroke,d=w,f=s-r,b=u;f>=0;d++,f--,b+=o){d>=m&&(d-=m);var x=this.layer.data[d];for(c=v,e=q-p,a=t;e>=0;c++,e--,a+=n){c>=l&&(c-=l);var y=x[c];!y||y.index<0||!y.collides||(this.debugSettings.collidingTileOverfill&&(i.fillStyle=this.debugSettings.collidingTileOverfill,i.fillRect(a,b,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(i.beginPath(),y.faceTop&&(i.moveTo(a,b),i.lineTo(a+this._mc.cw,b)),y.faceBottom&&(i.moveTo(a,b+this._mc.ch),i.lineTo(a+this._mc.cw,b+this._mc.ch)),y.faceLeft&&(i.moveTo(a,b),i.lineTo(a,b+this._mc.ch)),y.faceRight&&(i.moveTo(a+this._mc.cw,b),i.lineTo(a+this._mc.cw,b+this._mc.ch)),i.stroke()))}}},Object.defineProperty(c.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(a){this._wrap=a,this.dirty=!0}}),Object.defineProperty(c.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(a){this._scrollX=a}}),Object.defineProperty(c.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(a){this._scrollY=a}}),Object.defineProperty(c.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(a){this._mc.cw=0|a,this.dirty=!0}}),Object.defineProperty(c.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(a){this._mc.ch=0|a,this.dirty=!0}}),c.TilemapParser={parse:function(a,b,d,e,f,g){if(void 0===d&&(d=32),void 0===e&&(e=32),void 0===f&&(f=10),void 0===g&&(g=10),void 0===b)return this.getEmptyData();if(null===b)return this.getEmptyData(d,e,f,g);var h=a.cache.getTilemapData(b);if(h){if(h.format===c.Tilemap.CSV)return this.parseCSV(b,h.data,d,e);if(!h.format||h.format===c.Tilemap.TILED_JSON)return this.parseTiledJSON(h.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+b)},parseCSV:function(a,b,d,e){var f=this.getEmptyData();b=b.trim();for(var g=[],h=b.split("\n"),i=h.length,j=0,k=0;k<h.length;k++){g[k]=[];for(var l=h[k].split(","),m=0;m<l.length;m++)g[k][m]=new c.Tile(f.layers[0],parseInt(l[m],10),m,k,d,e);0===j&&(j=l.length)}return f.format=c.Tilemap.CSV,f.name=a,f.width=j,f.height=i,f.tileWidth=d,f.tileHeight=e,f.widthInPixels=j*d,f.heightInPixels=i*e,f.layers[0].width=j,f.layers[0].height=i,f.layers[0].widthInPixels=f.widthInPixels,f.layers[0].heightInPixels=f.heightInPixels,f.layers[0].data=g,f},getEmptyData:function(a,b,c,d){var e={};e.width=0,e.height=0,e.tileWidth=0,e.tileHeight=0,"undefined"!=typeof a&&null!==a&&(e.tileWidth=a),"undefined"!=typeof b&&null!==b&&(e.tileHeight=b),"undefined"!=typeof c&&null!==c&&(e.width=c),"undefined"!=typeof d&&null!==d&&(e.height=d),e.orientation="orthogonal",e.version="1",e.properties={},e.widthInPixels=0,e.heightInPixels=0;var f=[],g={name:"layer",x:0,y:0,width:0,height:0,widthInPixels:0,heightInPixels:0,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:[]};return f.push(g),e.layers=f,e.images=[],e.objects={},e.collision={},e.tilesets=[],e.tiles=[],e},parseTiledJSON:function(a){function b(a,b){var c={};for(var d in b){var e=b[d];"undefined"!=typeof a[e]&&(c[e]=a[e])}return c}if("orthogonal"!==a.orientation)return console.warn("TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser"),null;var d={};d.width=a.width,d.height=a.height,d.tileWidth=a.tilewidth,d.tileHeight=a.tileheight,d.orientation=a.orientation,d.format=c.Tilemap.TILED_JSON,d.version=a.version,d.properties=a.properties,d.widthInPixels=d.width*d.tileWidth,d.heightInPixels=d.height*d.tileHeight;for(var e=[],f=0;f<a.layers.length;f++)if("tilelayer"===a.layers[f].type){var g={name:a.layers[f].name,x:a.layers[f].x,y:a.layers[f].y,width:a.layers[f].width,height:a.layers[f].height,widthInPixels:a.layers[f].width*a.tilewidth,heightInPixels:a.layers[f].height*a.tileheight,alpha:a.layers[f].opacity,visible:a.layers[f].visible,properties:{},indexes:[],callbacks:[],bodies:[]};a.layers[f].properties&&(g.properties=a.layers[f].properties);for(var h,i,j,k,l=0,m=[],n=[],o=0,p=a.layers[f].data.length;p>o;o++){if(h=0,i=!1,k=a.layers[f].data[o],k>536870912)switch(j=0,k>2147483648&&(k-=2147483648,j+=4),k>1073741824&&(k-=1073741824,j+=2),k>536870912&&(k-=536870912,j+=1),j){case 5:h=Math.PI/2;break;case 6:h=Math.PI;break;case 3:h=3*Math.PI/2;break;case 4:h=0,i=!0;break;case 7:h=Math.PI/2,i=!0;break;case 2:h=Math.PI,i=!0;break;case 1:h=3*Math.PI/2,i=!0}k>0?(m.push(new c.Tile(g,k,l,n.length,a.tilewidth,a.tileheight)),m[m.length-1].rotation=h,m[m.length-1].flipped=i):m.push(new c.Tile(g,-1,l,n.length,a.tilewidth,a.tileheight)),l++,l===a.layers[f].width&&(n.push(m),l=0,m=[])}g.data=n,e.push(g)}d.layers=e;for(var q=[],f=0;f<a.layers.length;f++)if("imagelayer"===a.layers[f].type){var r={name:a.layers[f].name,image:a.layers[f].image,x:a.layers[f].x,y:a.layers[f].y,alpha:a.layers[f].opacity,visible:a.layers[f].visible,properties:{}};a.layers[f].properties&&(r.properties=a.layers[f].properties),q.push(r)}d.images=q;for(var s=[],t=[],f=0;f<a.tilesets.length;f++){var u=a.tilesets[f];if(u.image){var v=new c.Tileset(u.name,u.firstgid,u.tilewidth,u.tileheight,u.margin,u.spacing,u.properties);u.tileproperties&&(v.tileProperties=u.tileproperties),v.updateTileData(u.imagewidth,u.imageheight),s.push(v)}else{var w=new c.ImageCollection(u.name,u.firstgid,u.tilewidth,u.tileheight,u.margin,u.spacing,u.properties);for(var f in u.tiles){var r=u.tiles[f].image,k=u.firstgid+parseInt(f,10);w.addImage(k,r)}t.push(w)}}d.tilesets=s,d.imagecollections=t;for(var x={},y={},f=0;f<a.layers.length;f++)if("objectgroup"===a.layers[f].type){x[a.layers[f].name]=[],y[a.layers[f].name]=[];for(var z=0,p=a.layers[f].objects.length;p>z;z++)if(a.layers[f].objects[z].gid){var A={gid:a.layers[f].objects[z].gid,name:a.layers[f].objects[z].name,type:a.layers[f].objects[z].hasOwnProperty("type")?a.layers[f].objects[z].type:"",x:a.layers[f].objects[z].x,y:a.layers[f].objects[z].y,visible:a.layers[f].objects[z].visible,properties:a.layers[f].objects[z].properties};a.layers[f].objects[z].rotation&&(A.rotation=a.layers[f].objects[z].rotation),x[a.layers[f].name].push(A)}else if(a.layers[f].objects[z].polyline){var A={name:a.layers[f].objects[z].name,type:a.layers[f].objects[z].type,x:a.layers[f].objects[z].x,y:a.layers[f].objects[z].y,width:a.layers[f].objects[z].width,height:a.layers[f].objects[z].height,visible:a.layers[f].objects[z].visible,properties:a.layers[f].objects[z].properties};a.layers[f].objects[z].rotation&&(A.rotation=a.layers[f].objects[z].rotation),A.polyline=[];for(var B=0;B<a.layers[f].objects[z].polyline.length;B++)A.polyline.push([a.layers[f].objects[z].polyline[B].x,a.layers[f].objects[z].polyline[B].y]);y[a.layers[f].name].push(A),x[a.layers[f].name].push(A)}else if(a.layers[f].objects[z].polygon){var A=b(a.layers[f].objects[z],["name","type","x","y","visible","rotation","properties"]);A.polygon=[];for(var B=0;B<a.layers[f].objects[z].polygon.length;B++)A.polygon.push([a.layers[f].objects[z].polygon[B].x,a.layers[f].objects[z].polygon[B].y]);x[a.layers[f].name].push(A)}else if(a.layers[f].objects[z].ellipse){var A=b(a.layers[f].objects[z],["name","type","ellipse","x","y","width","height","visible","rotation","properties"]);x[a.layers[f].name].push(A)}else{var A=b(a.layers[f].objects[z],["name","type","x","y","width","height","visible","rotation","properties"]);A.rectangle=!0,x[a.layers[f].name].push(A)}}d.objects=x,d.collision=y,d.tiles=[];for(var f=0;f<d.tilesets.length;f++)for(var u=d.tilesets[f],l=u.tileMargin,C=u.tileMargin,D=0,E=0,F=0,o=u.firstgid;o<u.firstgid+u.total&&(d.tiles[o]=[l,C,f],l+=u.tileWidth+u.tileSpacing,D++,D!==u.total)&&(E++,E!==u.columns||(l=u.tileMargin,C+=u.tileHeight+u.tileSpacing,E=0,F++,F!==u.rows));o++);for(var g,G,H,u,f=0;f<d.layers.length;f++){g=d.layers[f];for(var I=0;I<g.data.length;I++){m=g.data[I];for(var J=0;J<m.length;J++)G=m[J],G.index<0||(H=d.tiles[G.index][2],u=d.tilesets[H],u.tileProperties&&u.tileProperties[G.index-u.firstgid]&&(G.properties=c.Utils.mixin(u.tileProperties[G.index-u.firstgid],G.properties)))}}return d}},c.Tileset=function(a,b,c,d,e,f,g){(void 0===c||0>=c)&&(c=32),(void 0===d||0>=d)&&(d=32),void 0===e&&(e=0),void 0===f&&(f=0),this.name=a,this.firstgid=0|b,this.tileWidth=0|c,this.tileHeight=0|d,this.tileMargin=0|e,this.tileSpacing=0|f,this.properties=g||{},this.image=null,this.rows=0,this.columns=0,this.total=0,this.drawCoords=[]},c.Tileset.prototype={draw:function(a,b,c,d){var e=d-this.firstgid<<1;e>=0&&e+1<this.drawCoords.length&&a.drawImage(this.image,this.drawCoords[e],this.drawCoords[e+1],this.tileWidth,this.tileHeight,b,c,this.tileWidth,this.tileHeight)},containsTileIndex:function(a){return a>=this.firstgid&&a<this.firstgid+this.total},setImage:function(a){this.image=a,this.updateTileData(a.width,a.height)},setSpacing:function(a,b){this.tileMargin=0|a,this.tileSpacing=0|b,this.image&&this.updateTileData(this.image.width,this.image.height)},updateTileData:function(a,b){var c=(b-2*this.tileMargin+this.tileSpacing)/(this.tileHeight+this.tileSpacing),d=(a-2*this.tileMargin+this.tileSpacing)/(this.tileWidth+this.tileSpacing);(c%1!==0||d%1!==0)&&console.warn("Phaser.Tileset - image tile area is not an even multiple of tile size"),c=Math.floor(c),d=Math.floor(d),(this.rows&&this.rows!==c||this.columns&&this.columns!==d)&&console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ"),this.rows=c,this.columns=d,this.total=c*d,this.drawCoords.length=0;for(var e=this.tileMargin,f=this.tileMargin,g=0;g<this.rows;g++){for(var h=0;h<this.columns;h++)this.drawCoords.push(e),this.drawCoords.push(f),e+=this.tileWidth+this.tileSpacing;e=this.tileMargin,f+=this.tileHeight+this.tileSpacing}}},c.Tileset.prototype.constructor=c.Tileset,c.Particles=function(a){this.game=a,this.emitters={},this.ID=0},c.Particles.prototype={add:function(a){return this.emitters[a.name]=a,a},remove:function(a){delete this.emitters[a.name]},update:function(){for(var a in this.emitters)this.emitters[a].exists&&this.emitters[a].update()}},c.Particles.prototype.constructor=c.Particles,c.Particles.Arcade={},c.Particles.Arcade.Emitter=function(a,b,d,e){this.maxParticles=e||50,c.Group.call(this,a),this.name="emitter"+this.game.particles.ID++,this.type=c.EMITTER,this.physicsType=c.GROUP,this.area=new c.Rectangle(b,d,1,1),this.minParticleSpeed=new c.Point(-100,-100),this.maxParticleSpeed=new c.Point(100,100),this.minParticleScale=1,this.maxParticleScale=1,this.scaleData=null,this.minRotation=-360,this.maxRotation=360,this.minParticleAlpha=1,this.maxParticleAlpha=1,this.alphaData=null,this.gravity=100,this.particleClass=c.Particle,this.particleDrag=new c.Point,this.angularDrag=0,this.frequency=100,this.lifespan=2e3,this.bounce=new c.Point,this.on=!1,this.particleAnchor=new c.Point(.5,.5),this.blendMode=c.blendModes.NORMAL,this.emitX=b,this.emitY=d,this.autoScale=!1,this.autoAlpha=!1,this.particleBringToTop=!1,this.particleSendToBack=!1,this._minParticleScale=new c.Point(1,1),this._maxParticleScale=new c.Point(1,1),this._quantity=0,this._timer=0,this._counter=0,this._flowQuantity=0,this._flowTotal=0,this._explode=!0,this._frames=null},c.Particles.Arcade.Emitter.prototype=Object.create(c.Group.prototype),c.Particles.Arcade.Emitter.prototype.constructor=c.Particles.Arcade.Emitter,c.Particles.Arcade.Emitter.prototype.update=function(){if(this.on&&this.game.time.time>=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(var a=0;a<this._flowQuantity;a++)if(this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._quantity>0&&this._counter>=this._quantity&&(this.on=!1));for(var a=this.children.length;a--;)this.children[a].exists&&this.children[a].update()},c.Particles.Arcade.Emitter.prototype.makeParticles=function(a,b,c,d,e){void 0===b&&(b=0),void 0===c&&(c=this.maxParticles),void 0===d&&(d=!1),void 0===e&&(e=!1);var f,g=0,h=a,i=b;for(this._frames=b,c>this.maxParticles&&(this.maxParticles=c);c>g;)Array.isArray(a)&&(h=this.game.rnd.pick(a)),Array.isArray(b)&&(i=this.game.rnd.pick(b)),f=new this.particleClass(this.game,0,0,h,i),this.game.physics.arcade.enable(f,!1),d?(f.body.checkCollision.any=!0,f.body.checkCollision.none=!1):f.body.checkCollision.none=!0,f.body.collideWorldBounds=e,f.body.skipQuadTree=!0,f.exists=!1,f.visible=!1,f.anchor.copyFrom(this.particleAnchor),this.add(f),g++;return this},c.Particles.Arcade.Emitter.prototype.kill=function(){this.on=!1,this.alive=!1,this.exists=!1},c.Particles.Arcade.Emitter.prototype.revive=function(){this.alive=!0,this.exists=!0},c.Particles.Arcade.Emitter.prototype.explode=function(a,b){this._flowTotal=0,this.start(!0,a,0,b,!1)},c.Particles.Arcade.Emitter.prototype.flow=function(a,b,c,d,e){(void 0===c||0===c)&&(c=1),void 0===d&&(d=-1),void 0===e&&(e=!0),c>this.maxParticles&&(c=this.maxParticles),this._counter=0,this._flowQuantity=c,this._flowTotal=d,e?(this.start(!0,a,b,c),this._counter+=c,this.on=!0,this._timer=this.game.time.time+b*this.game.time.slowMotion):this.start(!1,a,b,c)},c.Particles.Arcade.Emitter.prototype.start=function(a,b,c,d,e){if(void 0===a&&(a=!0),void 0===b&&(b=0),(void 0===c||null===c)&&(c=250),void 0===d&&(d=0),void 0===e&&(e=!1),d>this.maxParticles&&(d=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=b,this.frequency=c,a||e)for(var f=0;d>f;f++)this.emitParticle();else this.on=!0,this._quantity+=d,this._counter=0,this._timer=this.game.time.time+c*this.game.time.slowMotion},c.Particles.Arcade.Emitter.prototype.emitParticle=function(){var a=this.getFirstExists(!1);return null===a?!1:(this.width>1||this.height>1?a.reset(this.game.rnd.integerInRange(this.left,this.right),this.game.rnd.integerInRange(this.top,this.bottom)):a.reset(this.emitX,this.emitY),a.angle=0,a.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(a):this.particleSendToBack&&this.sendToBack(a),this.autoScale?a.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?a.scale.set(this.game.rnd.realInRange(this.minParticleScale,this.maxParticleScale)):(this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y)&&a.scale.set(this.game.rnd.realInRange(this._minParticleScale.x,this._maxParticleScale.x),this.game.rnd.realInRange(this._minParticleScale.y,this._maxParticleScale.y)),a.frame=Array.isArray("object"===this._frames)?this.game.rnd.pick(this._frames):this._frames,this.autoAlpha?a.setAlphaData(this.alphaData):a.alpha=this.game.rnd.realInRange(this.minParticleAlpha,this.maxParticleAlpha),a.blendMode=this.blendMode,a.body.updateBounds(),a.body.bounce.setTo(this.bounce.x,this.bounce.y),a.body.velocity.x=this.game.rnd.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),a.body.velocity.y=this.game.rnd.between(this.minParticleSpeed.y,this.maxParticleSpeed.y),a.body.angularVelocity=this.game.rnd.between(this.minRotation,this.maxRotation),a.body.gravity.y=this.gravity,a.body.drag.x=this.particleDrag.x,a.body.drag.y=this.particleDrag.y,a.body.angularDrag=this.angularDrag,a.onEmit(),!0)},c.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),c.Group.prototype.destroy.call(this,!0,!1)},c.Particles.Arcade.Emitter.prototype.setSize=function(a,b){this.area.width=a,this.area.height=b},c.Particles.Arcade.Emitter.prototype.setXSpeed=function(a,b){a=a||0,b=b||0,this.minParticleSpeed.x=a,this.maxParticleSpeed.x=b},c.Particles.Arcade.Emitter.prototype.setYSpeed=function(a,b){a=a||0,b=b||0,this.minParticleSpeed.y=a,this.maxParticleSpeed.y=b},c.Particles.Arcade.Emitter.prototype.setRotation=function(a,b){a=a||0,b=b||0,this.minRotation=a,this.maxRotation=b},c.Particles.Arcade.Emitter.prototype.setAlpha=function(a,b,d,e,f){if(void 0===a&&(a=1),void 0===b&&(b=1),void 0===d&&(d=0),void 0===e&&(e=c.Easing.Linear.None),void 0===f&&(f=!1),this.minParticleAlpha=a,this.maxParticleAlpha=b,this.autoAlpha=!1,d>0&&a!==b){var g={v:a},h=this.game.make.tween(g).to({v:b},d,e);h.yoyo(f),this.alphaData=h.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}},c.Particles.Arcade.Emitter.prototype.setScale=function(a,b,d,e,f,g,h){if(void 0===a&&(a=1),void 0===b&&(b=1),void 0===d&&(d=1),void 0===e&&(e=1),void 0===f&&(f=0),void 0===g&&(g=c.Easing.Linear.None),void 0===h&&(h=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(a,d),this._maxParticleScale.set(b,e),this.autoScale=!1,f>0&&(a!==b||d!==e)){var i={x:a,y:d},j=this.game.make.tween(i).to({x:b,y:e},f,g);j.yoyo(h),this.scaleData=j.generateData(60),this.scaleData.reverse(),this.autoScale=!0}},c.Particles.Arcade.Emitter.prototype.at=function(a){a.center?(this.emitX=a.center.x,this.emitY=a.center.y):(this.emitX=a.world.x+a.anchor.x*a.width,this.emitY=a.world.y+a.anchor.y*a.height)},Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(a){this.area.width=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(a){this.area.height=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(a){this.emitX=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(a){this.emitY=a}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(c.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),c.Video=function(a,b,d){if(void 0===b&&(b=null),void 0===d&&(d=null),this.game=a,this.key=b,this.width=0,this.height=0,this.type=c.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new c.Signal,this.onChangeSource=new c.Signal,this.onComplete=new c.Signal,this.onAccess=new c.Signal,this.onError=new c.Signal,this.onTimeout=new c.Signal,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._autoplay=!1,b&&this.game.cache.checkVideoKey(b)){var e=this.game.cache.getVideo(b);e.isBlob?this.createVideoFromBlob(e.data):this.video=e.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else d&&this.createVideoFromURL(d,!1);this.video&&!d?(this.baseTexture=new PIXI.BaseTexture(this.video),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(PIXI.TextureCache.__default.baseTexture.source),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new c.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==b&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,c.BitmapData&&(this.snapshot=new c.BitmapData(this.game,"",this.width,this.height)),!this.game.device.cocoonJS&&(this.game.device.iOS||this.game.device.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock?this.setTouchLock():e&&(e.locked=!1)},c.Video.prototype={connectToMediaStream:function(a,b){return a&&b&&(this.video=a,this.videoStream=b,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(a,b,c){if(void 0===a&&(a=!1),void 0===b&&(b=null),void 0===c&&(c=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&this.videoStream.stop(),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==b&&(this.video.width=b),null!==c&&(this.video.height=c),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:a,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(d){this.getUserMediaError(d)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(a){clearTimeout(this._timeOutID),this.onError.dispatch(this,a)},getUserMediaSuccess:function(a){clearTimeout(this._timeOutID),this.videoStream=a,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=a:this.video.src=window.URL&&window.URL.createObjectURL(a)||a;var b=this;this.video.onloadeddata=function(){function a(){if(c>0)if(b.video.videoWidth>0){var d=b.video.videoWidth,e=b.video.videoHeight;isNaN(b.video.videoHeight)&&(e=d/(4/3)),b.video.play(),b.isStreaming=!0,b.baseTexture.source=b.video,b.updateTexture(null,d,e),b.onAccess.dispatch(b)}else window.setTimeout(a,500);else console.warn("Unable to connect to video stream. Webcam error?");c--}var c=10;a()}},createVideoFromBlob:function(a){var b=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(a){b.updateTexture(a)},!0),this.video.src=window.URL.createObjectURL(a),this.video.canplay=!0,this},createVideoFromURL:function(a,b){return void 0===b&&(b=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,b&&this.video.setAttribute("autoplay","autoplay"),this.video.src=a,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=a,this},updateTexture:function(a,b,c){var d=!1;(void 0===b||null===b)&&(b=this.video.videoWidth,d=!0),(void 0===c||null===c)&&(c=this.video.videoHeight),this.width=b,this.height=c,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(b,c),this.texture.frame.resize(b,c),this.texture.width=b,this.texture.height=c,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(b,c),d&&null!==this.key&&(this.onChangeSource.dispatch(this,b,c),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(a,b){return void 0===a&&(a=!1),void 0===b&&(b=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this.video.addEventListener("ended",this.complete.bind(this),!0),this.video.loop=a?"loop":"",this.video.playbackRate=b,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):this.video.addEventListener("playing",this.playHandler.bind(this),!0)),this.video.play(),this.onPlay.dispatch(this,a,b)),this},playHandler:function(){this.video.removeEventListener("playing",this.playHandler.bind(this)),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this.complete.bind(this)),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(a){if(Array.isArray(a))for(var b=0;b<a.length;b++)a[b].loadTexture&&a[b].loadTexture(this);else a.loadTexture(this);return this},addToWorld:function(a,b,c,d,e,f){e=e||1,f=f||1;var g=this.game.add.image(a,b,this);return g.anchor.set(c,d),g.scale.set(e,f),g},render:function(){!this.disableTextureUpload&&this.playing&&this.baseTexture.dirty()},setMute:function(){this._muted||(this._muted=!0,this.video.muted=!0)},unsetMute:function(){this._muted&&!this._codeMuted&&(this._muted=!1,this.video.muted=!1)},setPause:function(){this._paused||this.touchLocked||(this._paused=!0,this.video.pause())},setResume:function(){!this._paused||this._codePaused||this.touchLocked||(this._paused=!1,this.video.ended||this.video.play())},changeSource:function(a,b){return void 0===b&&(b=!0),this.texture.valid=!1,this.video.pause(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.video.src=a,this.video.load(),this._autoplay=b,b||(this.paused=!0),this},checkVideoProgress:function(){4===this.video.readyState?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming))},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate),this.key){var a=this.game.cache.getVideo(this.key);a&&!a.isBlob&&(a.locked=!1)}return!0},grab:function(a,b,c){return void 0===a&&(a=!1),void 0===b&&(b=1),void 0===c&&(c=null),null===this.snapshot?void console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable"):(a&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,b,c),this.snapshot)},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(c.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(a){this.video.currentTime=a}}),Object.defineProperty(c.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(c.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(c.Video.prototype,"mute",{get:function(){return this._muted},set:function(a){if(a=a||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(c.Video.prototype,"paused",{get:function(){return this._paused},set:function(a){if(a=a||null,!this.touchLocked)if(a){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(c.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(a){0>a?a=0:a>1&&(a=1),this.video&&(this.video.volume=a)}}),Object.defineProperty(c.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(a){this.video&&(this.video.playbackRate=a)}}),Object.defineProperty(c.Video.prototype,"loop",{get:function(){return this.video?this.video.loop:!1},set:function(a){a&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(c.Video.prototype,"playing",{get:function(){return!(this.video.paused&&this.video.ended)}}),c.Video.prototype.constructor=c.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=c.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=c.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new PIXI.Matrix),void 0===PIXI.RenderTexture.tempMatrix&&(PIXI.RenderTexture.tempMatrix=new PIXI.Matrix),void 0===PIXI.Graphics.POLY&&(PIXI.Graphics.POLY=c.POLYGON,PIXI.Graphics.RECT=c.RECTANGLE,PIXI.Graphics.CIRC=c.CIRCLE,PIXI.Graphics.ELIP=c.ELLIPSE,PIXI.Graphics.RREC=c.ROUNDEDRECTANGLE),PIXI.TextureSilentFail=!0,"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=c),exports.Phaser=c):"undefined"!=typeof define&&define.amd?define("Phaser",function(){return b.Phaser=c}()):b.Phaser=c,c}.call(this);
+//# sourceMappingURL=phaser.map
\ No newline at end of file
diff --git a/js/plants/Character.js b/js/plants/Character.js
new file mode 100644
index 0000000..92fc540
--- /dev/null
+++ b/js/plants/Character.js
@@ -0,0 +1,34 @@
+function Character(manager, column, row, sprite_x, sprite_y) {
+    this.type = 'character';
+	this.manager = manager;
+	
+    this.props = new Props({
+		column: column,
+		row: row,
+		cooldown: 1000,
+		damage: 0,
+		speed: 100,
+		health: 2
+	});
+
+	this.sprite = game.add.sprite(sprite_x, sprite_y, 'plants');
+	this.sprite.smoothed = false;
+	this.sprite.width = 64;
+	this.sprite.height = 64;
+	
+	//Common functions
+	
+	this.hit = function(damage){
+		// Decrease health by the amount of damage, but never allow health to drop below zero
+	    this.props.health = Math.max(this.props.health - damage, 0);
+	    
+	    // If health is zero, mark the plant as dead
+		if (this.props.health <= 0) {
+			this.props.die = true;
+		}
+	};
+	
+	this.init();
+}
+
+Character.__proto__ = Component('character');
\ No newline at end of file
diff --git a/js/plants/Nut.js b/js/plants/Nut.js
index 3ca9523..7eb44dc 100644
--- a/js/plants/Nut.js
+++ b/js/plants/Nut.js
@@ -1,12 +1,23 @@
+function Nut() {
+    Character.apply(this, arguments);
+}
+
 Nut.prototype.init = function (){
 	this.last_action_time = 0;
 	this.props.health = 14;
+	
+	this.sprite.animations.add('idle_1', ['nut_0'], 2, true, false);
+	this.sprite.animations.add('idle_2', ['nut_1'], 2, true, false);
+	this.sprite.animations.add('idle_3', ['nut_2'], 2, true, false);
+	this.sprite.animations.add('idle_4', ['nut_3'], 2, true, false);
+	this.sprite.animations.add('idle_5', ['nut_4'], 2, true, false);
+	this.sprite.animations.add('idle_6', ['nut_5'], 2, true, false);
+	this.sprite.animations.add('idle_7', ['nut_6'], 2, true, false);
+	this.sprite.animations.play('idle_0', 2, true);
 };
 
 Nut.prototype.update = function() {
-
 	// Update sprite based on health remaining
 	var idleAnimationIndex = (8 - (this.props.health / 2)); // maps health in range of 1-7 (1 means full health, 7 means almost no health)
-	this.sprite.animations.play('idle' + idleAnimationIndex.toString(), 1, false);
-
+	this.sprite.animations.play('idle_' + idleAnimationIndex.toString(), 1, false);
 };
\ No newline at end of file
diff --git a/js/plants/Peashooter.js b/js/plants/Peashooter.js
index ce4850e..39b806e 100644
--- a/js/plants/Peashooter.js
+++ b/js/plants/Peashooter.js
@@ -1,3 +1,7 @@
+function Peashooter() {
+    Character.apply(this, arguments);
+}
+
 Peashooter.prototype.init = function (){
 	this.sprite.animations.add('idle', ['peashooter_3', 'peashooter_0'], 2, true, false);
 	this.sprite.animations.add('shoot', ['peashooter_0', 'peashooter_1', 'peashooter_2'], 2, true, false);
@@ -9,7 +13,7 @@ Peashooter.prototype.init = function (){
 Peashooter.prototype.update = function() {
 
 	var time_since = game.time.now - this.props.cooldown_timer;
-
+	
 	if(this.manager.campersInRow(this.props.row) > 0) {
 
 		var currentAnim = this.sprite.animations.currentAnim;
diff --git a/js/plants/Plant.js b/js/plants/Plant.js
deleted file mode 100644
index c9fa2fc..0000000
--- a/js/plants/Plant.js
+++ /dev/null
@@ -1,36 +0,0 @@
-function Character(manager, column, row, sprite, sprite_x, sprite_y) {
-    
-	this.manager = manager;
-	
-    this.props = new Props({
-		column: column,
-		row: row,
-		cooldown: 1000,
-		damage: 0,
-		speed: 100,
-		health: 2
-	});
-
-	this.sprite = game.add.sprite(sprite_x, sprite_y, 'plants');
-	this.sprite.smoothed = false;
-	this.sprite.width = 64;
-	this.sprite.height = 64;
-}
-
-//Common functions
-
-Character.prototype.hit = function (damage) {
-	// Decrease health by the amount of damage, but never allow health to drop below zero
-    this.props.health = Math.max(this.props.health - damage, 0);
-    
-    // If health is zero, mark the plant as dead
-	if (this.props.health === 0) {
-		this.props.die = true;
-	}
-}
-
-//PlantTypes
-
-Sunflower 	= Character;
-Peashooter 	= Character;
-Nut 		= Character;
\ No newline at end of file
diff --git a/js/plants/Sunflower.js b/js/plants/Sunflower.js
index a12dd00..c21b724 100644
--- a/js/plants/Sunflower.js
+++ b/js/plants/Sunflower.js
@@ -1,8 +1,10 @@
-Sunflower.prototype.init = function (){
+function Sunflower() {
+    Character.apply(this, arguments);
+}
+
+Sunflower.prototype.init = function () {
 	
-	this.props = new Props({
-		cooldown: (Math.random() * 5000) + 5000
-	});
+	this.props.cooldown = (Math.random() * 5000) + 5000;
 
 	this.sprite.animations.add('idle', ['sunflower_3', 'sunflower_0'], 2, true, false);
 	this.sprite.animations.play('idle', 2, true);
@@ -13,7 +15,7 @@ Sunflower.prototype.update = function() {
 	var time_since = game.time.now - this.props.cooldown_timer;
 
 	if (time_since >= this.props.cooldown) {
-		this.next_sun_spawn_ms = (Math.random() * 5000) + 5000;
+		this.props.cooldown = (Math.random() * 5000) + 5000;
 		this.props.cooldown_timer = game.time.now;
 		this.manager.spawnSun(this.props.column, this.props.row);
 	}
diff --git a/js/utils/Class.js b/js/utils/Class.js
new file mode 100644
index 0000000..56419fd
--- /dev/null
+++ b/js/utils/Class.js
@@ -0,0 +1,79 @@
+var PvZ = PvZ || {};
+
+
+// *** Example of creating a simple class within the PvZ namespace ! (PS: we should have namespaces Plants Vs Zombies === PvZ)
+
+// var Game = PvZ.Class.create('PvZ.Game', function Game(options, dependencies) {
+
+//     this.dependencies = dependencies;
+//     this.options = PvZ.Utils.extend({}, this.options, options);
+//     this.config = PvZ.Config;
+
+//     this.init();
+// });
+
+// *** this is how you extend a random class lets say you want to make a new player class
+
+// var Player = PvZ.Class.extend(PvZ.Game.Entity, 'PvZ.Game.Entity.Player', PvZ.Game.Entity); <--- assuming you have entities i think you guys call them characters
+
+// 	    Player.prototype.init = function() {
+// 		    this.controller = new O.Game.Controller;
+// 		    PvZ.Logger.log("Player Created");
+
+// 		    this.x = this.canvas.width / 2;
+//          this.y = this.canvas.height / 2;
+
+//          this.radius = 70;
+//          this.speed = 10;
+//      }
+
+PvZ.Class = (function() {
+	function makeNameSpace(namespace, constructor){
+		var parts = namespace.split('.');
+		var parent = window;
+
+		//loop thorugh namespace parts
+		var part;
+		for (var i = 0; i < parts.length; i++) {
+			part = parts[i];
+			if (typeof parent[part] === 'undefined') {
+				if(i === parts.length - 1 && typeof constructor === 'function' ){
+					parent[part] = constructor;
+				}else{
+					parent[part] = {};
+				}
+			}
+			parent = parent[part];
+		};
+
+		return parent;
+	}
+
+	return {
+		create: function(namespace, constructor) {
+			var newClass = makeNameSpace(namespace, constructor);
+			newClass = constructor;
+			newClass.prototype.fullClassName = namespace;
+			newClass.prototype.toString = function() {
+				return namespace;
+			}
+
+			return newClass;
+		},
+		extend: function(parent, namespace, constructor) {
+			
+			var F = function() {};
+			try{
+				F.prototype = parent.prototype;
+			} catch (e){
+				throw new Error('Parent class does not exist..');
+			}
+
+			constructor.prototype = new F();
+			constructor.prototype.parent = parent;
+			constructor.prototype.constructor = constructor;
+			return PvZ.Class.create(namespace, constructor);
+		}
+	}
+
+})();
\ No newline at end of file
diff --git a/js/utils/LoadPhaser.js b/js/utils/LoadPhaser.js
new file mode 100644
index 0000000..605c1c4
--- /dev/null
+++ b/js/utils/LoadPhaser.js
@@ -0,0 +1,7 @@
+var isPhaserMinified = false;
+
+if (isPhaserMinified) {
+    loadScript("../phaser/phaser.min.js");
+} else {
+    loadScript("../phaser/phaser.js");
+}
\ No newline at end of file
diff --git a/js/utils/Resource.js b/js/utils/Resource.js
new file mode 100644
index 0000000..e69de29
diff --git a/js/utils/Util.js b/js/utils/Util.js
new file mode 100644
index 0000000..cdce0e0
--- /dev/null
+++ b/js/utils/Util.js
@@ -0,0 +1,49 @@
+function Util(){}
+
+Util.prototype.deepExtend = function(out) {
+        out = out || {};
+        for (var i = 1; i < arguments.length; i++) {
+            var obj = arguments[i];
+
+            if (!obj)
+                continue;
+
+            for (var key in obj) {
+                if (obj.hasOwnProperty(key)) {
+                    if (typeof obj[key] === 'object')
+                        this.extend(out[key], obj[key]);
+                    else
+                        out[key] = obj[key];
+                }
+            }
+        }
+
+    return out;
+};
+
+Util.prototype.extend = function(out) {
+    out = out || {};
+
+    for (var i = 1; i < arguments.length; i++) {
+        if (!arguments[i])
+            continue;
+
+        for (var key in arguments[i]) {
+            if (arguments[i].hasOwnProperty(key))
+                out[key] = arguments[i][key];
+        }
+    }
+
+    return out;
+};
+
+Util.prototype.generateUUID = function() {
+    var d = new Date().getTime();
+    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
+        var r = (d + Math.random() * 16) % 16 | 0;
+        d = Math.floor(d / 16);
+        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
+    });
+    return uuid;
+};
+
