Merge remote-tracking branch 'origin/master'

This commit is contained in:
Pavle Goloskokovic 2017-11-26 15:50:18 +01:00
commit 995f04f34a
43 changed files with 1318 additions and 616 deletions

View file

@ -0,0 +1,126 @@
/**
* 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.
*/
var Class = require('../../utils/Class');
var ImageCollection = new Class({
initialize:
function ImageCollection (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;
},
/**
* 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++;
}
});
module.exports = ImageCollection;

View file

@ -28,13 +28,15 @@ var Tilemap = new Class({
this.properties = mapData.properties;
this.widthInPixels = mapData.widthInPixels;
this.heightInPixels = mapData.heightInPixels;
this.imageCollections = mapData.imageCollections;
this.images = mapData.images;
this.collision = mapData.collision;
this.layers = mapData.layers;
this.tilesets = mapData.tilesets;
this.tiles = mapData.tiles;
this.objects = mapData.objects;
this.currentLayerIndex = 0;
// TODO: collision, collideIndexes, imagecollections, images
// TODO: debugging methods
},
@ -225,16 +227,21 @@ var Tilemap = new Class({
return TilemapComponents.FindByIndex(findIndex, skip, reverse, layer);
},
forEachTile: function (callback, context, tileX, tileY, width, height, layer)
forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions, layer)
{
layer = this.getLayer(layer);
if (layer !== null)
{
TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, layer);
TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, layer);
}
return this;
},
getImageIndex: function (name)
{
return this.getIndex(this.images, name);
},
getIndex: function (location, name)
{
for (var i = 0; i < location.length; i++)
@ -296,11 +303,25 @@ var Tilemap = new Class({
return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, layer);
},
getTilesWithin: function (tileX, tileY, width, height, layer)
getTilesWithin: function (tileX, tileY, width, height, filteringOptions, layer)
{
layer = this.getLayer(layer);
if (layer === null) { return null; }
return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, layer);
return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer);
},
getTilesWithinShape: function (shape, filteringOptions, camera, layer)
{
layer = this.getLayer(layer);
if (layer === null) { return null; }
return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, layer);
},
getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera, layer)
{
layer = this.getLayer(layer);
if (layer === null) { return null; }
return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, layer);
},
getTilesetIndex: function (name)
@ -489,25 +510,25 @@ var Tilemap = new Class({
return this;
},
worldToTileX: function (worldX, camera, layer)
worldToTileX: function (worldX, snapToFloor, camera, layer)
{
layer = this.getLayer(layer);
if (layer === null) { return null; }
return TilemapComponents.WorldToTileX(worldX, camera, layer);
return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, layer);
},
worldToTileY: function (worldY, camera, layer)
worldToTileY: function (worldY, snapToFloor, camera, layer)
{
layer = this.getLayer(layer);
if (layer === null) { return null; }
return TilemapComponents.WorldToTileY(worldY, camera, layer);
return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, layer);
},
worldToTileXY: function (worldX, worldY, point, camera, layer)
worldToTileXY: function (worldX, worldY, snapToFloor, point, camera, layer)
{
layer = this.getLayer(layer);
if (layer === null) { return null; }
return TilemapComponents.WorldToTileXY(worldX, worldY, point, camera, layer);
return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer);
},
_isStaticCall: function (layer, functionName)

View file

@ -4,12 +4,14 @@ var Tileset = new Class({
initialize:
function Tileset (name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, properties)
function Tileset (name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, properties, tileData)
{
if (tileWidth === undefined || tileWidth <= 0) { tileWidth = 32; }
if (tileHeight === undefined || tileHeight <= 0) { tileHeight = 32; }
if (tileMargin === undefined) { tileMargin = 0; }
if (tileSpacing === undefined) { tileSpacing = 0; }
if (properties === undefined) { properties = {}; }
if (tileData === undefined) { tileData = {}; }
this.name = name;
this.firstgid = firstgid;
@ -18,6 +20,7 @@ var Tileset = new Class({
this.tileMargin = tileMargin;
this.tileSpacing = tileSpacing;
this.properties = properties;
this.tileData = tileData;
this.image = null;
this.rows = 0;
this.columns = 0;
@ -25,6 +28,18 @@ var Tileset = new Class({
this.texCoordinates = [];
},
getTileProperty: function (tileIndex)
{
if (!this.containsTileIndex(tileIndex)) { return null; }
return this.properties[tileIndex - this.firstgid];
},
getTileData: function (tileIndex)
{
if (!this.containsTileIndex(tileIndex)) { return null; }
return this.tileData[tileIndex - this.firstgid];
},
setImage: function (texture)
{
this.image = texture;

View file

@ -8,7 +8,7 @@ var CalculateFacesWithin = function (tileX, tileY, width, height, layer)
var left = null;
var right = null;
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer);
for (var i = 0; i < tiles.length; i++)
{

View file

@ -6,7 +6,7 @@ var Copy = function (srcTileX, srcTileY, width, height, destTileX, destTileY, la
if (srcTileX === undefined || srcTileX < 0) { srcTileX = 0; }
if (srcTileY === undefined || srcTileY < 0) { srcTileY = 0; }
var srcTiles = GetTilesWithin(srcTileX, srcTileY, width, height, layer);
var srcTiles = GetTilesWithin(srcTileX, srcTileY, width, height, null, layer);
var offsetX = destTileX - srcTileX;
var offsetY = destTileY - srcTileY;

View file

@ -10,6 +10,8 @@ var CullTiles = function (layer, camera, outputArray)
var mapHeight = layer.height;
var left = (camera.scrollX * tilemapLayer.scrollFactorX) - tilemapLayer.x;
var top = (camera.scrollY * tilemapLayer.scrollFactorY) - tilemapLayer.y;
var tileWidth = layer.tileWidth * tilemapLayer.scaleX;
var tileHeight = layer.tileHeight * tilemapLayer.scaleY;
for (var row = 0; row < mapHeight; ++row)
{
@ -19,13 +21,13 @@ var CullTiles = function (layer, camera, outputArray)
if (tile === null || (tile.index <= 0 && tilemapLayer.skipIndexZero)) { continue; }
var tileX = tile.worldX - left;
var tileY = tile.worldY - top;
var cullW = camera.width + tile.width;
var cullH = camera.height + tile.height;
var tileX = tile.x * tileWidth - left;
var tileY = tile.y * tileHeight - top;
var cullW = camera.width + tileWidth;
var cullH = camera.height + tileHeight;
if (tile.visible &&
tileX > -tile.width && tileY > -tile.height &&
tileX > -tileWidth && tileY > -tileHeight &&
tileX < cullW && tileY < cullH)
{
outputArray.push(tile);

View file

@ -3,7 +3,7 @@ var GetTilesWithin = require('./GetTilesWithin');
// Fills indices, not other properties. Does not modify collisions. Matches v2 functionality.
var Fill = function (index, tileX, tileY, width, height, layer)
{
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer);
for (var i = 0; i < tiles.length; i++)
{
tiles[i].index = index;

View file

@ -1,8 +1,8 @@
var GetTilesWithin = require('./GetTilesWithin');
var ForEachTile = function (callback, context, tileX, tileY, width, height, layer)
var ForEachTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer)
{
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer);
tiles.forEach(callback, context);
};

View file

@ -4,8 +4,8 @@ var WorldToTileY = require('./WorldToTileY');
var GetTileAtWorldXY = function (worldX, worldY, nonNull, camera, layer)
{
var tileX = WorldToTileX(worldX, camera, layer);
var tileY = WorldToTileY(worldY, camera, layer);
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return GetTileAt(tileX, tileY, nonNull, layer);
};

View file

@ -1,13 +1,44 @@
// TODO: add options for filtering by empty, collides, interestingFace
var GetTilesWithin = function (tileX, tileY, width, height, layer)
var GetFastValue = require('../../../utils/object/GetFastValue');
// Get tiles within the rectangular area specified. Note: this clips the x, y, w & h to the map's
// boundries.
// Options:
// {
// isNotEmpty: false,
// isColliding: false,
// hasInterestingFace: false
// }
var GetTilesWithin = function (tileX, tileY, width, height, filteringOptions, layer)
{
if (tileX === undefined || tileX < 0) { tileX = 0; }
if (tileY === undefined || tileY < 0) { tileY = 0; }
if (width === undefined || tileX + width > layer.width)
if (tileX === undefined) { tileX = 0; }
if (tileY === undefined) { tileY = 0; }
if (width === undefined) { width = layer.width; }
if (height === undefined) { height = layer.height; }
var isNotEmpty = GetFastValue(filteringOptions, 'isNotEmpty', false);
var isColliding = GetFastValue(filteringOptions, 'isColliding', false);
var hasInterestingFace = GetFastValue(filteringOptions, 'hasInterestingFace', false);
// Clip x, y to top left of map, while shrinking width/height to match.
if (tileX < 0)
{
width += tileX;
tileX = 0;
}
if (tileY < 0)
{
height += tileY;
tileY = 0;
}
// Clip width and height to bottom right of map.
if (tileX + width > layer.width)
{
width = Math.max(layer.width - tileX, 0);
}
if (height === undefined || tileY + height > layer.height)
if (tileY + height > layer.height)
{
height = Math.max(layer.height - tileY, 0);
}
@ -21,6 +52,9 @@ var GetTilesWithin = function (tileX, tileY, width, height, layer)
var tile = layer.data[ty][tx];
if (tile !== null)
{
if (isNotEmpty && tile.index === -1) { continue; }
if (isColliding && !tile.collides) { continue; }
if (hasInterestingFace && !tile.hasInterestingFace) { continue; }
results.push(tile);
}
}

View file

@ -0,0 +1,68 @@
var GetTilesWithin = require('./GetTilesWithin');
var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require('./WorldToTileY');
var TileToWorldX = require('./TileToWorldX');
var TileToWorldY = require('./TileToWorldY');
var Geom = require('../../../geom/');
var Intersects = require('../../../geom/intersects/');
var NOOP = require('../../../utils/NOOP');
var TriangleToRectangle = function (triangle, rect)
{
return Intersects.RectangleToTriangle(rect, triangle);
};
// Circle, Line, Rect, Triangle in world coordinates.
// Notes: circle is not working yet - see CircleToRectangle in geom. Could possibly be optimized
// by copying the shape and shifting it into tilemapLayer coordinates instead of shifting the tiles.
var GetTilesWithinShape = function (shape, filteringOptions, camera, layer)
{
if (shape === undefined) { return []; }
// intersectTest is a function with parameters: shape, rect
var intersectTest = NOOP;
if (shape instanceof Geom.Circle) { intersectTest = Intersects.CircleToRectangle; }
else if (shape instanceof Geom.Rectangle) { intersectTest = Intersects.RectangleToRectangle; }
else if (shape instanceof Geom.Triangle) { intersectTest = TriangleToRectangle; }
else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle; }
// Top left corner of the shapes's bounding box, rounded down to include partial tiles
var xStart = WorldToTileX(shape.left, true, camera, layer);
var yStart = WorldToTileY(shape.top, true, camera, layer);
// Bottom right corner of the shapes's bounding box, rounded up to include partial tiles
var xEnd = Math.ceil(WorldToTileX(shape.right, false, camera, layer));
var yEnd = Math.ceil(WorldToTileY(shape.bottom, false, camera, layer));
// Tiles within bounding rectangle of shape. Bounds are forced to be at least 1 x 1 tile in size
// to grab tiles for shapes that don't have a height or width (e.g. a horizontal line).
var width = Math.max(xEnd - xStart, 1);
var height = Math.max(yEnd - yStart, 1);
var tiles = GetTilesWithin(xStart, yStart, width, height, filteringOptions, layer);
var tileWidth = layer.tileWidth;
var tileHeight = layer.tileHeight;
if (layer.tilemapLayer)
{
tileWidth *= layer.tilemapLayer.scaleX;
tileHeight *= layer.tilemapLayer.scaleY;
}
var results = [];
var tileRect = new Geom.Rectangle(0, 0, tileWidth, tileHeight);
for (var i = 0; i < tiles.length; i++)
{
var tile = tiles[i];
tileRect.x = TileToWorldX(tile.x, camera, layer);
tileRect.y = TileToWorldY(tile.y, camera, layer);
if (intersectTest(shape, tileRect))
{
results.push(tile);
}
}
return results;
};
module.exports = GetTilesWithinShape;

View file

@ -0,0 +1,18 @@
var GetTilesWithin = require('./GetTilesWithin');
var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require('./WorldToTileY');
var GetTilesWithinWorldXY = function (worldX, worldY, width, height, filteringOptions, camera, layer)
{
// Top left corner of the rect, rounded down to include partial tiles
var xStart = WorldToTileX(worldX, true, camera, layer);
var yStart = WorldToTileY(worldY, true, camera, layer);
// Bottom right corner of the rect, rounded up to include partial tiles
var xEnd = Math.ceil(WorldToTileX(worldX + width, false, camera, layer));
var yEnd = Math.ceil(WorldToTileY(worldY + height, false, camera, layer));
return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer);
};
module.exports = GetTilesWithinWorldXY;

View file

@ -4,8 +4,8 @@ var WorldToTileY = require('./WorldToTileY');
var HasTileAtWorldXY = function (worldX, worldY, camera, layer)
{
var tileX = WorldToTileX(worldX, camera, layer);
var tileY = WorldToTileY(worldY, camera, layer);
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return HasTileAt(tileX, tileY, layer);
};

View file

@ -4,9 +4,9 @@ var WorldToTileY = require('./WorldToTileY');
var PutTileAtWorldXY = function (tile, worldX, worldY, recalculateFaces, camera, layer)
{
var tileX = WorldToTileX(worldX, camera, layer);
var tileY = WorldToTileY(worldY, camera, layer);
return PutTileAt(tile, tileX, tileY, layer);
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return PutTileAt(tile, tileX, tileY, recalculateFaces, layer);
};
module.exports = PutTileAtWorldXY;

View file

@ -5,7 +5,7 @@ var GetRandomElement = require('../../../utils/array/GetRandomElement');
var Randomize = function (tileX, tileY, width, height, indices, layer)
{
var i;
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer);
// If no indicies are given, then find all the unique indices within the specified region
if (indices === undefined)

View file

@ -4,9 +4,9 @@ var WorldToTileY = require('./WorldToTileY');
var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer)
{
var tileX = WorldToTileX(worldX, camera, layer);
var tileY = WorldToTileY(worldY, camera, layer);
return RemoveTileAt(tileX, tileY, replaceWithNull, layer);
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer);
};
module.exports = RemoveTileAtWorldXY;

View file

@ -3,7 +3,7 @@ var GetTilesWithin = require('./GetTilesWithin');
// Replaces indices, not other properties. Does not modify collisions. Matches v2 functionality.
var ReplaceByIndex = function (findIndex, newIndex, tileX, tileY, width, height, layer)
{
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer);
for (var i = 0; i < tiles.length; i++)
{
if (tiles[i] && tiles[i].index === findIndex)

View file

@ -4,7 +4,7 @@ var ShuffleArray = require('../../../utils/array/Shuffle');
// Shuffles indices, not other properties. Does not modify collisions. Matches v2 functionality.
var Shuffle = function (tileX, tileY, width, height, layer)
{
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer);
var indices = tiles.map(function (tile) { return tile.index; });
ShuffleArray(indices);

View file

@ -3,7 +3,7 @@ var GetTilesWithin = require('./GetTilesWithin');
// Swaps indices, not other properties. Does not modify collisions. Matches v2 functionality.
var SwapByIndex = function (indexA, indexB, tileX, tileY, width, height, layer)
{
var tiles = GetTilesWithin(tileX, tileY, width, height, layer);
var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer);
for (var i = 0; i < tiles.length; i++)
{
if (tiles[i])

View file

@ -0,0 +1,19 @@
var TileToWorldX = function (tileX, camera, layer)
{
var tileWidth = layer.tileWidth;
var tilemapLayer = layer.tilemapLayer;
var layerWorldX = 0;
if (tilemapLayer)
{
if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; }
layerWorldX = tilemapLayer.x - (camera.scrollX * tilemapLayer.scrollFactorX);
tileWidth *= tilemapLayer.scaleX;
}
return layerWorldX + tileX * tileWidth;
};
module.exports = TileToWorldX;

View file

@ -0,0 +1,19 @@
var TileToWorldY = function (tileY, camera, layer)
{
var tileHeight = layer.tileHeight;
var tilemapLayer = layer.tilemapLayer;
var layerWorldY = 0;
if (tilemapLayer)
{
if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; }
layerWorldY = tilemapLayer.y - (camera.scrollY * tilemapLayer.scrollFactorY);
tileHeight *= tilemapLayer.scaleY;
}
return layerWorldY + tileY * tileHeight;
};
module.exports = TileToWorldY;

View file

@ -1,8 +1,10 @@
var SnapFloor = require('../../../math/snap/SnapFloor');
var WorldToTileX = function (worldX, camera, layer)
var WorldToTileX = function (worldX, snapToFloor, camera, layer)
{
if (snapToFloor === undefined) { snapToFloor = true; }
var tileWidth = layer.tileWidth;
var tilemapLayer = layer.tilemapLayer;
if (tilemapLayer)
{
if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; }
@ -10,9 +12,13 @@ var WorldToTileX = function (worldX, camera, layer)
// Find the world position relative to the static or dynamic layer's top left origin,
// factoring in the camera's horizontal scroll
worldX = worldX + (camera.scrollX * tilemapLayer.scrollFactorX) - tilemapLayer.x;
tileWidth *= tilemapLayer.scaleX;
}
return SnapFloor(worldX, layer.tileWidth) / layer.tileWidth;
return snapToFloor
? Math.floor(worldX / tileWidth)
: worldX / tileWidth;
};
module.exports = WorldToTileX;

View file

@ -2,12 +2,12 @@ var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require('./WorldToTileY');
var Vector2 = require('../../../math/Vector2');
var WorldToTileXY = function (worldX, worldY, point, camera, layer)
var WorldToTileXY = function (worldX, worldY, snapToFloor, point, camera, layer)
{
if (point === undefined) { point = new Vector2(0, 0); }
point.x = WorldToTileX(worldX, camera, layer);
point.y = WorldToTileY(worldY, camera, layer);
point.x = WorldToTileX(worldX, snapToFloor, camera, layer);
point.y = WorldToTileY(worldY, snapToFloor, camera, layer);
return point;
};

View file

@ -1,18 +1,24 @@
var SnapFloor = require('../../../math/snap/SnapFloor');
var WorldToTileY = function (worldY, camera, layer)
var WorldToTileY = function (worldY, snapToFloor, camera, layer)
{
if (snapToFloor === undefined) { snapToFloor = true; }
var tileHeight = layer.tileHeight;
var tilemapLayer = layer.tilemapLayer;
if (tilemapLayer)
{
if (camera === undefined) { camera = tilemapLayer.scene.cameras.main; }
// Find the world position relative to the static or dynamic layer's top left origin,
// factoring in the camera's horizontal scroll
// factoring in the camera's vertical scroll
worldY = worldY + (camera.scrollY * tilemapLayer.scrollFactorY) - tilemapLayer.y;
tileHeight *= tilemapLayer.scaleY;
}
return SnapFloor(worldY, layer.tileWidth) / layer.tileWidth;
return snapToFloor
? Math.floor(worldY / tileHeight)
: worldY / tileHeight;
};
module.exports = WorldToTileY;

View file

@ -8,6 +8,8 @@ module.exports = {
GetTileAt: require('./GetTileAt'),
GetTileAtWorldXY: require('./GetTileAtWorldXY'),
GetTilesWithin: require('./GetTilesWithin'),
GetTilesWithinShape: require('./GetTilesWithinShape'),
GetTilesWithinWorldXY: require('./GetTilesWithinWorldXY'),
HasTileAt: require('./HasTileAt'),
HasTileAtWorldXY: require('./HasTileAtWorldXY'),
IsInLayerBounds: require('./IsInLayerBounds'),

View file

@ -87,9 +87,9 @@ var DynamicTilemapLayer = new Class({
return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer);
},
forEachTile: function (callback, context, tileX, tileY, width, height)
forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions)
{
TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, this.layer);
TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer);
return this;
},
@ -103,9 +103,19 @@ var DynamicTilemapLayer = new Class({
return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer);
},
getTilesWithin: function (tileX, tileY, width, height)
getTilesWithin: function (tileX, tileY, width, height, filteringOptions)
{
return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, this.layer);
return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer);
},
getTilesWithinShape: function (shape, filteringOptions, camera)
{
return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer);
},
getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera)
{
return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer);
},
hasTileAt: function (tileX, tileY)
@ -180,19 +190,19 @@ var DynamicTilemapLayer = new Class({
return this;
},
worldToTileX: function (worldX, camera)
worldToTileX: function (worldX, snapToFloor, camera)
{
return TilemapComponents.WorldToTileX(worldX, camera, this.layer);
return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer);
},
worldToTileY: function (worldY, camera)
worldToTileY: function (worldY, snapToFloor, camera)
{
return TilemapComponents.WorldToTileY(worldY, camera, this.layer);
return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer);
},
worldToTileXY: function (worldX, worldY, point, camera)
worldToTileXY: function (worldX, worldY, snapToFloor, point, camera)
{
return TilemapComponents.WorldToTileXY(worldX, worldY, point, camera, this.layer);
return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer);
}
});

View file

@ -22,6 +22,8 @@ var DynamicTilemapLayerWebGLRenderer = function (renderer, gameObject, interpola
var alpha = gameObject.alpha;
var x = gameObject.x;
var y = gameObject.y;
var sx = gameObject.scaleX;
var sy = gameObject.scaleY;
for (var index = 0; index < length; ++index)
{
@ -37,7 +39,9 @@ var DynamicTilemapLayerWebGLRenderer = function (renderer, gameObject, interpola
batch.addTileTextureRect(
texture,
x + tile.worldX, y + tile.worldY, tile.width, tile.height, alpha * tile.alpha, tile.tint,
x + tile.worldX * sx, y + tile.worldY * sy,
tile.width * sx, tile.height * sy,
alpha * tile.alpha, tile.tint,
scrollFactorX, scrollFactorY,
textureWidth, textureHeight,
frameX, frameY, frameWidth, frameHeight,

View file

@ -25,6 +25,7 @@ var MapData = new Class({
this.objects = GetFastValue(config, 'objects', {});
this.collision = GetFastValue(config, 'collision', {});
this.tilesets = GetFastValue(config, 'tilesets', []);
this.imageCollections = GetFastValue(config, 'imageCollections', []);
this.tiles = GetFastValue(config, 'tiles', []);
}

View file

@ -1,7 +1,7 @@
var Parse2DArray = require('./Parse2DArray');
var ParseCSV = require('./ParseCSV');
var ParseTiledJSON = require('./ParseTiledJSON');
var ParseTiledJSON = require('./parsetiledjson/');
var Formats = require('../Formats');
var Parse = function (key, mapFormat, mapData, tileWidth, tileHeight, insertNull)

View file

@ -1,522 +0,0 @@
var Formats = require('../Formats');
var Tileset = require('../Tileset');
var Tile = require('../Tile');
var Extend = require('../../../utils/object/Extend');
var MapData = require('../mapdata/MapData');
var LayerData = require('../mapdata/LayerData');
var ParseJSONTiled = function (key, json, insertNull)
{
if (json.orientation !== 'orthogonal')
{
console.warn('Only orthogonal map types are supported in this version of Phaser');
return null;
}
// Map data will consist of: layers, objects, images, tilesets, sizes
var mapData = new MapData({
width: json.width,
height: json.height,
name: key,
tileWidth: json.tilewidth,
tileHeight: json.tileheight,
orientation: json.orientation,
format: Formats.TILEMAP_TILED_JSON,
version: json.version,
properties: json.properties
});
// Tile Layers
var layers = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'tilelayer')
{
continue;
}
var curl = json.layers[i];
// Base64 decode data if necessary
// NOTE: uncompressed base64 only.
if (!curl.compression && curl.encoding && curl.encoding === 'base64')
{
var binaryString = window.atob(curl.data);
var len = binaryString.length;
var bytes = new Array(len);
// Interpret binaryString as an array of bytes representing
// little-endian encoded uint32 values.
for (var j = 0; j < len; j += 4)
{
bytes[j / 4] = (
binaryString.charCodeAt(j) |
binaryString.charCodeAt(j + 1) << 8 |
binaryString.charCodeAt(j + 2) << 16 |
binaryString.charCodeAt(j + 3) << 24
) >>> 0;
}
curl.data = bytes;
delete curl.encoding;
}
else if (curl.compression)
{
console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\'');
continue;
}
var layerData = new LayerData({
name: curl.name,
x: curl.x,
y: curl.y,
width: curl.width,
height: curl.height,
tileWidth: json.tilewidth,
tileHeight: json.tileheight,
alpha: curl.opacity,
visible: curl.visible,
properties: {},
indexes: [],
callbacks: [],
bodies: []
});
if (curl.properties)
{
layerData.properties = curl.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 = curl.data.length; t < len; t++)
{
rotation = 0;
flipped = false;
gid = curl.data[t];
flippedVal = 0;
// If true the current tile is flipped or rotated (Tiled TMX format)
if (gid > 0x20000000)
{
// FlippedX
if (gid > 0x80000000)
{
gid -= 0x80000000;
flippedVal += 4;
}
// FlippedY
if (gid > 0x40000000)
{
gid -= 0x40000000;
flippedVal += 2;
}
// FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners)
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)
{
var tile = new Tile(layerData, gid, x, output.length, json.tilewidth, json.tileheight);
tile.rotation = rotation;
tile.flipped = flipped;
if (flippedVal !== 0)
{
// The WebGL renderer uses this to flip UV coordinates before drawing
tile.flippedVal = flippedVal;
}
row.push(tile);
}
else
{
var blankTile = insertNull
? null
: new Tile(layerData, -1, x, output.length, json.tilewidth, json.tileheight);
row.push(blankTile);
}
x++;
if (x === curl.width)
{
output.push(row);
x = 0;
row = [];
}
}
layerData.data = output;
layers.push(layerData);
}
mapData.layers = layers;
// Images
var images = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'imagelayer')
{
continue;
}
var curi = json.layers[i];
var image = {
name: curi.name,
image: curi.image,
x: curi.x,
y: curi.y,
alpha: curi.opacity,
visible: curi.visible,
properties: {}
};
if (curi.properties)
{
image.properties = curi.properties;
}
images.push(image);
}
mapData.images = images;
// Tilesets & Image Collections
var tilesets = [];
var imagecollections = [];
var lastSet = null;
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 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
{
// TODO: ImageCollection
// var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
// for (var ti in set.tiles)
// {
// var image = set.tiles[ti].image;
// var gid = set.firstgid + parseInt(ti, 10);
// newCollection.addImage(gid, image);
// }
// imagecollections.push(newCollection);
}
// We've got a new Tileset, so set the lastgid into the previous one
if (lastSet)
{
lastSet.lastgid = set.firstgid - 1;
}
lastSet = set;
}
mapData.tilesets = tilesets;
mapData.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;
}
var curo = json.layers[i];
objects[curo.name] = [];
collision[curo.name] = [];
for (var v = 0, len = curo.objects.length; v < len; v++)
{
// Object Tiles
if (curo.objects[v].gid)
{
var object = {
gid: curo.objects[v].gid,
name: curo.objects[v].name,
type: curo.objects[v].hasOwnProperty('type') ? curo.objects[v].type : '',
x: curo.objects[v].x,
y: curo.objects[v].y,
visible: curo.objects[v].visible,
properties: curo.objects[v].properties
};
if (curo.objects[v].rotation)
{
object.rotation = curo.objects[v].rotation;
}
objects[curo.name].push(object);
}
else if (curo.objects[v].polyline)
{
var object = {
name: curo.objects[v].name,
type: curo.objects[v].type,
x: curo.objects[v].x,
y: curo.objects[v].y,
width: curo.objects[v].width,
height: curo.objects[v].height,
visible: curo.objects[v].visible,
properties: curo.objects[v].properties
};
if (curo.objects[v].rotation)
{
object.rotation = curo.objects[v].rotation;
}
object.polyline = [];
// Parse the polyline into an array
for (var p = 0; p < curo.objects[v].polyline.length; p++)
{
object.polyline.push([ curo.objects[v].polyline[p].x, curo.objects[v].polyline[p].y ]);
}
collision[curo.name].push(object);
objects[curo.name].push(object);
}
// polygon
else if (curo.objects[v].polygon)
{
var object = slice(curo.objects[v], [ 'name', 'type', 'x', 'y', 'visible', 'rotation', 'properties' ]);
// Parse the polygon into an array
object.polygon = [];
for (var p = 0; p < curo.objects[v].polygon.length; p++)
{
object.polygon.push([ curo.objects[v].polygon[p].x, curo.objects[v].polygon[p].y ]);
}
objects[curo.name].push(object);
}
// ellipse
else if (curo.objects[v].ellipse)
{
var object = slice(curo.objects[v], [ 'name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties' ]);
objects[curo.name].push(object);
}
// otherwise it's a rectangle
else
{
var object = slice(curo.objects[v], [ 'name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties' ]);
object.rectangle = true;
objects[curo.name].push(object);
}
}
}
mapData.objects = objects;
mapData.collision = collision;
mapData.tiles = [];
// Finally lets build our super tileset index
for (var i = 0; i < mapData.tilesets.length; i++)
{
var set = mapData.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
mapData.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 layerData;
var tile;
var sid;
var set;
// go through each of the map data layers
for (var i = 0; i < mapData.layers.length; i++)
{
layerData = mapData.layers[i];
set = null;
// rows of tiles
for (var j = 0; j < layerData.data.length; j++)
{
row = layerData.data[j];
// individual tiles
for (var k = 0; k < row.length; k++)
{
tile = row[k];
if (tile === null || tile.index < 0)
{
continue;
}
// find the relevant tileset
sid = mapData.tiles[tile.index][2];
set = mapData.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 = Extend(tile.properties, set.tileProperties[tile.index - set.firstgid]);
}
}
}
}
return mapData;
};
module.exports = ParseJSONTiled;

View file

@ -0,0 +1,21 @@
var Base64Decode = function (data)
{
var binaryString = window.atob(data);
var len = binaryString.length;
var bytes = new Array(len);
// Interpret binaryString as an array of bytes representing little-endian encoded uint32 values.
for (var i = 0; i < len; i += 4)
{
bytes[i / 4] = (
binaryString.charCodeAt(i) |
binaryString.charCodeAt(i + 1) << 8 |
binaryString.charCodeAt(i + 2) << 16 |
binaryString.charCodeAt(i + 3) << 24
) >>> 0;
}
return bytes;
};
module.exports = Base64Decode;

View file

@ -0,0 +1,71 @@
var FLIPPED_HORIZONTAL = 0x80000000;
var FLIPPED_VERTICAL = 0x40000000;
var FLIPPED_ANTI_DIAGONAL = 0x20000000; // Top-right is swapped with bottom-left corners
// See Tiled documentation on tile flipping:
// http://docs.mapeditor.org/en/latest/reference/tmx-map-format/
var ParseGID = function (gid)
{
var flippedHorizontal = Boolean(gid & FLIPPED_HORIZONTAL);
var flippedVertical = Boolean(gid & FLIPPED_VERTICAL);
var flippedAntiDiagonal = Boolean(gid & FLIPPED_ANTI_DIAGONAL);
gid = gid & ~(FLIPPED_HORIZONTAL | FLIPPED_VERTICAL | FLIPPED_ANTI_DIAGONAL);
// Parse the flip flags into something Phaser can use
var rotation = 0;
var flipped = false;
if (flippedHorizontal && flippedVertical && flippedAntiDiagonal)
{
rotation = Math.PI / 2;
flipped = true;
}
else if (flippedHorizontal && flippedVertical && !flippedAntiDiagonal)
{
rotation = Math.PI;
flipped = false;
}
else if (flippedHorizontal && !flippedVertical && flippedAntiDiagonal)
{
rotation = Math.PI / 2;
flipped = false;
}
else if (flippedHorizontal && !flippedVertical && !flippedAntiDiagonal)
{
rotation = 0;
flipped = true;
}
else if (!flippedHorizontal && flippedVertical && flippedAntiDiagonal)
{
rotation = 3 * Math.PI / 2;
flipped = false;
}
else if (!flippedHorizontal && flippedVertical && !flippedAntiDiagonal)
{
rotation = Math.PI;
flipped = true;
}
else if (!flippedHorizontal && !flippedVertical && flippedAntiDiagonal)
{
rotation = 3 * Math.PI / 2;
flipped = true;
}
else if (!flippedHorizontal && !flippedVertical && !flippedAntiDiagonal)
{
rotation = 0;
flipped = false;
}
return {
gid: gid,
flippedHorizontal: flippedHorizontal,
flippedVertical: flippedVertical,
flippedAntiDiagonal: flippedAntiDiagonal,
rotation: rotation,
flipped: flipped
};
};
module.exports = ParseGID;

View file

@ -0,0 +1,58 @@
var Pick = require('./Pick');
var ParseGID = require('./ParseGID');
var pointToArray = function (p) { return [ p.x, p.y ]; };
var commonObjectProps = [ 'id', 'name', 'type', 'rotation', 'properties', 'visible', 'x', 'y' ];
var ParseObject = function (tiledObject, offsetX, offsetY)
{
if (offsetX === undefined) { offsetX = 0; }
if (offsetY === undefined) { offsetY = 0; }
var parsedObject = Pick(tiledObject, commonObjectProps);
parsedObject.x += offsetX;
parsedObject.y += offsetY;
if (tiledObject.gid)
{
// Object tiles
var gidInfo = ParseGID(tiledObject.gid);
parsedObject.gid = gidInfo.gid;
parsedObject.flippedHorizontal = gidInfo.flippedHorizontal;
parsedObject.flippedVertical = gidInfo.flippedVertical;
parsedObject.flippedAntiDiagonal = gidInfo.flippedAntiDiagonal;
}
else if (tiledObject.polyline)
{
parsedObject.polyline = tiledObject.polyline.map(pointToArray);
}
else if (tiledObject.polygon)
{
parsedObject.polygon = tiledObject.polygon.map(pointToArray);
}
else if (tiledObject.ellipse)
{
parsedObject.ellipse = tiledObject.ellipse;
parsedObject.width = tiledObject.width;
parsedObject.height = tiledObject.height;
}
else if (tiledObject.text)
{
parsedObject.width = tiledObject.width;
parsedObject.height = tiledObject.height;
parsedObject.text = tiledObject.text;
}
else
{
// Otherwise, assume it is a rectangle
parsedObject.rectangle = true;
parsedObject.width = tiledObject.width;
parsedObject.height = tiledObject.height;
}
return parsedObject;
};
module.exports = ParseObject;

View file

@ -0,0 +1,19 @@
var HasValue = require('../../../../utils/object/HasValue');
var pick = function (object, keys)
{
var obj = {};
for (var i = 0; i < keys.length; i++)
{
var key = keys[i];
if (HasValue(object, key))
{
obj[key] = object[key];
}
}
return obj;
};
module.exports = pick;

View file

@ -0,0 +1,344 @@
var Formats = require('../../Formats');
var Tileset = require('../../Tileset');
var Tile = require('../../Tile');
var Extend = require('../../../../utils/object/Extend');
var MapData = require('../../mapdata/MapData');
var LayerData = require('../../mapdata/LayerData');
var ImageCollection = require('../../ImageCollection');
var GetFastValue = require('../../../../utils/object/GetFastValue');
var ParseGID = require('./ParseGID');
var Base64Decode = require('./Base64Decode');
var ParseObject = require('./ParseObject');
var ParseJSONTiled = function (key, json, insertNull)
{
if (json.orientation !== 'orthogonal')
{
console.warn('Only orthogonal map types are supported in this version of Phaser');
return null;
}
// Map data will consist of: layers, objects, images, tilesets, sizes
var mapData = new MapData({
width: json.width,
height: json.height,
name: key,
tileWidth: json.tilewidth,
tileHeight: json.tileheight,
orientation: json.orientation,
format: Formats.TILEMAP_TILED_JSON,
version: json.version,
properties: json.properties
});
var tileLayers = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'tilelayer')
{
continue;
}
var curl = json.layers[i];
// Base64 decode data if necessary. NOTE: uncompressed base64 only.
if (curl.compression)
{
console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\'');
continue;
}
else if (curl.encoding && curl.encoding === 'base64')
{
curl.data = Base64Decode(curl.data);
}
var layerData = new LayerData({
name: curl.name,
x: GetFastValue(curl, 'offsetx', 0) + curl.x,
y: GetFastValue(curl, 'offsety', 0) + curl.y,
width: curl.width,
height: curl.height,
tileWidth: json.tilewidth,
tileHeight: json.tileheight,
alpha: curl.opacity,
visible: curl.visible,
properties: GetFastValue(curl, 'properties', {})
});
var x = 0;
var row = [];
var output = [];
var 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 = curl.data.length; t < len; t++)
{
var gidInfo = ParseGID(curl.data[t]);
// index, x, y, width, height
if (gidInfo.gid > 0)
{
var tile = new Tile(layerData, gidInfo.gid, x, output.length, json.tilewidth, json.tileheight);
tile.rotation = gidInfo.rotation;
tile.flipped = gidInfo.flipped;
tile.flippedHorizontal = gidInfo.flippedHorizontal;
tile.flippedVertical = gidInfo.flippedVertical;
tile.flippedAntiDiagonal = gidInfo.flippedAntiDiagonal;
row.push(tile);
}
else
{
var blankTile = insertNull
? null
: new Tile(layerData, -1, x, output.length, json.tilewidth, json.tileheight);
row.push(blankTile);
}
x++;
if (x === curl.width)
{
output.push(row);
x = 0;
row = [];
}
}
layerData.data = output;
tileLayers.push(layerData);
}
mapData.layers = tileLayers;
var images = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'imagelayer')
{
continue;
}
var curi = json.layers[i];
images.push({
name: curi.name,
image: curi.image,
x: GetFastValue(curi, 'offsetx', 0) + curi.x,
y: GetFastValue(curi, 'offsety', 0) + curi.y,
alpha: curi.opacity,
visible: curi.visible,
properties: GetFastValue(curi, "properties", {})
});
}
mapData.images = images;
// Tilesets & Image Collections
var tilesets = [];
var imageCollections = [];
var lastSet = null;
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 Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
// Properties stored per-tile in object with string indices starting at "0"
if (set.tileproperties)
{
newSet.tileProperties = set.tileproperties;
}
// Object & terrain shapes stored per-tile in object with string indices starting at "0"
if (set.tiles)
{
newSet.tileData = set.tiles;
// Parse the objects into Phaser format to match handling of other Tiled objects
for (var stringID in newSet.tileData)
{
var objectGroup = newSet.tileData[stringID].objectgroup;
if (objectGroup && objectGroup.objects)
{
objectGroup.objects = objectGroup.objects.map(ParseObject);
}
}
}
// 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 ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
for (var stringID in set.tiles)
{
var image = set.tiles[stringID].image;
var gid = set.firstgid + parseInt(stringID, 10);
newCollection.addImage(gid, image);
}
imageCollections.push(newCollection);
}
// We've got a new Tileset, so set the lastgid into the previous one
if (lastSet)
{
lastSet.lastgid = set.firstgid - 1;
}
lastSet = set;
}
mapData.tilesets = tilesets;
mapData.imageCollections = imageCollections;
// Objects & Collision Data (polylines, etc)
var objects = {};
var collision = {};
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'objectgroup')
{
continue;
}
var curo = json.layers[i];
var layerName = curo.name;
var offsetX = GetFastValue(curo, 'offsetx', 0);
var offsetY = GetFastValue(curo, 'offsety', 0);
objects[layerName] = [];
collision[layerName] = [];
for (var j = 0; j < curo.objects.length; j++)
{
var parsedObject = ParseObject(curo.objects[j], offsetX, offsetY);
// Matching v2 where only polylines were added to collision prop of the map
if (parsedObject.polyline) { collision[layerName].push(parsedObject); }
objects[layerName].push(parsedObject);
}
}
mapData.objects = objects;
mapData.collision = collision;
mapData.tiles = [];
// Finally lets build our super tileset index
for (var i = 0; i < mapData.tilesets.length; i++)
{
var set = mapData.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
mapData.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 layerData;
var tile;
var sid;
var set;
// go through each of the map data layers
for (var i = 0; i < mapData.layers.length; i++)
{
layerData = mapData.layers[i];
set = null;
// rows of tiles
for (var j = 0; j < layerData.data.length; j++)
{
row = layerData.data[j];
// individual tiles
for (var k = 0; k < row.length; k++)
{
tile = row[k];
if (tile === null || tile.index < 0)
{
continue;
}
// find the relevant tileset
sid = mapData.tiles[tile.index][2];
set = mapData.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 = Extend(tile.properties, set.tileProperties[tile.index - set.firstgid]);
}
}
}
}
return mapData;
};
module.exports = ParseJSONTiled;

View file

@ -228,9 +228,9 @@ var StaticTilemapLayer = new Class({
return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer);
},
forEachTile: function (callback, context, tileX, tileY, width, height)
forEachTile: function (callback, context, tileX, tileY, width, height, filteringOptions)
{
TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, this.layer);
TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer);
return this;
},
@ -244,9 +244,19 @@ var StaticTilemapLayer = new Class({
return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer);
},
getTilesWithin: function (tileX, tileY, width, height)
getTilesWithin: function (tileX, tileY, width, height, filteringOptions)
{
return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, this.layer);
return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer);
},
getTilesWithinWorldXY: function (worldX, worldY, width, height, filteringOptions, camera)
{
return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer);
},
getTilesWithinShape: function (shape, filteringOptions, camera)
{
return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer);
},
hasTileAt: function (tileX, tileY)
@ -277,19 +287,19 @@ var StaticTilemapLayer = new Class({
return this;
},
worldToTileX: function (worldX, camera)
worldToTileX: function (worldX, snapToFloor, camera)
{
return TilemapComponents.WorldToTileX(worldX, camera, this.layer);
return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer);
},
worldToTileY: function (worldY, camera)
worldToTileY: function (worldY, snapToFloor, camera)
{
return TilemapComponents.WorldToTileY(worldY, camera, this.layer);
return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer);
},
worldToTileXY: function (worldX, worldY, point, camera)
worldToTileXY: function (worldX, worldY, snapToFloor, point, camera)
{
return TilemapComponents.WorldToTileXY(worldX, worldY, point, camera, this.layer);
return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer);
}
});

View file

@ -15,28 +15,28 @@ var CircleToRectangle = function (circle, rect)
var halfHeight = rect.height / 2;
var cx = Math.abs(circle.x - rect.x - halfWidth);
var xDist = halfWidth + circle.radius;
if (cx <= halfWidth || cx > xDist)
{
return false;
}
var cy = Math.abs(circle.y - rect.y - halfHeight);
var xDist = halfWidth + circle.radius;
var yDist = halfHeight + circle.radius;
if (cy <= halfHeight || cy > yDist)
if (cx > xDist || cy > yDist)
{
return false;
}
else if (cx <= halfWidth || cy <= halfHeight)
{
return true;
}
else
{
var xCornerDist = cx - halfWidth;
var yCornerDist = cy - halfHeight;
var xCornerDistSq = xCornerDist * xCornerDist;
var yCornerDistSq = yCornerDist * yCornerDist;
var maxCornerDistSq = circle.radius * circle.radius;
var xCornerDist = cx - halfWidth;
var yCornerDist = cy - halfHeight;
var xCornerDistSq = xCornerDist * xCornerDist;
var yCornerDistSq = yCornerDist * yCornerDist;
var maxCornerDistSq = circle.radius * circle.radius;
return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq);
return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq);
}
};
module.exports = CircleToRectangle;

View file

@ -1,4 +1,4 @@
var Matter = module.exports = require('./lib/core/Matter');
var Matter = require('./lib/core/Matter');
Matter.Body = require('./lib/body/Body');
Matter.Composite = require('./lib/body/Composite');
@ -38,3 +38,5 @@ Matter.World.addComposite = Matter.Composite.addComposite;
Matter.World.addBody = Matter.Composite.addBody;
Matter.World.addConstraint = Matter.Composite.addConstraint;
Matter.World.clear = Matter.Composite.clear;
module.exports = Matter;

View file

@ -1,5 +1,10 @@
var Class = require('../../utils/Class');
var Factory = require('./Factory');
var GetValue = require('../../utils/object/GetValue');
var MatterAttractors = require('./lib/plugins/MatterAttractors');
var MatterLib = require('./lib/core/Matter');
var MatterWrap = require('./lib/plugins/MatterWrap');
var Plugin = require('./lib/core/Plugin');
var World = require('./World');
var Matter = new Class({
@ -15,6 +20,36 @@ var Matter = new Class({
physicsManager.world = new World(physicsManager.scene, config);
physicsManager.add = new Factory(physicsManager.world);
// Matter plugins
if (GetValue(config, 'plugins.attractors', false))
{
Plugin.register(MatterAttractors);
Plugin.use(MatterLib, MatterAttractors);
}
if (GetValue(config, 'plugins.wrap', false))
{
Plugin.register(MatterWrap);
Plugin.use(MatterLib, MatterWrap);
}
},
enableAttractorPlugin: function ()
{
Plugin.register(MatterAttractors);
Plugin.use(MatterLib, MatterAttractors);
return this;
},
enableWrapPlugin: function ()
{
Plugin.register(MatterWrap);
Plugin.use(MatterLib, MatterWrap);
return this;
}
});

View file

@ -27,7 +27,7 @@ var Common = require('./Common');
* @readOnly
* @type {String}
*/
Matter.version = '@@VERSION@@';
Matter.version = '0.13.1';
/**
* A list of plugin dependencies to be installed. These are normally set and installed through `Matter.use`.

View file

@ -171,7 +171,7 @@ var Common = require('./Common');
module.used.push(plugin.name);
}
if (status.length > 0) {
if (status.length > 0 && !plugin.silent) {
Common.info(status.join(' '));
}
};

View file

@ -0,0 +1,136 @@
var Matter = require('../../CustomMain');
/**
* An attractors plugin for matter.js.
* See the readme for usage and examples.
* @module MatterAttractors
*/
var MatterAttractors = {
// plugin meta
name: 'matter-attractors', // PLUGIN_NAME
version: '0.1.7', // PLUGIN_VERSION
for: 'matter-js@^0.13.1',
silent: true, // no console log please
// installs the plugin where `base` is `Matter`
// you should not need to call this directly.
install: function(base) {
base.after('Body.create', function() {
MatterAttractors.Body.init(this);
});
base.before('Engine.update', function(engine) {
MatterAttractors.Engine.update(engine);
});
},
Body: {
/**
* Initialises the `body` to support attractors.
* This is called automatically by the plugin.
* @function MatterAttractors.Body.init
* @param {Matter.Body} body The body to init.
* @returns {void} No return value.
*/
init: function(body) {
body.plugin.attractors = body.plugin.attractors || [];
}
},
Engine: {
/**
* Applies all attractors for all bodies in the `engine`.
* This is called automatically by the plugin.
* @function MatterAttractors.Engine.update
* @param {Matter.Engine} engine The engine to update.
* @returns {void} No return value.
*/
update: function(engine) {
var world = engine.world,
bodies = Matter.Composite.allBodies(world);
for (var i = 0; i < bodies.length; i += 1) {
var bodyA = bodies[i],
attractors = bodyA.plugin.attractors;
if (attractors && attractors.length > 0) {
for (var j = i + 1; j < bodies.length; j += 1) {
var bodyB = bodies[j];
for (var k = 0; k < attractors.length; k += 1) {
var attractor = attractors[k],
forceVector = attractor;
if (Matter.Common.isFunction(attractor)) {
forceVector = attractor(bodyA, bodyB);
}
if (forceVector) {
Matter.Body.applyForce(bodyB, bodyB.position, forceVector);
}
}
}
}
}
}
},
/**
* Defines some useful common attractor functions that can be used
* by pushing them to your body's `body.plugin.attractors` array.
* @namespace MatterAttractors.Attractors
* @property {number} gravityConstant The gravitational constant used by the gravity attractor.
*/
Attractors: {
gravityConstant: 0.001,
/**
* An attractor function that applies Newton's law of gravitation.
* Use this by pushing `MatterAttractors.Attractors.gravity` to your body's `body.plugin.attractors` array.
* The gravitational constant defaults to `0.001` which you can change
* at `MatterAttractors.Attractors.gravityConstant`.
* @function MatterAttractors.Attractors.gravity
* @param {Matter.Body} bodyA The first body.
* @param {Matter.Body} bodyB The second body.
* @returns {void} No return value.
*/
gravity: function(bodyA, bodyB) {
// use Newton's law of gravitation
var bToA = Matter.Vector.sub(bodyB.position, bodyA.position),
distanceSq = Matter.Vector.magnitudeSquared(bToA) || 0.0001,
normal = Matter.Vector.normalise(bToA),
magnitude = -MatterAttractors.Attractors.gravityConstant * (bodyA.mass * bodyB.mass / distanceSq),
force = Matter.Vector.mult(normal, magnitude);
// to apply forces to both bodies
Matter.Body.applyForce(bodyA, bodyA.position, Matter.Vector.neg(force));
Matter.Body.applyForce(bodyB, bodyB.position, force);
}
}
};
module.exports = MatterAttractors;
/**
* @namespace Matter.Body
* @see http://brm.io/matter-js/docs/classes/Body.html
*/
/**
* This plugin adds a new property `body.plugin.attractors` to instances of `Matter.Body`.
* This is an array of callback functions that will be called automatically
* for every pair of bodies, on every engine update.
* @property {Function[]} body.plugin.attractors
* @memberof Matter.Body
*/
/**
* An attractor function calculates the force to be applied
* to `bodyB`, it should either:
* - return the force vector to be applied to `bodyB`
* - or apply the force to the body(s) itself
* @callback AttractorFunction
* @param {Matter.Body} bodyA
* @param {Matter.Body} bodyB
* @returns {Vector|undefined} a force vector (optional)
*/

View file

@ -0,0 +1,177 @@
var Matter = require('../../CustomMain');
/**
* A coordinate wrapping plugin for matter.js.
* See the readme for usage and examples.
* @module MatterWrap
*/
var MatterWrap = {
// plugin meta
name: 'matter-wrap', // PLUGIN_NAME
version: '0.1.4', // PLUGIN_VERSION
for: 'matter-js@^0.13.1',
silent: true, // no console log please
// installs the plugin where `base` is `Matter`
// you should not need to call this directly.
install: function(base) {
base.after('Engine.update', function() {
MatterWrap.Engine.update(this);
});
},
Engine: {
/**
* Updates the engine by wrapping bodies and composites inside `engine.world`.
* This is called automatically by the plugin.
* @function MatterWrap.Engine.update
* @param {Matter.Engine} engine The engine to update.
* @returns {void} No return value.
*/
update: function(engine) {
var world = engine.world,
bodies = Matter.Composite.allBodies(world),
composites = Matter.Composite.allComposites(world);
for (var i = 0; i < bodies.length; i += 1) {
var body = bodies[i];
if (body.plugin.wrap) {
MatterWrap.Body.wrap(body, body.plugin.wrap);
}
}
for (i = 0; i < composites.length; i += 1) {
var composite = composites[i];
if (composite.plugin.wrap) {
MatterWrap.Composite.wrap(composite, composite.plugin.wrap);
}
}
}
},
Bounds: {
/**
* Returns a translation vector that wraps the `objectBounds` inside the `bounds`.
* @function MatterWrap.Bounds.wrap
* @param {Matter.Bounds} objectBounds The bounds of the object to wrap inside the bounds.
* @param {Matter.Bounds} bounds The bounds to wrap the body inside.
* @returns {?Matter.Vector} A translation vector (only if wrapping is required).
*/
wrap: function(objectBounds, bounds) {
var x = null,
y = null;
if (typeof bounds.min.x !== 'undefined' && typeof bounds.max.x !== 'undefined') {
if (objectBounds.min.x > bounds.max.x) {
x = bounds.min.x - objectBounds.max.x;
} else if (objectBounds.max.x < bounds.min.x) {
x = bounds.max.x - objectBounds.min.x;
}
}
if (typeof bounds.min.y !== 'undefined' && typeof bounds.max.y !== 'undefined') {
if (objectBounds.min.y > bounds.max.y) {
y = bounds.min.y - objectBounds.max.y;
} else if (objectBounds.max.y < bounds.min.y) {
y = bounds.max.y - objectBounds.min.y;
}
}
if (x !== null || y !== null) {
return {
x: x || 0,
y: y || 0
};
}
}
},
Body: {
/**
* Wraps the `body` position such that it always stays within the given bounds.
* Upon crossing a boundary the body will appear on the opposite side of the bounds,
* while maintaining its velocity.
* This is called automatically by the plugin.
* @function MatterWrap.Body.wrap
* @param {Matter.Body} body The body to wrap.
* @param {Matter.Bounds} bounds The bounds to wrap the body inside.
* @returns {?Matter.Vector} The translation vector that was applied (only if wrapping was required).
*/
wrap: function(body, bounds) {
var translation = MatterWrap.Bounds.wrap(body.bounds, bounds);
if (translation) {
Matter.Body.translate(body, translation);
}
return translation;
}
},
Composite: {
/**
* Returns the union of the bounds of all of the composite's bodies
* (not accounting for constraints).
* @function MatterWrap.Composite.bounds
* @param {Matter.Composite} composite The composite.
* @returns {Matter.Bounds} The composite bounds.
*/
bounds: function(composite) {
var bodies = Matter.Composite.allBodies(composite),
vertices = [];
for (var i = 0; i < bodies.length; i += 1) {
var body = bodies[i];
vertices.push(body.bounds.min, body.bounds.max);
}
return Matter.Bounds.create(vertices);
},
/**
* Wraps the `composite` position such that it always stays within the given bounds.
* Upon crossing a boundary the composite will appear on the opposite side of the bounds,
* while maintaining its velocity.
* This is called automatically by the plugin.
* @function MatterWrap.Composite.wrap
* @param {Matter.Composite} composite The composite to wrap.
* @param {Matter.Bounds} bounds The bounds to wrap the composite inside.
* @returns {?Matter.Vector} The translation vector that was applied (only if wrapping was required).
*/
wrap: function(composite, bounds) {
var translation = MatterWrap.Bounds.wrap(
MatterWrap.Composite.bounds(composite),
bounds
);
if (translation) {
Matter.Composite.translate(composite, translation);
}
return translation;
}
}
};
module.exports = MatterWrap;
/**
* @namespace Matter.Body
* @see http://brm.io/matter-js/docs/classes/Body.html
*/
/**
* This plugin adds a new property `body.plugin.wrap` to instances of `Matter.Body`.
* This is a `Matter.Bounds` instance that specifies the wrapping region.
* @property {Matter.Bounds} body.plugin.wrap
* @memberof Matter.Body
*/
/**
* This plugin adds a new property `composite.plugin.wrap` to instances of `Matter.Composite`.
* This is a `Matter.Bounds` instance that specifies the wrapping region.
* @property {Matter.Bounds} composite.plugin.wrap
* @memberof Matter.Composite
*/