Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # Choro - Tileset
- # Copyright (c) 2012 Nico Hämäläinen <nico@bender.fi>
- # MIT Licensed
- #
- #
- # Events:
- # - tilesetImageLoaded
- # This event is emitted when the initial tileset graphic is loaded
- # and saved into the tileset instance.
- #
- # Load needed modules
- EventEmitter = require('events').EventEmitter
- Canvas = require 'canvas'
- Util = require '../util'
- Rectangle = Util.math.Rectangle
- # Create a new Tileset with given attributes
- Tileset = (@image, @tilesWide, @tilesHigh, @tileWidth, @tileHeight) ->
- # Make our tileset support events
- EventEmitter.call(this)
- # If image param isn't an image
- if not (@image instanceof Canvas.Image)
- throw new Tileset.Error(100)
- # If we're given silly sizes
- if @tilesWide <= 0 or @tilesHigh <= 0
- throw new Tileset.Error(101)
- if @tileWidth <= 0 or @tileHeight <= 0
- throw new Tileset.Error(102)
- # If our image size doesn't match tile dimension and count
- realWidth = @tilesWide * @tileWidth
- realHeight = @tilesHigh * @tileHeight
- if @image.width < realWidth
- throw new Tileset.Error(103)
- # Rectangle -data of all the tiles
- @tileRectangles = []
- # Total count of tiles
- tileCount = @tilesWide * @tilesHigh
- # Create tile rectangles for the whole tileset
- tileIndex = 0
- # Loop through the rows of the tileset
- y = 0
- while y < @tilesHigh
- # Loop through the columns of the current row
- x = 0
- while x < @tilesWide
- # Create a rectangle object for this tile position
- @tileRectangles[tileIndex] = new Rectangle(
- x * @tileWidth,
- y * @tileHeight,
- @tileWidth,
- @tileHeight
- )
- tileIndex++
- x++
- y++
- this
- # Set up event emitter
- Tileset.prototype = EventEmitter.prototype
- # Load the tileset image from a URL and save it into the instance
- # emit an event to inform listeners of the image being succesfully
- # loaded into the Tileset.
- Tileset.prototype.loadImageFromURL = (imageURL) ->
- # Create the image object
- image = new Canvas.Image
- image.onload = () =>
- @image = image
- # Inform our listeners of this happening
- @emit('tilesetImageLoaded', image)
- image.src = imageURL
- # Implement Tileset.Error
- Tileset.Error = Util.implementErrorClass('TilesetError', {
- 100: "Tileset image is not a valid Image or Canvas.Image object",
- 101: "Tileset width and height must be more than zero",
- 102: "Tileset tile sizes must be more than zero",
- 103: "Space required by tiles is larger than given image"
- })
- # Exports
- module.exports = Tileset
Add Comment
Please, Sign In to add comment