/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 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 {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);
    }

};


'  if ( gl_FragCoord.x < uClipping.x && gl_FragCoord.y > uClipping.y)',

'    gl_FragColor = texture2D(uImageSampler, vTexCoord) * uAlpha;',

'  if ( gl_FragCoord.x >= uClipLoc.x && gl_FragCoord.y >= uClipLoc.y && gl_FragCoord.x < uClipLimit.x && gl_FragCoord.y > uClipLimit.y )',

/**
* @author       Richard Davey <rich@photonstorm.com>
* @author       Pete Baron <pete@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* A TilemapLayerGL is a PIXI.Tilemap that renders a specific TileLayer of a Tilemap using the PIXI WebGL renderer.
*
* NOTE: This is a close duplicate of Phaser.TilemapLayer class, modified to support WebGL rendering, it may be possible to merge the two classes
* although that will probably incur performance penalties due to some fundamental differences in the set-up before rendering.
*
* Since a PIXI.Tilemap is a PIXI.DisplayObjectContainer it can be moved around the display list, 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.TilemapLayerGL
* @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.TilemapLayerGL = function (game, tilemap, index, width, height) {

    this.game = game;

    /**
    * 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 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 {float} [overdrawRatio=0.20] - Over Draw ratio.
    *
    * @default
    */
    this.renderSettings = {
        overdrawRatio: 0.20
    };

    /**
    * @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
    */
    var tileset = this.layer.tileset || this.map.tilesets[0];

    this._mc = {

        // Used to bypass rendering without reliance on `dirty` and detect changes.
        scrollX: 0,
        scrollY: 0,
        renderWidth: 0,
        renderHeight: 0,

        // dimensions of tiles in the original tilemap (the one holding all the tile indices)
        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.

        // dimensions of tiles in this tileset (may not match the original tilemap)
        cw: tileset.tileWidth,
        ch: tileset.tileHeight,

        // the tileset for this layer
        tileset: tileset,

        // Cached tilesets from index -> Tileset
        tilesets: []

    };

    /**
     * The rendering mode (used by PIXI.Tilemap).  Modes are: 0 - render entire screen of tiles, 1 - render entire map of tiles
     * TODO: make some constants for the rendering modes
     * @property {number} _renderMode
     * @private
     */
    this._renderMode = 0;

    /**
    * 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 = [];

    // get PIXI textures for each tileset source image
    var baseTexture = new PIXI.BaseTexture(tileset.image);

    PIXI.Tilemap.call(this, new PIXI.Texture(baseTexture), width | 0, height | 0, this.map.width, this.map.height, this._mc.tileset.tileWidth, this._mc.tileset.tileHeight, this.layer);

    Phaser.Component.Core.init.call(this, game, 0, 0, null, null);

    // must be set *after* the Core.init
    this.fixedToCamera = true;

};

// constructor: extends PIXI.Tilemap
Phaser.TilemapLayerGL.prototype = Object.create(PIXI.Tilemap.prototype);
Phaser.TilemapLayerGL.prototype.constructor = Phaser.TilemapLayerGL;

//  Only one Phaser component used
Phaser.Component.Core.install.call(Phaser.TilemapLayerGL.prototype, [
    'FixedToCamera'
]);

Phaser.TilemapLayerGL.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;

/**
* Automatically called by World.preUpdate.
*
* @method Phaser.TilemapLayerGL#preUpdate
*/
Phaser.TilemapLayerGL.prototype.preUpdate = function () {

    return this.preUpdateCore();

};

/**
* Automatically called by World.postUpdate. Handles camera scrolling.
*
* @method Phaser.TilemapLayerGL#postUpdate
* @protected
*/
Phaser.TilemapLayerGL.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();

};

/**
* Destroys this TilemapLayerGL.
*
* @method Phaser.TilemapLayerGL#destroy
*/
Phaser.TilemapLayerGL.prototype.destroy = function() {

    Phaser.Component.Destroy.prototype.destroy.call(this);

};

/**
* Resizes the internal dimensions used by this TilemapLayerGL during rendering.
*
* @method Phaser.TilemapLayerGL#resize
* @param {number} width - The new width of the TilemapLayerGL
* @param {number} height - The new height of the TilemapLayerGL
*/
Phaser.TilemapLayerGL.prototype.resize = function (width, height) {

    this.displayWidth = width;
    this.displayHeight = height;
    this.dirty = true;

};

/**
* Sets the world size to match the size of this layer.
*
* @method Phaser.TilemapLayerGL#resizeWorld
* @public
*/
Phaser.TilemapLayerGL.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.TilemapLayerGL#_fixX
* @private
* @param {number} x - x coordinate in camera space
* @return {number} x coordinate in scrollFactor-adjusted dimensions
*/
Phaser.TilemapLayerGL.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.TilemapLayerGL#_unfixX
* @private
* @param {number} x - x coordinate in scrollFactor-adjusted dimensions
* @return {number} x coordinate in camera space
*/
Phaser.TilemapLayerGL.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.TilemapLayerGL#_fixY
* @private
* @param {number} y - y coordinate in camera space
* @return {number} y coordinate in scrollFactor-adjusted dimensions
*/
Phaser.TilemapLayerGL.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.TilemapLayerGL#_unfixY
* @private
* @param {number} y - y coordinate in scrollFactor-adjusted dimensions
* @return {number} y coordinate in camera space
*/
Phaser.TilemapLayerGL.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.TilemapLayerGL#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.TilemapLayerGL.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.TilemapLayerGL#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.TilemapLayerGL.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.TilemapLayerGL#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.TilemapLayerGL.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.TilemapLayerGL#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.TilemapLayerGL.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.TilemapLayerGL#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.TilemapLayerGL.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;

    //  Discard old results before storing the new ones
    this._results = [];

    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();

};

/**
* The TilemapLayerGL 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.TilemapLayerGL#resetTilesetCache
* @public
*/
Phaser.TilemapLayerGL.prototype.resetTilesetCache = function () {

    this._mc.tilesets = [];

};

/**
 * This method will set the scale of the tilemap as well as update the underlying block data of this layer.
 *
 * @method Phaser.TilemapLayerGL#setScale
 * @param {number} [xScale=1] - The scale factor along the X-plane
 * @param {number} [yScale] - The scale factor along the Y-plane
 */
Phaser.TilemapLayerGL.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);

};

/**
* 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.TilemapLayerGL#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.TilemapLayerGL.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom, offx, offy) {

    var width = this.layer.width;
    var height = this.layer.height;
    var tw = this._mc.tileWidth;
    var th = this._mc.tileHeight;

    offx = offx || 0;
    offy = offy || 0;

    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;

    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)
            {
                // skipping some tiles, add a degenerate marker into the batch list
                this._mc.tileset.addDegenerate(this.glBatch);
                continue;
            }

            var index = tile.index;

            this._mc.tileset.drawGl(this.glBatch, tx + offx, ty + offy, index, tile.alpha, tile.flippedVal);
        }

        // at end of each row, add a degenerate marker into the batch drawing list
        this._mc.tileset.addDegenerate(this.glBatch);
    }

};

/**
* Clear and render the entire canvas.
*
* @method Phaser.TilemapLayerGL#renderFull
* @private
*/
Phaser.TilemapLayerGL.prototype.renderFull = function () {

    var scrollX = this._mc.scrollX;
    var scrollY = this._mc.scrollY;

    var renderW = this.game._width;     //this.canvas.width;
    var renderH = this.game._height;    //this.canvas.height;

    var tw = this._mc.tileWidth;
    var th = this._mc.tileHeight;

    var cw = this._mc.cw;
    var ch = this._mc.ch;

    var left = Math.floor((scrollX - (cw - tw)) / tw);
    var right = Math.floor((renderW - 1 + scrollX) / tw);
    var top = Math.floor((scrollY - (ch - th)) / th);
    var bottom = Math.floor((renderH - 1 + scrollY) / th);

    this.glBatch = [];
    this.renderRegion(scrollX, scrollY, left, top, right, bottom, 0, -(ch - th));

};

/**
* Renders the tiles to the layer canvas and pushes to the display.
*
* @method Phaser.TilemapLayerGL#render
* @protected
*/
Phaser.TilemapLayerGL.prototype.render = function () {

    var redrawAll = false;

    if (!this.visible)
    {
        return;
    }

    if (this.dirty || this.layer.dirty)
    {
        this.layer.dirty = false;
        redrawAll = true;
    }

    //  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)
    {
        //  No reason to rebuild batch, looking at same thing and not invalidated.
        return;
    }

    mc.scrollX = scrollX;
    mc.scrollY = scrollY;

    this.renderFull();

    this.texture.baseTexture.dirty();

    this.dirty = false;

    return true;

};

/**
* 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.TilemapLayerGL
* @public
* @default false
*/
Object.defineProperty(Phaser.TilemapLayerGL.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.TilemapLayerGL
* @public
*/
Object.defineProperty(Phaser.TilemapLayerGL.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.TilemapLayerGL
* @public
*/
Object.defineProperty(Phaser.TilemapLayerGL.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.TilemapLayerGL
* @public
*/
Object.defineProperty(Phaser.TilemapLayerGL.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.TilemapLayerGL
* @public
*/
Object.defineProperty(Phaser.TilemapLayerGL.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>
* @author       Pete Baron <pete@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* This shader is used to render a batch of tiles stored as a tri-strip with
* degenerate triangles at the end of each row, or group of tiles (A group is a
* row of tiles with content followed by one or more empty tiles which are not
* drawn).
*
* Settings available are:
*
* uAlpha - the alpha blending factor for a batch draw
* uOffset - an offset for all tiles in this batch (e.g. screen shake)
* uCentreOffset - the offset to the center of the drawing area, in WebGL units (-1...1)
* uScale - the scaling factor for a batch draw
* uImageSampler - the source texture containing the tile images
* aPosition - the attribute set by the batch data for drawing location
*
* @class TilemapShader
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.TilemapShader = 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;

    this.fragmentSrc = [
        'precision lowp float;',
        'uniform sampler2D uImageSampler;',
        'uniform float uAlpha;',
        'uniform vec2 uClipping;',
        'varying vec2 vTexCoord;',
        'void main(void) {',
        '  if ( gl_FragCoord.x < uClipping.x && gl_FragCoord.y > uClipping.y)',
        '    gl_FragColor = texture2D(uImageSampler, vTexCoord) * uAlpha;',
        '}'
    ];

    this.vertexSrc = [
        'precision lowp float;',
        'uniform vec2 uOffset;',
        'uniform vec2 uCentreOffset;',
        'uniform vec2 uScale;',
        'attribute vec4 aPosition;',
        'varying vec2 vTexCoord;',
        'void main(void) {',
        '  gl_Position.zw = vec2(1, 1);',
        '  gl_Position.xy = (aPosition.xy + uOffset + uCentreOffset) * uScale - uCentreOffset;',
        '  vTexCoord = aPosition.zw;',
        '}'
    ];

    /**
     * A local texture counter for multi-texture shaders.
     * @property textureCount
     * @type Number
     */
    this.textureCount = 0;

    this.init();

};

PIXI.TilemapShader.prototype.constructor = PIXI.TilemapShader;

/**
* Initialises the shader.
*
* @method init
*/
PIXI.TilemapShader.prototype.init = function () {

    var gl = this.gl;

    var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
    gl.useProgram(program);

    // get and store the attributes
    this.aPosition = gl.getAttribLocation(program, 'aPosition');
    this.uSampler = gl.getUniformLocation(program, 'uImageSampler');
    this.uClipping = gl.getUniformLocation(program, 'uClipping');
    this.uOffset = gl.getUniformLocation(program, 'uOffset');
    this.uCentreOffset = gl.getUniformLocation(program, 'uCentreOffset');
    this.uAlpha = gl.getUniformLocation(program, 'uAlpha');
    this.uScale = gl.getUniformLocation(program, 'uScale');

    this.attributes = [this.aPosition];
    this.uniforms = [this.uClipping, this.uOffset, this.uCentreOffset, this.uAlpha, this.uScale, this.uSampler];

    this.program = program;

};

/**
* Destroys the shader.
*
* @method destroy
*/
PIXI.TilemapShader.prototype.destroy = function () {

    this.gl.deleteProgram(this.program);
    this.gl = null;

    this.uniforms = null;
    this.attributes = null;

};


root this PIXI game WEBGL_RENDERER CANVAS_RENDERER VERSION _UID Float32Array Uint16Array Uint32Array ArrayBuffer Array PI_2 Math PI RAD_TO_DEG DEG_TO_RAD RETINA_PREFIX DisplayObject position Point scale pivot rotation alpha visible hitArea renderable parent stage worldAlpha worldTransform Matrix worldPosition worldScale worldRotation filterArea _sr _cr _bounds Rectangle _currentBounds _mask _cacheAsBitmap _cacheIsDirty prototype constructor destroy children i length _destroyCachedSprite updateTransform p world a b c d tx ty pt wt rotationCache sin cos x y set sqrt atan2 transformCallback call transformCallbackContext setStageReference preUpdate generateTexture resolution scaleMode renderer bounds getLocalBounds renderTexture RenderTexture width height _tempMatrix render updateCache _generateCachedSprite toGlobal apply toLocal from applyInverse _renderCachedSprite renderSession _cachedSprite gl Sprite _renderWebGL _renderCanvas max ceil texture resize tempFilters _filters filters anchor displayObjectUpdateTransform Object defineProperties get value worldVisible item mask isMask isArray passes filterPasses j push _filterBlock target blendMode blendModes MULTIPLY NORMAL cacheAsBitmap DisplayObjectContainer ignoreChildInput create defineProperty _width _height addChild child addChildAt index removeChild splice Error swapChildren child2 index1 getChildIndex index2 indexOf setChildIndex currentIndex getChildAt removeChildAt removeStageReference undefined removeChildren beginIndex endIndex begin end range removed displayObjectContainerUpdateTransform getBounds EmptyRectangle childBounds childMaxX childMaxY minX Infinity minY maxX maxY childVisible matrixCache identityMatrix spriteBatch flush filterManager pushFilter stop maskManager pushMask start popMask popFilter Texture emptyTexture tint cachedTint tintedTexture shader exists baseTexture hasLoaded onTextureUpdate frame setTexture destroyBase skipRender valid matrix w0 w1 h0 h1 temp x1 y1 x2 y2 x3 y3 x4 y4 crop currentBlendMode context globalCompositeOperation blendModesCanvas globalAlpha smoothProperty scaleModes LINEAR dx trim dy shakeX shakeY roundPixels setTransform cw ch requiresReTint CanvasTinter getTintedTexture drawImage cx cy source SpriteBatch textureThing ready initWebGL fastSpriteBatch WebGLFastSpriteBatch setContext shaderManager setShader fastShader transform isRotated childTransform hex2rgb hex rgb2hex rgb canUseNewCanvasBlendModes document pngHead pngEnd magenta Image src yellow canvas CanvasPool getContext getImageData data remove getNextPowerOfTwo number result isPowerOfTwo idx getFirst container createElement pool removeByCanvas getTotal getFree initDefaultShaders CompileVertexShader shaderSrc _CompileShader VERTEX_SHADER CompileFragmentShader FRAGMENT_SHADER shaderType join createShader shaderSource compileShader getShaderParameter COMPILE_STATUS window console log getShaderInfoLog compileProgram vertexSrc fragmentSrc fragmentShader vertexShader shaderProgram createProgram attachShader linkProgram getProgramParameter LINK_STATUS getProgramInfoLog PixiShader program textureCount firstRun dirty attributes init defaultVertexSrc useProgram uSampler getUniformLocation projectionVector offsetVector dimensions aVertexPosition getAttribLocation aTextureCoord colorAttribute key uniforms uniformLocation initUniforms uniform type _init initSampler2D glMatrix glValueLength glFunc uniformMatrix2fv uniformMatrix3fv uniformMatrix4fv activeTexture bindTexture TEXTURE_2D _glTextures id textureData magFilter minFilter wrapS CLAMP_TO_EDGE wrapT format LUMINANCE RGBA repeat REPEAT pixelStorei UNPACK_FLIP_Y_WEBGL flipY border texImage2D UNSIGNED_BYTE texParameteri TEXTURE_MAG_FILTER TEXTURE_MIN_FILTER TEXTURE_WRAP_S TEXTURE_WRAP_T uniform1i syncUniforms transpose z w _dirty instances updateTexture deleteProgram PixiFastShader uMatrix aPositionCoord aScale aRotation StripShader translationMatrix attribute PrimitiveShader tintColor ComplexPrimitiveShader color glContexts WebGLRenderer defaultRenderer transparent autoResize preserveDrawingBuffer clearBeforeRender view _contextOptions antialias premultipliedAlpha stencil projection offset WebGLShaderManager WebGLSpriteBatch WebGLMaskManager WebGLFilterManager stencilManager WebGLStencilManager blendModeManager WebGLBlendModeManager drawCount initContext mapBlendModes glContextId disable DEPTH_TEST CULL_FACE enable BLEND contextLost viewport bindFramebuffer FRAMEBUFFER clearColor _bgColor r g clear COLOR_BUFFER_BIT camera _shake renderDisplayObject displayObject buffer setBlendMode style createTexture UNPACK_PREMULTIPLY_ALPHA_WEBGL NEAREST mipmap LINEAR_MIPMAP_LINEAR NEAREST_MIPMAP_NEAREST generateMipmap _powerOf2 blendModesWebGL modes ONE ONE_MINUS_SRC_ALPHA ADD SRC_ALPHA DST_ALPHA DST_COLOR SCREEN OVERLAY DARKEN LIGHTEN COLOR_DODGE COLOR_BURN HARD_LIGHT SOFT_LIGHT DIFFERENCE EXCLUSION HUE SATURATION COLOR LUMINOSITY blendModeWebGL blendFunc maskData WebGLGraphics updateGraphics _webGL pushStencil popStencil stencilStack reverse count graphics webGLData bindGraphics STENCIL_TEST STENCIL_BUFFER_BIT level colorMask stencilFunc ALWAYS stencilOp KEEP INVERT mode drawElements TRIANGLE_FAN indices UNSIGNED_SHORT EQUAL DECR INCR TRIANGLE_STRIP _currentGraphics complexPrimitiveShader uniform1f toArray uniform2f uniform3fv bindBuffer ARRAY_BUFFER vertexAttribPointer FLOAT ELEMENT_ARRAY_BUFFER indexBuffer primitiveShader pop maxAttibs attribState tempAttribState stack defaultShader stripShader tilemapShader TilemapShader setAttribs attribs attribId enableVertexAttribArray disableVertexAttribArray _currentId currentShader vertSize size numVerts numIndices vertices positions colors lastIndexCount drawing currentBatchSize currentBaseTexture textures shaders sprites AbstractFilter vertexBuffer createBuffer bufferData STATIC_DRAW DYNAMIC_DRAW sprite uvs _uvs aX aY x0 y0 renderTilingSprite tilingTexture TextureUvs h tilePosition tileScaleOffset offsetX offsetY scaleX tileScale scaleY TEXTURE0 stride bufferSubData subarray nextTexture nextBlendMode nextShader batchSize blendSwap shaderSwap skip renderBatch startIndex TRIANGLES deleteBuffer maxSize renderSprite filterStack texturePool initShaderBuffers filterBlock _filterArea _previous_stencil_mgr filter FilterTexture padding frameBuffer _glFilterTexture vertexArray uvBuffer uvArray inputTexture outputTexture filterPass applyFilterPass sizeX sizeY currentFilter colorBuffer colorArray createFramebuffer DEFAULT framebufferTexture2D COLOR_ATTACHMENT0 renderBuffer createRenderbuffer bindRenderbuffer RENDERBUFFER framebufferRenderbuffer DEPTH_STENCIL_ATTACHMENT renderbufferStorage DEPTH_STENCIL deleteFramebuffer deleteTexture CanvasBuffer clearRect CanvasMaskManager save cacheAlpha CanvasGraphics renderGraphicsMask clip restore tintMethod tintWithMultiply fillStyle toString substr fillRect tintWithPerPixel rgbValues pixelData pixels canHandleAlpha putImageData checkInverseAlpha s1 s2 canUseMultiply CanvasRenderer refresh Phaser Canvas getSmoothingPrefix navigator isCocoonJS screencanvas rgba removeView useNew BaseTexture complete naturalWidth naturalHeight forceLoaded unloadFromGPU updateSourceImage newSrc warn glTexture fromCanvas TextureSilentFail noFrame isTiling requiresUpdate setFrame onBaseTextureLoaded _updateUvs tw th textureBuffer renderWebGL renderCanvas tempMatrix updateBase identity translate append realResolution getImage image getBase64 getCanvas toDataURL webGLPixels Uint8Array readPixels tempCanvas canvasData Strip canvasPadding drawMode DrawModes _vertexBuffer _initWebGL _renderStrip _indexBuffer _uvBuffer _colorBuffer _renderCanvasTriangleStrip _renderCanvasTriangles _renderCanvasDrawTriangle index0 textureSource textureWidth textureHeight u0 u1 u2 v0 v1 v2 paddingX paddingY centerX centerY normX normY dist beginPath moveTo lineTo closePath delta deltaA deltaB deltaC deltaD deltaE deltaF renderStripFlat strip fill updateFrame n rawX rawY Rope points lastPoint point amount total nextPoint perp ratio perpLength num TilingSprite textureDebug canvasBuffer tilePattern refreshTexture frameWidth frameHeight generateTilingTexture needsUpdate createPattern sessionBlendMode forcePowerOfTwo targetWidth _frame sourceSizeW targetHeight sourceSizeH trimmed spriteSourceSizeX spriteSourceSizeY strokeStyle strokeRect exports module define amd WheelEventProxy scaleFactor deltaMode _scaleFactor _deltaMode originalEvent GAMES AUTO CANVAS WEBGL HEADLESS NONE LEFT RIGHT UP DOWN SPRITE BUTTON IMAGE GRAPHICS TEXT TILESPRITE BITMAPTEXT GROUP RENDERTEXTURE TILEMAP TILEMAPLAYER EMITTER POLYGON BITMAPDATA CANVAS_FILTER WEBGL_FILTER ELLIPSE SPRITEBATCH RETROFONT POINTER ROPE CIRCLE RECTANGLE LINE MATRIX POINT ROUNDEDRECTANGLE CREATURE VIDEO PENDING_ATLAS HORIZONTAL VERTICAL LANDSCAPE PORTRAIT ANGLE_UP ANGLE_DOWN ANGLE_LEFT ANGLE_RIGHT ANGLE_NORTH_EAST ANGLE_NORTH_WEST ANGLE_SOUTH_EAST ANGLE_SOUTH_WEST TOP_LEFT TOP_CENTER TOP_RIGHT LEFT_TOP LEFT_CENTER LEFT_BOTTOM CENTER RIGHT_TOP RIGHT_CENTER RIGHT_BOTTOM BOTTOM_LEFT BOTTOM_CENTER BOTTOM_RIGHT trunc floor Function bind slice thisArg bound args boundArgs concat arguments TypeError F proto arg forEach fun t len CheapArray assert Utils reverseString string split getProperty obj prop parts last l current setProperty chanceRoll chance random randomChoice choice1 choice2 parseDimension dimension f px parseInt innerWidth innerHeight pad str dir padlen right left isPlainObject nodeType hasOwnProperty e extend options name copy copyIsArray clone deep mixinPrototype mixin replace mixinKeys keys to o childNodes cloneNode Circle diameter _diameter _radius circumference out u radius setTo copyFrom copyTo dest distance round output contains circumferencePoint angle asDegrees offsetPoint top bottom equals intersects degToRad intersectsRectangle abs halfWidth xDist halfHeight yDist xCornerDist yCornerDist xCornerDistSq yCornerDistSq maxCornerDistSq Ellipse normx normy Line fromSprite startSprite endSprite useCenter center fromAngle rotate rotateAround line asSegment intersectsPoints reflect midPoint centerOn add pointOnLine pointOnSegment xMin min xMax yMin yMax coordinatesOnLine stepRate results sx sy err e2 wrap a1 a2 b1 b2 c1 c2 denom uc ua ub rect bx1 by1 bx2 by2 normalAngle fromArray array pos newPos tx1 d1 invert subtract multiply divide clampX clamp clampY radToDeg getMagnitude getMagnitudeSq setMagnitude magnitude normalize isZero m dot cross rperp normalRightHand negative multiplyAdd s interpolate project amt projectUnit centroid pointslength parse xProp yProp Polygon area _points closed flattened toNumberArray flatten inside ix iy jx jy Number MAX_VALUE calculateArea p1 p2 avgHeight floorAll ceilAll inflate containsRect intersection intersectsRaw tolerance union randomX randomY getPoint empty inflatePoint containsRaw rx ry rw rh containsPoint volume sameDimensions aabb NEGATIVE_INFINITY POSITIVE_INFINITY RoundedRectangle Camera deadzone roundPx atLimit totalInView lerp onShakeComplete Signal onFlashComplete onFadeComplete fx _targetPosition _edge _position intensity duration horizontal vertical shakeBounds _fxDuration _fxType FOLLOW_LOCKON FOLLOW_PLATFORMER FOLLOW_TOPDOWN FOLLOW_TOPDOWN_TIGHT SHAKE_BOTH SHAKE_HORIZONTAL SHAKE_VERTICAL ENABLE_FX boot Graphics follow lerpX lerpY helper unfollow focusOn setPosition focusOnXY shake force direction flash beginFill drawRect endFill fade update updateFX updateShake checkBounds time elapsedMS dispatch rnd frac updateTarget math linear setBoundsToWorld vx vw vy vh setSize reset resetFX State make cache input load sound state tweens particles physics preload loadUpdate loadRender preRender paused resumed pauseUpdate shutdown StateManager pendingState states _pendingState _clearWorld _clearCache _created _args onStateChange onInitCallback onPreloadCallback onCreateCallback onUpdateCallback onRenderCallback onResizeCallback onPreRenderCallback onLoadUpdateCallback onLoadRenderCallback onPausedCallback onResumedCallback onPauseUpdateCallback onShutDownCallback onPause pause onResume resume autoStart newState isBooted callbackContext clearWorld clearCache checkState restart dummy previousStateKey clearCurrentState setCurrentState totalQueuedFiles totalQueuedPacks loadComplete removeAll debug link unlink _kickstart getCurrentState elapsedTime renderType _bindings _prevParams memorize _shouldPropagate active _boundDispatch validateListener listener fnName _registerListener isOnce listenerContext priority binding prevIndex _indexOfListener SignalBinding _addBinding execute _priority cur _listener has addOnce _destroy getNumListeners halt bindings paramsArr forget dispose _this signal _isOnce _signal callCount params handlerReturn detach isBound getListener getSignal Filter prevPoint Date mouse date getFullYear getMonth getDate getHours getMinutes getSeconds sampleRate iChannel0 iChannel1 iChannel2 iChannel3 setResolution pointer toFixed totalElapsedSeconds addToWorld anchorX anchorY Plugin hasPreUpdate hasUpdate hasPostUpdate hasRender hasPostRender postRender PluginManager plugins _len _i plugin postUpdate Stage disableVisibilityChange currentRenderOrderID _hiddenVar _onChange config parseConfig setBackgroundColor DOM getOffset setUserSelect setTouchAction checkVisibility webkitHidden mozHidden msHidden hidden event visibilityChange addEventListener onblur onfocus onpagehide onpageshow device cocoonJSApp CocoonJS App onSuspended onActivated focusLoss focusGain gamePaused gameResumed Color valueToColor updateColor removeEventListener Group addToStage enableBody physicsBodyType Physics ARCADE physicsType alive ignoreDestroy pendingDestroy classType cursor inputEnableChildren onChildInputDown onChildInputUp onChildInputOver onChildInputOut enableBodyDebug physicsSortDirection onDestroy cursorIndex fixedToCamera cameraOffset hash _sortProperty RETURN_NONE RETURN_TOTAL RETURN_CHILD RETURN_ALL SORT_ASCENDING SORT_DESCENDING silent body removeFromHash updateZ addToHash inputEnabled events onAddedToGroup$dispatch addAt addMultiple moveAll getAt createMultiple quantity singleKey singleFrame align rows columns cellWidth cellHeight alignIn resetCursor next previous swap child1 bringToTop getIndex sendToBack moveUp moveDown xy getByName oldChild newChild hasProperty operation checkProperty checkAlive checkVisible setAll setAllChildren checkAll addAll property subAll multiplyAll divideAll callAllExists callback existsValue callbackFromArray callAll method methodLength contextLength renderOrderID predicate checkExists ArraySet forEachExists iterate forEachAlive forEachDead sort order ascendingSortHandler descendingSortHandler customSort sortHandler returnType getFirstExists createIfNull resetChild getFirstAlive getFirstDead loadTexture getTop getBottom getClosestTo object tempDistance getFurthestFrom countLiving countDead getRandom ArrayUtils getRandomItem getRandomExists list getAll pick destroyPhase onRemovedFromGroup$dispatch group destroyTexture removeBetween destroyChildren soft World _definedSize stateChange setBounds useBounds between Game physicsConfig isRunning raf net Device lockRender stepping pendingStep stepCount onBlur onFocus _paused _codePaused currentUpdateID updatesThisFrame _deltaTime _lastCount _spiraling fpsProblemNotifier forceSingleUpdate _nextFpsNotification enableDebug RandomDataGenerator now whenReady seed ScaleManager setUpRenderer GameObjectFactory GameObjectCreator Cache Loader Time TweenManager Input SoundManager Particles Create Net Debug showDebugHeader RequestAnimationFrame stopFocus focus hideBanner v webAudio chrome webGL contextRestored cocoonJS smoothed addToDOM preventDefault clearGLTextures updateLogic desiredFpsMult updateRender slowMotion desiredFps slowStep elapsed timeStep enableStep disableStep step removeFromDOM muteOnPause setMute cordova iOS unsetMute hitCanvas hitContext moveCallbacks customCandidateHandler customCandidateHandlerContext pollRate enabled multiInputOverride MOUSE_TOUCH_COMBINE speed circle maxPointers tapRate doubleTapRate holdRate justPressedRate justReleasedRate recordPointerHistory recordRate recordLimit pointer1 pointer2 pointer3 pointer4 pointer5 pointer6 pointer7 pointer8 pointer9 pointer10 pointers activePointer mousePointer keyboard touch mspointer gamepad resetLocked onDown onUp onTap onHold minPriorityID interactiveItems _localPoint _pollCounter _oldPosition _x _y MOUSE_OVERRIDES_TOUCH TOUCH_OVERRIDES_MOUSE MAX_POINTERS Pointer PointerMode CURSOR addPointer Mouse Touch MSPointer Keyboard Gamepad _onClickTrampoline onClickTrampoline setInteractiveCandidateHandler addMoveCallback deleteMoveCallback TOUCH hard resetSpeed startPointer countActivePointers updatePointer identifier move stopPointer limit getPointer isActive getPointerFromIdentifier getPointerFromId pointerId getLocalPosition hitTest localPoint TileSprite graphicsData shape processClickTrampolines mouseDownCallback mouseUpCallback mouseOutCallback mouseOverCallback mouseWheelCallback capture button wheelDelta locked stopOnGameOut pointerLock _onMouseDown _onMouseMove _onMouseUp _onMouseOut _onMouseOver _onMouseWheel _wheelEvent NO_BUTTON LEFT_BUTTON MIDDLE_BUTTON RIGHT_BUTTON BACK_BUTTON FORWARD_BUTTON WHEEL_UP WHEEL_DOWN android onMouseDown onMouseMove onMouseUp _onMouseUpGlobal onMouseUpGlobal _onMouseOutGlobal onMouseOutGlobal onMouseOut onMouseOver onMouseWheel wheelEvent mouseMoveCallback withinGame leftButton rightButton bindEvent deltaY requestPointerLock element mozRequestPointerLock webkitRequestPointerLock _pointerLockChange pointerLockChange pointerLockElement mozPointerLockElement webkitPointerLockElement releasePointerLock exitPointerLock mozExitPointerLock webkitExitPointerLock _stubsGenerated makeBinder detail deltaX wheelDeltaX deltaZ pointerDownCallback pointerMoveCallback pointerUpCallback _onMSPointerDown _onMSPointerMove _onMSPointerUp _onMSPointerUpGlobal _onMSPointerOut _onMSPointerOver onPointerDown onPointerMove onPointerUp onPointerUpGlobal onPointerOut onPointerOver pointerType DeviceButton buttonCode isDown isUp timeDown timeUp repeats altKey shiftKey ctrlKey onFloat padFloat justPressed justReleased pointerMode CONTACT middleButton backButton forwardButton eraserButton ERASER_BUTTON _holdSent _history _nextDrop _stateReset clientX clientY pageX pageY screenX screenY rawMovementX rawMovementY movementX movementY isMouse previousTapTime totalTouches msSinceLastClick targetObject interactiveCandidates positionDown positionUp _clickTrampolines _trampolineTargetObject resetButtons processButtonsDown buttons processButtonsUp updateButtons down toLowerCase totalActivePointers _touchedHandler processInteractiveObjects shift fromClick pollLocked mozMovementX webkitMovementX mozMovementY webkitMovementY isDragged highestRenderOrderID highestInputPriorityID candidateTarget currentNode first checked validForInput checkPointerDown checkPointerOver priorityID swapTarget newTarget _pointerOutHandler _pointerOverHandler leave currentPointers addClickTrampoline callbackArgs trampolines trampoline _releasedHandler resetMovement touchLockCallbacks touchStartCallback touchMoveCallback touchEndCallback touchEnterCallback touchLeaveCallback touchCancelCallback _onTouchStart _onTouchMove _onTouchEnd _onTouchEnter _onTouchLeave _onTouchCancel onTouchStart onTouchMove onTouchEnd onTouchEnter onTouchLeave onTouchCancel consumeDocumentTouches _documentTouchMove addTouchLockCallback onEnd removeTouchLockCallback cb changedTouches InputHandler useHandCursor _setHandCursor allowHorizontalDrag allowVerticalDrag snapOffset snapOnDrag snapOnRelease snapX snapY snapOffsetX snapOffsetY pixelPerfectOver pixelPerfectClick pixelPerfectAlpha draggable boundsRect boundsSprite scaleLayer dragOffset dragFromCenter dragStopBlocksInputUp dragStartPoint dragDistanceThreshold dragTimeThreshold downPoint snapPoint _dragPoint _dragPhase _pendingDrag _dragTimePass _dragDistancePass _wasEnabled _tempPoint _pointerData camX camY isOver isOut timeOver timeOut downDuration onAddedToGroup addedToGroup onRemovedFromGroup removedFromGroup highestID highestRenderID includePixelPerfect isPixelPerfect pointerX pointerY pointerDown pointerUp pointerTimeDown pointerTimeUp pointerOver pointerOut pointerTimeOver pointerTimeOut pointerDragged fastTest checkPixel _dx _dy startDrag _draggedPointerID updateDrag sendEvent onInputOver$dispatch onInputOut$dispatch onInputDown$dispatch dragTimeElapsed onInputUp$dispatch stopDrag fromStart globalToLocalX py globalToLocalY checkBoundsRect checkBoundsSprite onDragUpdate justOver delay overDuration justOut enableDrag lockCenter pixelPerfect alphaThreshold disableDrag onDragStart$dispatch grid boundsFluid scaleFluidInversed onDragStop$dispatch setDragLock allowHorizontal allowVertical enableSnap onDrag onRelease disableSnap _gamepadIndexMap _rawPads _active _gamepadSupportAvailable webkitGetGamepads webkitGamepads userAgent getGamepads _prevRawGamepadTypes _prevTimestamps onConnectCallback onDisconnectCallback onDownCallback onUpCallback onAxisCallback onFloatCallback _ongamepadconnected _gamepaddisconnected _gamepads SinglePad addCallbacks callbacks onConnect onDisconnect onAxis _onGamepadConnected onGamepadConnected _onGamepadDisconnected onGamepadDisconnected newPad connect removedPad disconnect _pollGamepads pad1 pollStatus pad2 pad3 pad4 rawGamepads gamepadsChanged _rawPad singlePad validConnections rawIndices padIndices connected k rawPad setDeadZones deadZone BUTTON_0 BUTTON_1 BUTTON_2 BUTTON_3 BUTTON_4 BUTTON_5 BUTTON_6 BUTTON_7 BUTTON_8 BUTTON_9 BUTTON_10 BUTTON_11 BUTTON_12 BUTTON_13 BUTTON_14 BUTTON_15 AXIS_0 AXIS_1 AXIS_2 AXIS_3 AXIS_4 AXIS_5 AXIS_6 AXIS_7 AXIS_8 AXIS_9 XBOX360_A XBOX360_B XBOX360_X XBOX360_Y XBOX360_LEFT_BUMPER XBOX360_RIGHT_BUMPER XBOX360_LEFT_TRIGGER XBOX360_RIGHT_TRIGGER XBOX360_BACK XBOX360_START XBOX360_STICK_LEFT_BUTTON XBOX360_STICK_RIGHT_BUTTON XBOX360_DPAD_LEFT XBOX360_DPAD_RIGHT XBOX360_DPAD_UP XBOX360_DPAD_DOWN XBOX360_STICK_LEFT_X XBOX360_STICK_LEFT_Y XBOX360_STICK_RIGHT_X XBOX360_STICK_RIGHT_Y PS3XC_X PS3XC_CIRCLE PS3XC_SQUARE PS3XC_TRIANGLE PS3XC_L1 PS3XC_R1 PS3XC_L2 PS3XC_R2 PS3XC_SELECT PS3XC_START PS3XC_STICK_LEFT_BUTTON PS3XC_STICK_RIGHT_BUTTON PS3XC_DPAD_UP PS3XC_DPAD_DOWN PS3XC_DPAD_LEFT PS3XC_DPAD_RIGHT PS3XC_STICK_LEFT_X PS3XC_STICK_LEFT_Y PS3XC_STICK_RIGHT_X PS3XC_STICK_RIGHT_Y padParent _padParent _prevTimestamp _buttons _buttonsLen _axes _axesLen getButton timestamp rawButtonVal isNaN processButtonDown processButtonUp processButtonFloat axes processAxisChange triggerCallback disconnectingIndex axis axisCode buttonValue Key keycode _enabled keyCode onHoldCallback onHoldContext _justDown _justUp processKeyDown processKeyUp upDuration pressEvent onPressCallback _keys _capture _onKeyDown _onKeyPress _onKeyUp _k onPress addKey addKeyCapture addKeys removeKey removeKeyCapture createCursorKeys up KeyCode processKeyPress clearCaptures String fromCharCode charCode A charCodeAt B C D E G H I J K L M N O P Q R S T U V W X Y Z ZERO TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE NUMPAD_0 NUMPAD_1 NUMPAD_2 NUMPAD_3 NUMPAD_4 NUMPAD_5 NUMPAD_6 NUMPAD_7 NUMPAD_8 NUMPAD_9 NUMPAD_MULTIPLY NUMPAD_ADD NUMPAD_ENTER NUMPAD_SUBTRACT NUMPAD_DECIMAL NUMPAD_DIVIDE F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 COLON EQUALS COMMA UNDERSCORE PERIOD QUESTION_MARK TILDE OPEN_BRACKET BACKWARD_SLASH CLOSED_BRACKET QUOTES BACKSPACE TAB CLEAR ENTER SHIFT CONTROL ALT CAPS_LOCK ESC SPACEBAR PAGE_UP PAGE_DOWN END HOME PLUS MINUS INSERT DELETE HELP NUM_LOCK match Component Angle wrapAngle Animation play frameRate loop killOnComplete animations AutoCull autoCull inCamera checkWorldBounds Bounds alignTo BringToTop Core install components previousPosition Events PhysicsBody AnimationManager LoadTexture FixedToCamera previousRotation fresh _exists P2JS removeFromWorld customRender Crop cropRect _crop updateCrop resetFrame Delta Destroy onDestroy$dispatch removeFrom Video onChangeSource resizeFrame BitmapText _glyphs _parent _onDestroy _onAddedToGroup _onRemovedFromGroup _onRemovedFromWorld _onKilled _onRevived _onEnterBounds _onOutOfBounds _onInputOver _onInputOut _onInputDown _onInputUp _onDragStart _onDragUpdate _onDragStop _onAnimationStart _onAnimationComplete _onAnimationLoop onRemovedFromWorld onKilled onRevived onOutOfBounds onEnterBounds onInputOver onInputOut onInputDown onInputUp onDragStart onDragStop onAnimationStart onAnimationComplete onAnimationLoop backing _fixedToCamera Health health maxHealth damage kill setHealth heal InCamera InputEnabled InWorld outOfCameraBoundsKill _outOfBoundsFired onEnterBounds$dispatch onOutOfBounds$dispatch outOfBoundsKill inWorld LifeSpan lifespan physicsElapsedMS revive onRevived$dispatch onKilled$dispatch stopAnimation BitmapData hasFrameData loadFrameData getFrameData frameData Tilemap TilemapLayer img base frameName Overlap overlap _reset Reset ScaleMinMax scaleMin scaleMax checkTransform setScaleMinMax Smoothed existing weapon Weapon createBullets creature mesh Creature tween physicsGroup audio audioSprite addSprite tileSprite rope text Text overFrame outFrame downFrame upFrame Button emitter maxParticles Arcade Emitter retroFont font characterWidth characterHeight chars charsPerRow xSpacing ySpacing xOffset yOffset RetroFont bitmapText tilemap tileWidth tileHeight addToCache uuid addRenderTexture video url bitmapData addBitmapData Tween preUpdatePhysics preUpdateLifeSpan preUpdateInWorld preUpdateCore _onOverFrame _onOutFrame _onDownFrame _onUpFrame onOverSound onOutSound onDownSound onUpSound onOverSoundMarker onOutSoundMarker onDownSoundMarker onUpSoundMarker onOverMouseOnly justReleasedPreventsOver freezeFrames forceOut setFrames onInputOverHandler onInputOutHandler onInputDownHandler onInputUpHandler removedFromWorld STATE_OVER STATE_OUT STATE_DOWN STATE_UP clearFrames setStateFrame switchImmediately frameKey changeStateFrame setStateSound marker soundKey markerKey Sound AudioSprite playStateSound setSounds overSound overMarker downSound downMarker outSound outMarker upSound upMarker setOverSound setOutSound setDownSound setUpSound changedUp skipPool ctx imageData FrameData textureFrame addFrame Frame disableTextureUpload cls _image _pos _size _scale _rotate _alpha prev _anchor _tempR _tempG _tempB _circle _swapCanvas moveH moveV draw addImage processPixelRGB pixel createColor unpackPixel getPixel32 setPixel32 processPixel replaceRGB r1 g1 r2 g2 region packPixel setHSL bHaveH bHaveS bHaveL HSLtoRGB shiftHSL red green blue immediate LITTLE_ENDIAN setPixel getPixel getPixelRGB hsl hsv getPixels getFirstPixel scan newWidth newHeight op copyTransform copyRect drawGroup drawGroupProxy drawFull renderGraphics shadow blur shadowColor shadowBlur shadowOffsetX shadowOffsetY alphaMask sourceRect maskRect blendSourceAtop blendReset extract destination prevFont fillText arc lineWidth stroke textureLine blendSourceOver blendSourceIn blendSourceOut blendDestinationOver blendDestinationIn blendDestinationOut blendDestinationAtop blendXor blendAdd blendMultiply blendScreen blendOverlay blendDarken blendLighten blendColorDodge blendColorBurn blendHardLight blendSoftLight blendDifference blendExclusion blendHue blendSaturation blendColor blendLuminosity getSmoothingEnabled setSmoothingEnabled getTransform translateX translateY skewX skewY fillAlpha lineColor currentPath boundsPadding _localBounds webGLDirty cachedSpriteDirty lineStyle lineAlpha drawShape updateLocalBounds quadraticCurveTo cpX cpY toX toY xa ya fromX fromY bezierCurveTo cpX2 cpY2 dt dt2 dt3 t2 t3 arcTo mm dd cc tt k1 k2 j1 j2 qx qy startAngle endAngle anticlockwise segments sweep segs startX startY filling theta theta2 cTheta sTheta segMinus remainder real fillColor drawRoundedRect drawCircle drawEllipse drawPolygon path clearDirty updateCachedSpriteTexture _prevTint tempPoint RECT RREC CIRC ELIP cachedSprite destroyCachedSprite GraphicsData POLY _lineTint _fillTint PolyK Triangulate sign tgs avl al i0 i1 i2 ax ay bx by earFound _convex vi _PointInTriangle v0x v0y v1x v1y v2x v2y dot00 dot01 dot02 dot11 dot12 invDenom EarCut holeIndices dim hasHoles outerLen outerNode linkedList triangles eliminateHoles earcutLinked clockwise sum insertNode filterPoints again steiner removeNode ear pass indexCurve isEarHashed isEar cureLocalIntersections splitEarcut pointInTriangle minTX minTY maxTX maxTY minZ zOrder maxZ nextZ prevZ locallyInside isValidDiagonal splitPolygon queue getLeftmost compareX eliminateHole hole findHoleBridge hx hy tan tanMin sortLinked q tail numMerges pSize qSize inSize leftmost intersectsPolygon middleInside q1 q2 Node an bp stencilBufferLimit lastIndex graphicsDataPool switchMode canDrawUsingSimple buildPoly buildComplexPoly buildLine buildRectangle buildCircle buildRoundedRectangle upload WebGLGraphicsData rectData verts vertPos tempPoints rrectData recPoints quadraticBezierCurve vecPos getPt n1 n2 perc diff xb yb circleData totalSegs seg firstPoint midPointX midPointY unshift p1x p1y p2x p2y p3x p3y perpx perpy perp2x perp2y perp3x perp3y pdist indexCount indexStart glPoints glIndicies updateGraphicsTint kappa ox oy xe ye xm ym maxRadius tintR tintG tintB drawTriangle cull triangle cameraToFace ab faceNormal drawTriangles point1 point2 point3 renderXY renderRawXY textBounds strokeColors fontStyles fontWeights autoRound useAdvancedWrap _res _text _fontComponents _lineSpacing _charCount setStyle updateText setShadow shadowStroke shadowFill backgroundColor boundsAlignH boundsAlignV strokeThickness wordWrap wordWrapWidth maxLines tabs fontToComponents fontStyle fontVariant fontWeight fontSize componentsToFont outputText runWordWrap lines lineWidths maxLineWidth fontProperties determineFontProperties drawnLines measureLine measureText tab section snapToCeil lineHeight lineSpacing textBaseline lineCap lineJoin linePositionX linePositionY ascent updateLine updateShadow strokeText renderTabLine snap lineLength letter clearColors clearFontValues addColor addStrokeColor addFontStyle addFontWeight weight precalculateWordWrap wrappedLines advancedWordWrap basicWordWrap linesCount currentLineWidth words word wordWithSpace wordWidth newWord secondPart spaceLeft wordWidthWithSpace updateFont family exec fontFamily setText parseList setTextBounds properties fontPropertiesCache fontPropertiesCanvas fontPropertiesContext baseline descent imagedata parseFloat textWidth textHeight _prevAnchor _maxWidth _data getBitmapFont _font _fontSize _align _tint sourceWidth sourceHeight scanLine lastSpace wrappedWidth prevCharCode maxWidth test charAt charData kerning xAdvance cleanText re purgeGlyphs kept checkImageKey characterSpacingX characterSpacingY characterPerRow multiLine autoUpperCase customSpacingX customSpacingY fixedWidth fontSet grabData currentX currentY updateFrameData stamp ALIGN_LEFT ALIGN_RIGHT ALIGN_CENTER TEXT_SET1 TEXT_SET2 TEXT_SET3 TEXT_SET4 TEXT_SET5 TEXT_SET6 TEXT_SET7 TEXT_SET8 TEXT_SET9 TEXT_SET10 TEXT_SET11 setFixedWidth lineAlignment content characterSpacing allowLowerCase buildRetroFontText getLongestLine pasteLine longestLine removeUnsupportedCharacters stripCR newString aChar code updateOffset diffX diffY frames getFrames newText toUpperCase _hasUpdateAnimation _updateAnimationCallback updateAnimation _updateAnimation difference _scroll def physicsElapsed autoScroll stopScroll deviceReadyAt initialized desktop iOSVersion node nodeWebkit electron ejecta crosswalk chromeOS linux macOS windows windowsPhone canvasBitBltShift file fileSystem localStorage worker css3D typedArray vibration getUserMedia quirksMode arora chromeVersion epiphany firefox firefoxVersion ie ieVersion trident tridentVersion edge mobileSafari midori opera safari safariVersion webApp silk audioData ogg opus mp3 wav m4a webm dolby oggVideo h264Video mp4Video webmVideo vp9Video hlsVideo iPhone iPhone4 iPad pixelRatio littleEndian support32bit fullscreen requestFullscreen cancelFullscreen fullscreenKeyboard onInitialized nonPrimer readyCheck _readyCheck _monitor _queue readyState setTimeout _initialize _checkOS vita kindle RegExp $1 _checkFeatures getItem error WebGLRenderingContext compatMode webkitGetUserMedia mozGetUserMedia msGetUserMedia oGetUserMedia URL webkitURL mozURL msURL _checkInput documentElement maxTouchPoints msPointerEnabled pointerEnabled _checkFullScreenSupport fs cfs Element _checkBrowser $3 process require versions _checkVideo videoElement canPlayType _checkAudio audioElement major minor $2 _checkDevice Int8Array _checkIsLittleEndian Uint8ClampedArray Int32Array _checkIsUint8ClampedImageData vibrate webkitVibrate mozVibrate msVibrate elem createImageData _checkCSS3D has3d el transforms webkitTransform OTransform msTransform MozTransform insertBefore getComputedStyle getPropertyValue canPlayAudio canPlayVideo isConsoleOpen profile profileEnd isAndroidStockBrowser matches display msTouchAction overflowHidden getElementById overflow appendChild parentNode vendor prefix setImageRenderingCrisp types msInterpolationMode setImageRenderingBicubic forceSetTimeOut vendors requestAnimationFrame cancelAnimationFrame _isSetTimeOut _onLoop _timeOutID updateSetTimeout updateRAF rafTime timeToCall clearTimeout isSetTimeOut isRAF PI2 fuzzyEqual epsilon fuzzyLessThan fuzzyGreaterThan fuzzyCeil val fuzzyFloor average shear snapTo gap snapToFloor roundTo place pow floorTo ceilTo angleBetween angleBetweenY angleBetweenPoints angleBetweenPointsY reverseAngle angleRad normalizeAngle maxAdd minSub wrapValue isOdd isEven minProperty maxProperty radians linearInterpolation bezierInterpolation bernstein catmullRomInterpolation catmullRom p0 factorial res p3 roundAwayFromZero sinCosGenerator sinAmplitude cosAmplitude frequency frq cosTable sinTable distanceSq distancePow clampBottom within mapLinear smoothstep smootherstep percent degreeToRadiansFactor radianToDegreesFactor degrees seeds s0 sow integer integerInRange realInRange normal ary weightedPick QuadTree maxObjects maxLevels objects nodes _empty subWidth subHeight populate populateHandler insert retrieve returnObjects getHostName location hostname checkDomainName domain updateQueryString redirect href separator getQueryString parameter keyValues search substring decodeURI decodeURIComponent frameBased _tweens _add easeMap Power0 Easing Power1 Power2 Power3 Power4 Linear None Quad Quadratic Out Cubic Quart Quartic Quint Quintic Sine Sinusoidal Expo Exponential Circ Circular Elastic Back Bounce Quad.easeIn In Cubic.easeIn Quart.easeIn Quint.easeIn Sine.easeIn Expo.easeIn Circ.easeIn Elastic.easeIn Back.easeIn Bounce.easeIn Quad.easeOut Cubic.easeOut Quart.easeOut Quint.easeOut Sine.easeOut Expo.easeOut Circ.easeOut Elastic.easeOut Back.easeOut Bounce.easeOut Quad.easeInOut InOut Cubic.easeInOut Quart.easeInOut Quint.easeInOut Sine.easeInOut Expo.easeInOut Circ.easeInOut Elastic.easeInOut Back.easeInOut Bounce.easeInOut _pauseAll _resumeAll pendingDelete _manager addTweens numTweens isTweening some _pause _resume pauseAll resumeAll manager timeline timeScale repeatCounter onStart onLoop onRepeat onChildComplete onComplete chainedTween isPaused _onUpdateCallback _onUpdateCallbackContext _pausedTime _hasStarted ease yoyo Default TweenData vEnd loadValues updateTweenData repeatDelay yoyoDelay easing interpolation repeatAll chain startTime status PENDING RUNNING LOOPED COMPLETE generateData vStart vStartCache vEndCache repeatTotal inReverse easingFunction interpolationFunction interpolationContext isFrom yoyoCounter ms fps blob reversed asin prevTime _desiredFps suggestedFps advancedTiming fpsMin fpsMax msMin msMax pauseDuration timeExpected Timer _frameCount _elapsedAccumulator _started _timeLastSecond _pauseStarted _justResumed _timers timer autoDestroy previousDateNow updateAdvancedTiming updateTimers elapsedSince since elapsedSecondsSince running expired nextTick timeCap _pauseTotal _now _marked _diff _newTick MINUTE SECOND HALF QUARTER repeatCount tick TimerEvent clearEvents clearPendingEvents adjustEvents baseTime currentFrame currentAnim updateIfVisible isLoaded _frameData _anims _outputFrames anim copyFrameData useNumericIndex getFrameIndexes validateFrames checkFrameName isPlaying getAnimation refreshFrame getFrame getFrameByName _frameIndex _frames loopCount isFinished _pauseStartTime _frameDiff _frameSkip onUpdate isReversed _timeLastFrame _timeNextFrame updateCurrentFrame onAnimationStart$dispatch reverseOnce frameId useLocalFrameIndex frameIndex dispatchComplete onAnimationComplete$dispatch onAnimationLoop$dispatch signalUpdate fromPlay generateFrameNames suffix zeroPad rotated rotationDirection spriteSourceSizeW spriteSourceSizeH setTrim actualWidth actualHeight destX destY destWidth destHeight getRect _frameNames getFrameRange AnimationParser spriteSheet frameMax margin spacing row column JSONData json newFrame filename sourceSize spriteSourceSize JSONDataPyxel signature tileheight tilewidth JSONDataHash XMLData xml getElementsByTagName frameX frameY autoResolveURL _cache binary bitmapFont _urlMap _urlResolver _urlTemp onSoundUnlock _cacheMap TEXTURE SOUND PHYSICS BINARY BITMAPFONT JSON XML SHADER RENDER_TEXTURE addDefaultImage addMissingImage MISSING addCanvas removeImage _resolveURL addSound audioTag decoded isDecoding touchLocked addText addPhysicsData addTilemap mapData addBinary binaryData addBitmapFont atlasData atlasType LoaderParser jsonBitmapFont xmlBitmapFont addJSON addXML addVideo isBlob addShader addSpriteSheet addTextureAtlas TEXTURE_ATLAS_XML_STARLING TEXTURE_ATLAS_JSON_PYXEL reloadSound getSound reloadSoundComplete updateSound decodedSound isSoundDecoded isSoundReady checkKey checkURL checkCanvasKey checkTextureKey checkSoundKey checkTextKey checkPhysicsKey checkTilemapKey checkBinaryKey checkBitmapDataKey checkBitmapFontKey checkJSONKey checkXMLKey checkVideoKey checkShaderKey checkRenderTextureKey full getTextureFrame getSoundData getText getPhysicsData fixtureKey fixtures fixture getTilemapData getBinary getBitmapData getJSON getXML getVideo getShader getRenderTexture getBaseTexture getFrameCount getFrameByIndex getURL getKeys removeCanvas destroyBaseTexture removeSound removeText removePhysics removeTilemap removeBinary removeBitmapData removeBitmapFont removeJSON removeXML removeVideo removeShader removeRenderTexture removeSpriteSheet removeTextureAtlas atlas baseURL isLoading preloadSprite crossOrigin headers onLoadStart onLoadComplete onPackComplete onFileStart onFileComplete onFileError useXDomainRequest _warnedAboutXDomainRequest enableParallel maxParallelDownloads _withSyncPointDepth _fileList _flightQueue _processingHead _fileLoadStarted _totalPackCount _totalFileCount _loadedPackCount _loadedFileCount TEXTURE_ATLAS_JSON_ARRAY TEXTURE_ATLAS_JSON_HASH PHYSICS_LIME_CORONA_JSON PHYSICS_PHASER_JSON setPreloadSprite checkKeyExists getAssetIndex bestFound loaded loading getAsset fileIndex addToFileList overwrite extension syncPoint currentFile replaceInFileList pack images urls script spritesheet autoDecode noAudio jsonURL jsonData audiosprite loadEvent asBlob CSV TILED_JSON LIME_CORONA_JSON textureURL atlasURL parseXml atlasJSONArray atlasJSONHash atlasXML withSyncPoint addSyncPoint asset removeFile updateProgress processLoadQueue finishedLoading requestUrl requestObject progress syncblock inflightLimit processPack loadFile abnormal asyncComplete errorMessage packData transformUrl xhrLoad fileComplete loadImageTag getAudioURL usingWebAudio usingAudioTag loadAudioTag fileError getVideoURL loadVideoTag jsonLoadComplete xmlLoadComplete csvLoadComplete onload onerror controls autoplay videoLoadEvent canplay Audio playThroughEvent XDomainRequest xhrLoadWithXDR xhr XMLHttpRequest open responseType setRequestHeader message send timeout ontimeout onprogress videoType uri lastIndexOf audioType reason loadNext responseText response decode language defer head contentType domparser DOMParser parseFromString ActiveXObject async loadXML totalLoadedFiles totalLoadedPacks progressFloat info common getAttribute letters kernings second finalizeBitmapFont _face _lineHeight _id _xoffset _yoffset _xadvance _second _first _amount bitmapFontData autoplayKey sounds spritemap addMarker connectToMaster markers totalDuration currentTime durationMS stopTime pausedPosition pausedTime currentMarker fadeTween pendingPlayback override allowMultiple externalNode masterGainNode gainNode _sound masterGain createGain createGainNode gain soundHasUnlocked onDecoded onPlay onStop onMute onMarkerComplete _volume _buffer _muted _tempMarker _tempPosition _tempVolume _tempPause _muteVolume _tempLoop _onDecodedEventDispatched removeMarker onEndedHandler onended isDecoded loopFull forceRestart noteOff createBufferSource noteGrainOn muted mute prevMarker fadeIn fadeTo fadeOut fadeComplete updateGlobalVolume globalVolume onSoundDecode onVolumeChange onUnMute channels _codeMuted _unlockSource _sounds _watchList _watching _watchCallback _watchContext disableAudio disableWebAudio audioContext fakeiOSTouchLock setTouchLock unlock noteOn stopAll soundData decodeAudioData setDecodedCallback files playbackState PLAYING_STATE FINISHED_STATE removeByKey close dom minWidth minHeight maxHeight forceLandscape forcePortrait incorrectOrientation _pageAlignHorizontally _pageAlignVertically onOrientationChange enterIncorrectOrientation leaveIncorrectOrientation fullScreenTarget _createdFullScreenTarget onFullScreenInit onFullScreenChange onFullScreenError screenOrientation getScreenOrientation scaleFactorInversed aspectRatio sourceAspectRatio windowConstraints compatibility supportsFullScreen orientationFallback noMargins scrollTo forceMinimumDocumentHeight canExpandParent clickTrampoline _scaleMode NO_SCALE _fullScreenScaleMode parentIsWindow parentScaleFactor trackParentInterval onSizeChange onResize onResizeContext _pendingScaleMode _fullScreenRestore _gameSize _userScaleFactor _userScaleTrim _lastUpdate _updateThrottle _updateThrottleReset _parentBounds _tempBounds _lastReportedCanvasSize _lastReportedGameSize _booted setupScale EXACT_FIT SHOW_ALL RESIZE USER_SCALE compat _orientationChange orientationChange _windowResize windowResize _fullScreenChange fullScreenChange _fullScreenError fullScreenError _gameResumed setGameSize FlexGrid fullScreenScaleMode getParentBounds visualBounds updateDimensions queueUpdate currentScaleMode setUserScale hScale vScale hTrim vTrim setResizeCallback signalSizeChange setMinMax prevThrottle prevWidth prevHeight boundsChanged orientationChanged updateOrientationState updateLayout throttle updateScalingAndBounds forceOrientation classifyOrientation orientation previousOrientation previouslyIncorrect isLandscape isPortrait changed correctnessChanged scrollTop reflowGame setMaximum setExactFit isFullScreen boundingParent setShowAll resetCanvas reflowCanvas layoutBounds clientRect getBoundingClientRect parentRect offsetParent wc windowBounds alignCanvas parentBounds canvasBounds currentEdge targetEdge marginLeft marginRight marginTop marginBottom pageAlignHorizontally pageAlignVertically cssWidth cssHeight expanding multiplier createFullScreenTarget fsTarget background startFullScreen allowTrampoline cleanupCreatedTarget initData targetElement ALLOW_KEYBOARD_INPUT stopFullScreen prepScreenMode enteringFullscreen createdTarget scaleSprite letterBox scaleX1 scaleY1 scaleX2 scaleY2 scaleOnWidth bmd columnWidth renderShadow currentAlpha scaleManager currentColor soundInfo cameraInfo hideIfUp downColor upColor worldX worldY spriteInputInfo justDown justUp inputInfo spriteBounds filled rectangle ropeSegments self segment spriteInfo spriteCoords lineInfo geom forceType quadTree quadtree Body NINJA Ninja BOX2D Box2D renderBody bodyInfo renderBodyInfo box2d box2dWorld renderDebugDraw box2dBody displayList box scrollY scrollLeft scrollX clientTop clientLeft cushion calibrate coords getAspectRatio inLayoutViewport primaryFallback screen mozOrientation msOrientation matchMedia documentBounds pageXOffset pageYOffset treatAsDesktop clientWidth clientHeight offsetWidth scrollWidth offsetHeight scrollHeight getByKey randomIndex removeRandomItem shuffle transposeMatrix sourceRowCount sourceColCount rotateMatrix findClosest arr NaN low high rotateRight rotateLeft numberArray numberArrayStep LinkedList entity palettes 0 1 2 3 4 5 6 7 8 9 PALETTE_ARNE PALETTE_JMP PALETTE_CGA PALETTE_C64 PALETTE_JAPANESE_MACHINE pixelWidth pixelHeight palette boundsCustom boundsFull boundsNone positionCustom positionFluid positionFull positionNone scaleCustom scaleFluid scaleFull scaleNone customWidth customHeight customOffsetX customOffsetY ratioH ratioV layers createCustomLayer layer FlexLayer createFluidLayer createFullLayer createFixedLayer persist fitSprite topLeft topMiddle topRight bottomLeft bottomMiddle bottomRight RGBtoHSL RGBtoHSV fromRGBA toRGBA toABGR hueToColor HSVtoRGB color32 getColor getColor32 RGBtoString componentToHex hexToRGB hexToColor webToColor web tempColor getRGB HSVColorWheel HSLColorWheel interpolateColor color1 color2 steps currentStep src1 src2 interpolateColorWithRGB or og ob interpolateRGB getRandomColor getWebRGB getAlpha getAlphaFloat getRed getGreen getBlue blendNormal blendAverage blendSubtract blendNegation blendLinearDodge blendLinearBurn blendLinearLight blendVividLight blendPinLight blendHardMix blendReflect blendGlow blendPhoenix arcade ninja chipmunk matter CHIPMUNK MATTERJS P2 Matter startSystem system enableAABB gravity checkCollision OVERLAP_BIAS forceX sortDirection LEFT_RIGHT skipQuadTree _total SORT_NONE RIGHT_LEFT TOP_BOTTOM BOTTOM_TOP updateMotion velocityDelta computeVelocity angularVelocity angularAcceleration angularDrag maxAngular velocity acceleration drag maxVelocity allowGravity object1 object2 overlapCallback processCallback collideHandler collide collideCallback sortLeftRight sortRightLeft sortTopBottom sortBottomTop overlapOnly collideGroupVsSelf collideSpriteVsSprite collideSpriteVsGroup collideSpriteVsTilemapLayer collideGroupVsGroup collideGroupVsTilemapLayer sprite1 sprite2 separate items bounds1 bounds2 group1 group2 body1 body2 isCircle separateCircle bodyRect bodyCircle resultX resultY separateX separateY onOverlap onCollide circleBodyIntersects getOverlapX getOverlapY angleCollision angleBetweenCenters immovable customSeparateX tempVel1 mass tempVel2 bounce maxOverlap deltaAbsX embedded touching none overlapX deltaAbsY overlapY moves friction nv1 nv2 avg customSeparateY getObjectsUnderPointer getObjectsAtLocation callbackArg moveToObject maxTime distanceBetween moveToPointer angleToPointer distanceToPointer moveToXY distanceToXY velocityFromAngle velocityFromRotation accelerationFromRotation accelerateToObject xSpeedMax ySpeedMax accelerateToPointer accelerateToXY angleToXY worldAngleToPointer allowRotation preRotation newVelocity deltaMax worldBounce onWorldBounds facing overlapR collideWorldBounds any wasTouching blocked tilePadding syncBounds isMoving stopVelocityOnCollide moveTimer moveDistance moveDuration moveTarget moveEnd onMoveComplete movementCallback movementCallbackContext _sx _sy updateBounds asx asy updateMovement collided stopMovement stopVelocity check bodyBounds moveFrom setCircle onFloor onCeiling onWall TilemapCollision TILE_BIAS tilemapLayer getTiles separateTile tile tilemapLayerOffsetX tilemapLayerOffsetY collisionCallback collisionCallbackContext faceLeft faceRight faceTop faceBottom tileCheckX tileCheckY collideRight collideLeft processTileSeparationX collideDown collideUp processTileSeparationY mapwidth mapheight tileWide tileHigh mapWide mapHigh glBatch lastTile batchDataElement dataSize _renderWholeTilemap positionBuffer _renderBatch oldR oldT uvl uvt screenWide2 screenHigh2 iTextureWide iTextureHigh srcWide srcHigh iWide iHigh wide degenerate lft bot aPosition drawArrays uCentreOffset uAlpha uScale ImageCollection firstgid imageWidth imageHeight imageMargin imageSpacing containsImageIndex imageIndex gid Tile flipped scanned setCollisionCallback setCollision resetCollision isInteresting collides faces TilemapParser version widthInPixels heightInPixels tilesets tilesetLayers imagecollections tiles collideIndexes collision currentLayer debugMap _results _tempA NORTH EAST SOUTH WEST setTileSize createBlankLayer addTilesetImage tileset tileMargin tileSpacing getTilesetIndex setImage newSet Tileset countX countY createFromObjects CustomClass adjustY found createFromTiles replacements getLayer customClass lw lh createLayer getLayerIndex ts li createInternalLayer TilemapLayerGL indexes bodies setIndex getImageIndex setTileIndexCallback setTileLocationCallback recalculate setCollisionByIndex calculateFaces setCollisionBetween setCollisionByExclusion setPreventRecalculate preventingRecalculate needToRecalculate above below getTileAbove getTileBelow getTileLeft getTileRight setLayer hasTile removeTile removeTileWorldXY putTile putTileWorldXY searchTileIndex getTile nonNull getTileWorldXY paste tileblock tileA tileB swapHandler removeAllLayers dump txt map renderSettings enableScrollDelta overdrawRatio copyCanvas debugSettings missingImageFill debuggedTileOverfill forceFullRedraw debugAlpha facingEdgeStroke collidingTileOverfill scrollFactorX scrollFactorY rayStepRate _wrap _mc renderWidth renderHeight _scrollX _scrollY ensureSharedCopyCanvas sharedCopyCanvas resizeWorld _fixX _unfixX _fixY _unfixY getTileX getTileY getTileXY getRayCastTiles interestingFace coord fetchAll wy wx resolveTileset tileIndex containsTileIndex resetTilesetCache setScale xScale yScale shiftCanvas copyW copyH copyContext renderRegion lastAlpha xmax ymax baseX baseY normStartX normStartY renderDeltaScroll shiftX shiftY renderW renderH trueTop trueBottom trueLeft trueRight renderFull redrawAll mc renderDebug _renderMode offx offy addDegenerate drawGl INSERT_NULL getEmptyData parseCSV parseTiledJSON fields sliced curl compression encoding binaryString atob bytes opacity flippedVal curi tileproperties tileProperties updateTileData imagewidth imageheight newCollection ti curo polyline polygon ellipse sid drawCoords coordIndex sw sh dw dh setSpacing rowCount colCount Particle autoScale scaleData _s autoAlpha alphaData _a onEmit setAlphaData setScaleData emitters ID minParticleSpeed maxParticleSpeed minParticleScale maxParticleScale minRotation maxRotation minParticleAlpha maxParticleAlpha particleClass particleDrag on particleAnchor emitX emitY particleBringToTop particleSendToBack _minParticleScale _maxParticleScale _quantity _timer _counter _flowQuantity _flowTotal _explode emitParticle makeParticles particle rndKey rndFrame explode flow forceQuantity setXSpeed setYSpeed setRotation setAlpha rate tweenData at bullets autoExpandBulletsGroup autofire shots fireLimit fireRate fireRateVariance fireFrom fireAngle bulletInheritSpriteSpeed bulletAnimation bulletFrameRandom bulletFrameCycle bulletWorldWrap bulletWorldWrapPadding bulletAngleOffset bulletAngleVariance bulletSpeed bulletSpeedVariance bulletLifespan bulletKillDistance bulletGravity bulletRotateToVelocity bulletKey bulletFrame _bulletClass Bullet _bulletCollideWorldBounds _bulletKillType KILL_WORLD_BOUNDS customBody bulletBounds bulletFrames bulletFrameIndex anims onFire onKill onFireLimit trackedSprite trackedPointer trackRotation trackOffset _nextFire KILL_NEVER KILL_LIFESPAN KILL_DISTANCE KILL_WEAPON_BOUNDS KILL_CAMERA_BOUNDS KILL_STATIC_BOUNDS killAll resetShots newLimit fire trackSprite trackPointer moveX moveY bullet bulletManager killType bulletKillType killDistance rotateToVelocity bodyDirty bulletCollideWorldBounds fireAtPointer fireAtSprite fireAtXY setBulletBodyOffset setBulletFrames cycle addBulletAnimation debugBodies onAccess onError onTimeout videoStream isStreaming retryLimit retry retryInterval _retryID _pending _autoplay _endCallback _playCallback _video createVideoFromBlob videoWidth videoHeight createVideoFromURL snapshot connectToMediaStream stream startMediaStream captureAudio removeVideoElement setAttribute getUserMediaTimeout getUserMediaSuccess getUserMediaError mozSrcObject createObjectURL onloadeddata checkStream checkVideoProgress change playbackRate setPause setResume playHandler getTracks track playing ended changeSource grab hasChildNodes firstChild removeAttribute


module.exports = {

    docs: ['<%= docs_dir %>/*'],
    build: ['<%= compile_dir %>/*', '<%= modules_dir %>/*.js'],
    release: ['<%= release_dir %>/*.js', '<%= release_dir %>/*.map', '<%= release_custom_dir %>/*'],
    out: ['out']

};