Removed stupid merge code and changed field types back to Int.

Strict

Import monkey.map
Import collections
Import framework
Import xml

' TileMapPropertyContainer
' Classes that extend this will automatically instantiate a property container and expose it.
Class TileMapPropertyContainer
Private
	Field properties:TileMapProperties = New TileMapProperties

Public
	Method Properties:TileMapProperties() Property
		Return properties
	End
End

' TileMapPostLoad
' Classes that implement this interface will have PostLoad automatically called once the object has been created.
Interface TileMapPostLoad
	Method PostLoad:Void()
End

' TileMapReader
' This can be extended to handle any map file format.
Class TileMapReader Abstract
	Field tileMap:TileMap

	Method LoadMap:TileMap(filename:String) Abstract

	' override this to create a custom tilemap class
	Method CreateMap:TileMap()
		Return New TileMap
	End
End

' TiledTileMapReader
' Extends TileMapReader to add support for the Tiled map editor.
Class TiledTileMapReader Extends TileMapReader
	Field doc:XMLDocument

	' Overrides TileMapReader
	Method LoadMap:TileMap(filename:String)
		' open file and get root node
		Local parser:XMLParser = New XMLParser
		doc = parser.ParseString(LoadString(filename)) ' TODO: at the moment it assumes filename is actually the loaded string
		Return ReadMap(doc.Root)
	End

	Method ReadMap:TileMap(node:XMLElement)
		tileMap = CreateMap()
		ReadProperties(node, tileMap)

		' extract map properties
		If tileMap.properties.Has(PROP_MAP_WRAP_X) Then tileMap.wrapX = tileMap.properties.Get(PROP_MAP_WRAP_X).GetBool()
		If tileMap.properties.Has(PROP_MAP_WRAP_Y) Then tileMap.wrapY = tileMap.properties.Get(PROP_MAP_WRAP_Y).GetBool()

		' read root node's attributes
		If node.HasAttribute(ATTR_MAP_VERSION) Then tileMap.version = node.GetAttribute(ATTR_MAP_VERSION)
		If node.HasAttribute(ATTR_MAP_ORIENTATION) Then tileMap.orientation = node.GetAttribute(ATTR_MAP_ORIENTATION)
		If node.HasAttribute(ATTR_MAP_WIDTH) Then tileMap.width = Int(node.GetAttribute(ATTR_MAP_WIDTH))
		If node.HasAttribute(ATTR_MAP_HEIGHT) Then tileMap.height = Int(node.GetAttribute(ATTR_MAP_HEIGHT))
		If node.HasAttribute(ATTR_MAP_TILEWIDTH) Then tileMap.tileWidth = Int(node.GetAttribute(ATTR_MAP_TILEWIDTH))
		If node.HasAttribute(ATTR_MAP_TILEHEIGHT) Then tileMap.tileHeight = Int(node.GetAttribute(ATTR_MAP_TILEHEIGHT))

		tileMap.maxTileWidth = tileMap.tileWidth
		tileMap.maxTileHeight = tileMap.tileHeight

		' parse children
		If Not node.Children.IsEmpty() Then
			For Local mapchild:XMLElement = EachIn node.Children
				' tileset
				If mapchild.Name = NODE_TILESET Then
					Local ts:TileMapTileset = ReadTileset(mapchild)
					tileMap.tilesets.Set(ts.name, ts)

				' tile layer
				ElseIf mapchild.Name = NODE_LAYER Then
					Local layer:TileMapLayer = ReadTileLayer(mapchild)
					tileMap.layers.Add(layer)

				' object layer
				ElseIf mapchild.Name = NODE_OBJECTGROUP Then
					Local layer:TileMapLayer = ReadObjectLayer(mapchild)
					tileMap.layers.Add(layer)
				EndIf
			Next
		EndIf

		DoPostLoad(tileMap)

		Return tileMap
	End

	Method DoPostLoad:Void(obj:Object)
		If TileMapPostLoad(obj) <> Null Then TileMapPostLoad(obj).PostLoad()
	End

	Method ReadProperties:Void(node:XMLElement, obj:Object)
		Local cont:TileMapPropertyContainer = TileMapPropertyContainer(obj)
		If cont <> Null Then
			For Local propNode:XMLElement = EachIn node.Children
				If propNode.Name = NODE_PROPERTIES Then
					For Local child:XMLElement = EachIn propNode.Children
						If child.Name = NODE_PROPERTY Then
							Local prop:TileMapProperty = ReadProperty(child)
							cont.properties.props.Set(prop.name, prop)
						EndIf
					Next
					Return
				End
			Next
		End
	End

	Method ReadProperty:TileMapProperty(node:XMLElement)
		Return New TileMapProperty(node.GetAttribute(ATTR_PROPERTY_NAME, "default"), node.GetAttribute(ATTR_PROPERTY_VALUE, ""))
	End

	Method ReadTileset:TileMapTileset(node:XMLElement, target:TileMapTileset=Null)
		Local rv:TileMapTileset = target
		ReadProperties(node, rv)
		If rv = Null Then rv = tileMap.CreateTileset()
		If node.HasAttribute(ATTR_TILESET_FIRSTGID) Then rv.firstGid = Int(node.GetAttribute(ATTR_TILESET_FIRSTGID))

		If node.HasAttribute(ATTR_TILESET_SOURCE) Then
			rv.source = node.GetAttribute(ATTR_TILESET_SOURCE)
			Local parser:XMLParser = New XMLParser
			Local tilesetdoc:XMLDocument = parser.ParseFile(rv.source)
			Return ReadTileset(tilesetdoc.Root, rv)
		Else
			If node.HasAttribute(ATTR_TILESET_NAME) Then rv.name = node.GetAttribute(ATTR_TILESET_NAME)
			If node.HasAttribute(ATTR_TILESET_TILEWIDTH) Then rv.tileWidth = Int(node.GetAttribute(ATTR_TILESET_TILEWIDTH))
			If node.HasAttribute(ATTR_TILESET_TILEHEIGHT) Then rv.tileHeight = Int(node.GetAttribute(ATTR_TILESET_TILEHEIGHT))
			If node.HasAttribute(ATTR_TILESET_SPACING) Then rv.spacing = Int(node.GetAttribute(ATTR_TILESET_SPACING))
			If node.HasAttribute(ATTR_TILESET_MARGIN) Then rv.margin = Int(node.GetAttribute(ATTR_TILESET_MARGIN))

			If Not node.Children.IsEmpty() Then
				For Local child:XMLElement = EachIn node.Children
					If child.Name = NODE_IMAGE Then
						rv.imageNode = ReadImage(child)
					ElseIf child.Name = NODE_TILE Then
						rv.tileNodes.Add(ReadTile(child))
					End
				Next
			End
		End
		DoPostLoad(rv)
		Return rv
	End

	Method ReadLayerAttributes:Void(node:XMLElement, layer:TileMapLayer)
		If node.HasAttribute(ATTR_LAYER_NAME) Then layer.name = node.GetAttribute(ATTR_LAYER_NAME)
		If node.HasAttribute(ATTR_LAYER_WIDTH) Then layer.width = Int(node.GetAttribute(ATTR_LAYER_WIDTH))
		If node.HasAttribute(ATTR_LAYER_HEIGHT) Then layer.height = Int(node.GetAttribute(ATTR_LAYER_HEIGHT))
		layer.visible = Not node.HasAttribute(ATTR_LAYER_VISIBLE) Or Int(node.GetAttribute(ATTR_LAYER_VISIBLE)) <> 0
		If node.HasAttribute(ATTR_LAYER_OPACITY) Then layer.opacity = Float(node.GetAttribute(ATTR_LAYER_OPACITY))
	End

	Method ReadTileLayer:TileMapTileLayer(node:XMLElement)
		Local rv:TileMapTileLayer = tileMap.CreateTileLayer()
		ReadProperties(node, rv)
		ReadLayerAttributes(node, rv)

		If rv.properties.Has(PROP_LAYER_PARALLAX_OFFSET_X) Then rv.parallaxOffsetX = rv.properties.Get(PROP_LAYER_PARALLAX_OFFSET_X).GetFloat()
		If rv.properties.Has(PROP_LAYER_PARALLAX_OFFSET_Y) Then rv.parallaxOffsetY = rv.properties.Get(PROP_LAYER_PARALLAX_OFFSET_Y).GetFloat()
		If rv.properties.Has(PROP_LAYER_PARALLAX_SCALE_X) Then rv.parallaxScaleX = rv.properties.Get(PROP_LAYER_PARALLAX_SCALE_X).GetFloat()
		If rv.properties.Has(PROP_LAYER_PARALLAX_SCALE_Y) Then rv.parallaxScaleY = rv.properties.Get(PROP_LAYER_PARALLAX_SCALE_Y).GetFloat()

		For Local child:XMLElement = EachIn node.Children
			If child.Name = NODE_DATA Then
				rv.mapData = ReadTileData(child, rv)
			End
		Next

		DoPostLoad(rv)
		Return rv
	End

	Method ReadObjectLayer:TileMapObjectLayer(node:XMLElement)
		Local rv:TileMapObjectLayer = tileMap.CreateObjectLayer()
		ReadProperties(node, rv)
		ReadLayerAttributes(node, rv)

		If node.HasAttribute(ATTR_OBJECTGROUP_COLOR) Then rv.color = ColorToInt(node.GetAttribute(ATTR_OBJECTGROUP_COLOR))

		For Local child:XMLElement = EachIn node.Children
			If child.Name = NODE_OBJECT Then
				rv.objects.Add(ReadObject(child, rv))
			End
		Next

		DoPostLoad(rv)
		Return rv
	End

	Method ReadImage:TileMapImage(node:XMLElement)
		Local rv:TileMapImage = tileMap.CreateImage()
		ReadProperties(node, rv)

		If node.HasAttribute(ATTR_IMAGE_SOURCE) Then rv.source = StripDir(node.GetAttribute(ATTR_IMAGE_SOURCE))
		If node.HasAttribute(ATTR_IMAGE_WIDTH) Then rv.width = Int(node.GetAttribute(ATTR_IMAGE_WIDTH))
		If node.HasAttribute(ATTR_IMAGE_HEIGHT) Then rv.height = Int(node.GetAttribute(ATTR_IMAGE_HEIGHT))
		If node.HasAttribute(ATTR_IMAGE_TRANS) Then rv.trans = node.GetAttribute(ATTR_IMAGE_TRANS)
		If rv.trans.Length > 0 Then
			rv.transR = HexToDec(rv.trans[0..2])
			rv.transG = HexToDec(rv.trans[2..4])
			rv.transB = HexToDec(rv.trans[4..6])
		EndIf

		DoPostLoad(rv)
		Return rv
	End

	Method ReadTile:TileMapTile(node:XMLElement)
		Local id:Int = Int(node.GetAttribute(ATTR_TILE_ID, "0"))
		Local rv:TileMapTile = tileMap.CreateTile(id)
		ReadProperties(node, rv)
		DoPostLoad(rv)
		Return rv
	End

	Method ReadObject:TileMapObject(node:XMLElement, layer:TileMapObjectLayer)
		Local rv:TileMapObject = tileMap.CreateObject()
		ReadProperties(node, rv)
		If node.HasAttribute(ATTR_OBJECT_NAME) Then rv.name = node.GetAttribute(ATTR_OBJECT_NAME)
		If node.HasAttribute(ATTR_OBJECT_TYPE) Then rv.objectType = node.GetAttribute(ATTR_OBJECT_TYPE)
		If node.HasAttribute(ATTR_OBJECT_X) Then rv.x = Int(node.GetAttribute(ATTR_OBJECT_X))
		If node.HasAttribute(ATTR_OBJECT_Y) Then rv.y = Int(node.GetAttribute(ATTR_OBJECT_Y))
		If node.HasAttribute(ATTR_OBJECT_WIDTH) Then rv.width = Int(node.GetAttribute(ATTR_OBJECT_WIDTH))
		If node.HasAttribute(ATTR_OBJECT_HEIGHT) Then rv.height = Int(node.GetAttribute(ATTR_OBJECT_HEIGHT))
		DoPostLoad(rv)
		Return rv
	End

	Method ReadTileData:TileMapData(node:XMLElement, layer:TileMapTileLayer)
		Local rv:TileMapData = tileMap.CreateData(layer.width, layer.height)

		' default to raw xml (ugly)
		Local encoding$ = DATA_ENCODING_RAW
		If node.HasAttribute(ATTR_DATA_ENCODING) Then encoding = node.GetAttribute(ATTR_DATA_ENCODING)

		If encoding = DATA_ENCODING_RAW Then
			' TODO: raw xml
		ElseIf encoding = DATA_ENCODING_CSV Then
			' TODO: csv encoding
		ElseIf encoding = DATA_ENCODING_BASE64 Then
			Local bytes:Int[] = DecodeBase64Bytes(node.Value)
			If node.HasAttribute(ATTR_DATA_COMPRESSION) Then
				' TODO: compression
			End
			For Local i% = 0 Until bytes.Length Step 4
				' little endian
				Local gid% = bytes[i]
				gid += bytes[i + 1] Shl 8
				gid += bytes[i + 2] Shl 16
				gid += bytes[i + 3] Shl 24
				rv.tiles[i / 4] = gid
				rv.cells[i / 4] = tileMap.CreateCell(gid, (i / 4) Mod rv.width, (i / 4) / rv.width)
			Next
		End
		Return rv
	End
End

' TileMapProperties
' Container for properties.
Class TileMapProperties
	Field props:StringMap<TileMapProperty> = New StringMap<TileMapProperty>

	Method Has:Bool(name:String)
		Return props.Contains(name)
	End

	Method Get:TileMapProperty(name:String)
		Return props.Get(name)
	End

	Method Set:Void(name:String, prop:TileMapProperty)
		props.Set(name, prop)
	End
End

' TileMap
' The main Map class.
Class TileMap Extends TileMapPropertyContainer Implements TileMapPostLoad

	' attributes
	Field version:String = "1.0"
	Field orientation:String = MAP_ORIENTATION_ORTHOGONAL
	Field width:Int
	Field height:Int
	Field tileWidth:Int = 32
	Field tileHeight:Int = 32

	' children
	Field tilesets:StringMap<TileMapTileset> = New StringMap<TileMapTileset>
	Field layers:ArrayList<TileMapLayer> = New ArrayList<TileMapLayer>

	' post-load
	Field layerNames:StringMap<TileMapLayer> = New StringMap<TileMapLayer>
	Field tiles:TileMapTile[]
	Field maxTileWidth:Int
	Field maxTileHeight:Int
	Field wrapX:Bool = False
	Field wrapY:Bool = False

	' override this to configure a layer (called on every render)
	Method ConfigureLayer:Void(tileLayer:TileMapLayer)
	End

	' override this to draw a tile
	Method DrawTile:Void(tileLayer:TileMapTileLayer, mapTile:TileMapTile, x:Int, y:Int)
	End

	' override this to create a custom tile class
	Method CreateTile:TileMapTile(id:Int)
		Return New TileMapTile(id)
	End

	' override this to create a custom tileset class
	Method CreateTileset:TileMapTileset()
		Return New TileMapTileset
	End

	' override this to create a custom tile layer class
	Method CreateTileLayer:TileMapTileLayer()
		Return New TileMapTileLayer
	End

	' override this to create a custom object layer class
	Method CreateObjectLayer:TileMapObjectLayer()
		Return New TileMapObjectLayer
	End

	' override this to create a custom image class
	Method CreateImage:TileMapImage()
		Return New TileMapImage
	End

	' override this to create a custom object class
	Method CreateObject:TileMapObject()
		Return New TileMapObject
	End

	' override this to create a custom cell class
	Method CreateCell:TileMapCell(gid:Int, x:Int, y:Int)
		Return New TileMapCell(gid, x, y)
	End

	' override this to create a custom data class
	Method CreateData:TileMapData(width:Int, height:Int)
		Return New TileMapData(width, height)
	End

	' override this to perform additional post-loading functionality (remember to call Super.PostLoad() first)
	Method PostLoad:Void()
		Local totaltiles% = 0, ts:TileMapTileset
		Local alltiles:ArrayList<TileMapTile> = New ArrayList<TileMapTile>
		For Local ts:TileMapTileset = EachIn tilesets.Values()
			' load the image
			ts.image = game.images.LoadTileset(ts.imageNode.source, ts.tileWidth, ts.tileHeight, ts.margin, ts.spacing)
			' get the cell count
			ts.tileCount = ts.image.tileCount

			' update max tile size
			If maxTileWidth < ts.tileWidth Then maxTileWidth = ts.tileWidth
			If maxTileHeight < ts.tileHeight Then maxTileHeight = ts.tileHeight

			' build tile list
			ts.tiles = New TileMapTile[ts.tileCount]
			For Local t:TileMapTile = EachIn ts.tileNodes
				ts.tiles[t.id] = t
			Next
			For Local i% = 0 Until ts.tiles.Length
				If ts.tiles[i] = Null Then
					ts.tiles[i] = CreateTile(i)
				End
				ts.tiles[i].gid = ts.firstGid + i
				ts.tiles[i].image = ts.image
				ts.tiles[i].width = ts.tileWidth
				ts.tiles[i].height = ts.tileHeight
				alltiles.Add(ts.tiles[i])
			Next
			' update total tiles
			totaltiles += ts.tileCount
		Next

		' make our cache
		tiles = New TileMapTile[totaltiles]
		For Local t:TileMapTile = EachIn alltiles
			tiles[t.gid - 1] = t
		Next

		' calculate the max tile size per layer
		For Local l:TileMapLayer = EachIn layers
			If TileMapTileLayer(l) <> Null Then
				Local tl:TileMapTileLayer = TileMapTileLayer(l)
				For Local i% = 0 Until tl.mapData.tiles.Length
					If tl.mapData.tiles[i] > 0 Then
						If tl.maxTileWidth < tiles[tl.mapData.tiles[i] - 1].width Then tl.maxTileWidth = tiles[tl.mapData.tiles[i] - 1].width
						If tl.maxTileHeight < tiles[tl.mapData.tiles[i] - 1].height Then tl.maxTileHeight = tiles[tl.mapData.tiles[i] - 1].height
					End
				Next
			End
		Next
	End

	#Rem
	Method WorldToMap:TPoint(worldPoint:TPoint)
		If worldPoint.X < 0 Or worldPoint.Y < 0 Or worldPoint.X > Width * TileWidth Or worldPoint.Y > Height * TileHeight Then
			' out of range!
			Return Null
		EndIf
		Local rv:TPoint = New TPoint.CreatePoint(worldPoint.X / TileWidth, worldPoint.Y / TileHeight)
		If worldPoint.X = Width * TileWidth Then rv.X:-1
		If worldPoint.Y = Height * TileHeight Then rv.Y:-1
		Return rv
	End
	#End

	Method GetAllObjects:ArrayList<TileMapObject>()
		#Rem
		Local layer:TTiledLayer
		Local obj:TTiledObject
		Local rv:TList = New TList
		For layer = EachIn Layers
			If TTiledObjectLayer(layer) <> Null Then
				For obj = EachIn TTiledObjectLayer(layer).Objects
					rv.AddLast(obj)
				Next
			EndIf
		Next
		Return rv
		#End
	End

	Method FindObjectByName:TileMapObject(name:String)
		#Rem
		Local layer:TTiledLayer, obj:TTiledObject
		For layer = EachIn Layers
			If TTiledObjectLayer(layer) <> Null Then
				For obj = EachIn TTiledObjectLayer(layer).Objects
					If obj.Name = name Then Return obj
				Next
			EndIf
		Next
		#End
		Return Null
	End

	' bx,by,bw,bh = render bounds (screen)
	' sx,sy = scale x/y (float, defaults to 1) i'll do this later
	' wx,wy = wrap x/y (boolean, defaults to false)
	Method RenderMap:Void(bx%, by%, bw%, bh%, sx# = 1, sy# = 1)
		Local x%, y%, rx%, ry%, mx%, my%, mx2%, my2%, modx%, mody%
		For Local layer:TileMapLayer = EachIn layers
			If layer.visible And TileMapTileLayer(layer) <> Null Then
				Local tl:TileMapTileLayer = TileMapTileLayer(layer)
				Local mapTile:TileMapTile, gid%
				ConfigureLayer(layer)
				' ortho
				If orientation = MAP_ORIENTATION_ORTHOGONAL Then
					modx = (bx * tl.parallaxScaleX) mod tileWidth
					mody = (by * tl.parallaxScaleY) mod tileHeight
					y = by
					my = Int(Floor(Float(by * tl.parallaxScaleY) / Float(tileHeight)))
					While y < by + bh + tl.maxTileHeight
						x = bx - tl.maxTileWidth
						mx = Int(Floor(Float(bx * tl.parallaxScaleX) / Float(tileWidth)))
						While x < bx + bw + tl.maxTileWidth
							If (wrapX Or (mx >= 0 And mx < width)) And (wrapY Or (my >= 0 And my < height)) Then
								mx2 = mx
								my2 = my
								While mx2 < 0
									mx2 += width
								End
								While mx2 >= width
									mx2 -= width
								End
								While my2 < 0
									my2 += height
								End
								While my2 >= height
									my2 -= height
								End
								gid = tl.mapData.GetCell(mx2, my2).gid
								If gid > 0 Then
									mapTile = tiles[gid - 1]

									If modx < 0 Then modx += tileWidth
									If mody < 0 Then mody += tileHeight
									rx = x - modx - bx
									ry = y - mody - by
									DrawTile(tl, mapTile, rx, ry)
								End
							End
							x += tileWidth
							mx += 1
						End
						y += tileHeight
						my += 1
					End

				' iso
				ElseIf orientation = MAP_ORIENTATION_ISOMETRIC Then
					' TODO: wrapping
					For y = 0 Until tl.width + tl.height
						ry = y
						rx = 0
						While ry >= tl.height
							ry -= 1
							rx += 1
						Wend
						While ry >= 0 And rx < tl.width
							gid = tl.mapData.GetCell(rx, ry).gid
							If gid > 0 Then
								mapTile = tiles[gid - 1]
								DrawTile(tl, mapTile, (rx - ry - 1) * tileWidth / 2, (rx + ry + 2) * tileHeight / 2 - mapTile.height)
							EndIf
							ry -= 1
							rx += 1
						End
					Next
				End
			End
		Next
	End

	Method GetBounds:TileMapRect()
		Local rv:TileMapRect = New TileMapRect
		If orientation = MAP_ORIENTATION_ORTHOGONAL Then
			rv.x = 0
			rv.y = tileHeight - maxTileHeight
			rv.w = (width - 1) * tileWidth + maxTileWidth
			rv.h = (height - 1) * tileHeight + maxTileHeight
		ElseIf orientation = MAP_ORIENTATION_ISOMETRIC Then
			rv.x = -height * tileWidth / 2
			rv.y = tileHeight - maxTileHeight
			rv.w = (width - 2) * tileWidth / 2 + maxTileWidth - rv.X
			rv.h = (width + height) * tileHeight / 2 - rv.Y
		EndIf
		Return rv
	End

	Method UpdateAnimation:Void(timePassed:Int)
		Local layer:TileMapLayer, tl:TileMapTileLayer, cell:TileMapCell, t:TileMapTile
		' loop on each layer
		For layer = EachIn layers
			' cast
			tl = TileMapTileLayer(layer)

			' if the layer is a tile layer
			If tl <> Null Then
				' loop on each cell
				For cell = EachIn tl.mapData.cells
					' if the cell exists and has a value
					If cell <> Null And cell.gid > 0 Then
						' get the tile
						t = tiles[cell.gid-1]

						' if the direction is 0 (paused), do nothing
						If t <> Null And cell.direction <> 0 Then
							' add our time to the time passed for the cell
							cell.timePassed += timePassed

							' if this tile has animation information
							If t.animated Then
								' get the new direction if we have one
								If t.hasAnimDirection Then cell.direction = t.animDirection

								' while it's not paused and we're not up to the current frame
								While cell.direction <> 0 And cell.timePassed >= t.animDelay
									' move to the next frame
									cell.timePassed -= t.animDelay
									cell.gid += cell.direction * t.animNext

									' get the tile for the new frame
									t = tiles[cell.gid-1]

									' if there's animation information, get it
									If t <> Null And t.animated Then
										' if the tile has a direction assigned to it, use it (we might be turning around)
										If t.hasAnimDirection Then cell.direction = t.animDirection

									' otherwise, pause and die
									Else
										cell.direction = 0
										Exit
									End
								End

							' no animation information, so pause
							Else
								cell.direction = 0
							End
						End
					End
				Next
			End
		Next
	End
End

Class TileMapTileset Implements TileMapPostLoad
	' attributes
	Field firstGid:Int
	Field name:String
	Field tileWidth:Int
	Field tileHeight:Int
	Field spacing:Int
	Field margin:Int
	Field source:String

	' children
	Field imageNode:TileMapImage
	Field tileNodes:ArrayList<TileMapTile> = New ArrayList<TileMapTile>

	' post load
	Field tiles:TileMapTile[]
	Field image:GameImage
	Field tileCount:Int

	Method PostLoad:Void()
	End
End

Class TileMapImage Implements TileMapPostLoad
	' attributes
	Field source$
	Field width%
	Field height%
	Field trans$ = ""

	' post-load
	Field transR%, transG%, transB%

	Method PostLoad:Void()
	End
End

'<layer> and <objectgroup>
Class TileMapLayer Extends TileMapPropertyContainer Implements TileMapPostLoad Abstract
	' attributes
	Field name$
	Field width%
	Field height%
	Field visible% = True
	Field opacity:Float = 1

	Method PostLoad:Void()
	End
End

Class TileMapData
	Field width%
	Field height%
	Field tiles:Int[]
	Field cells:TileMapCell[]

	Method New(width%, height%)
		Self.width = width
		Self.height = height
		Self.tiles = New Int[width * height]
		Self.cells = New TileMapCell[width * height]
	End Method

	Method Get%(x%, y%)
		Return tiles[x + y * width]
	End

	Method Set:Void(x%, y%, gid%)
		tiles[x + y * width] = gid
	End

	Method GetCell:TileMapCell(x%, y%)
		Return cells[x + y * width]
	End

	Method SetCell:Void(x%, y%, cell:TileMapCell)
		cells[x + y * width] = cell
	End
End

Class TileMapTileLayer Extends TileMapLayer
	Field mapData:TileMapData
	Field maxTileWidth%
	Field maxTileHeight%
	Field parallaxOffsetX# = 0
	Field parallaxOffsetY# = 0
	Field parallaxScaleX# = 1
	Field parallaxScaleY# = 1
End

Class TileMapObjectLayer Extends TileMapLayer
	' attributes
	Field color%
	' children
	Field objects:ArrayList<TileMapObject> = New ArrayList<TileMapObject>
End

Class TileMapObject Extends TileMapPropertyContainer
	' attributes
	Field name:String
	Field objectType:String
	Field x:Int
	Field y:Int
	Field width:Int
	Field height:Int
End

Class TileMapProperty
Private
	Field valueType% = 0 ' 0=int, 1=float, 2=bool, 3=string
	Field name$ = ""
	Field rawValue$ = ""

Public
	Method New(name:String="default", value:String="")
		Self.name = name
		Self.rawValue = value
		Self.valueType = 3
	End

	Method Set:Void(value:Int)
		rawValue = value
		valueType = 0
	End

	Method Set:Void(value:Float)
		RawValue = value
		ValueType = 1
	End

	Method Set:Void(value:Bool)
		If value Then
			rawValue = "true"
		Else
			rawValue = "false"
		EndIf
		ValueType = 2
	End

	Method Set:Void(value:String)
		rawValue = value
		valueType = 3
	End

	Method GetInt:Int()
		Return Int(rawValue)
		'Local rv% = 0
		'rv = RawValue.ToInt()
		'Catch ex:Object
		'End
		'Return rv
	End

	Method GetFloat:Float()
		Return Float(rawValue)
		'Local rv:Float = 0
		'Try
		'	rv = RawValue.ToFloat()
		'Catch ex:Object
		'EndTry
		'Return rv
	End

	Method GetBool:Bool()
		Local val:String = rawValue.ToLower()
		If val = "true" Or val = "t" Or val = "y" Then Return True
		Return False
		'If val = "false" Or val = "f" Or val = "n" Then Return False
		'Return GetInt() <> 0
	End

	Method GetString:String()
		Return rawValue
	End
End

Class TileMapTile Extends TileMapPropertyContainer Implements TileMapPostLoad
	Field id%
	Field image:GameImage
	Field width:Int
	Field height:Int
	Field gid:Int

	Field animDelay:Int
	Field animNext:Int
	Field animDirection:Int
	Field hasAnimDirection:Bool
	Field animated:Bool

	Method New(id:Int)
		Self.id = id
	End

	Method PostLoad:Void()
		If properties.Has(PROP_TILE_ANIM_DELAY) Then
			animDelay = game.CalcAnimLength(properties.Get(PROP_TILE_ANIM_DELAY).GetInt())
			animated = True
		End
		If properties.Has(PROP_TILE_ANIM_NEXT) Then animNext = properties.Get(PROP_TILE_ANIM_NEXT).GetInt()
		If properties.Has(PROP_TILE_ANIM_DIRECTION) Then
			animDirection = properties.Get(PROP_TILE_ANIM_DIRECTION).GetInt()
			hasAnimDirection = True
		End
	End
End

Class TileMapCell
	' mandatory fields
	Field gid%
	Field x%
	Field y%

	' animation stuff
	Field originalGid%
	Field timePassed:Int = 0 ' the time that has passed since the last frame change
	Field direction% = 1 ' >0 = forward, <0 = backward, 0 = paused

	Method New(gid%, x%, y%)
		Self.gid = gid
		Self.x = x
		Self.y = y
		originalGid = gid
	End
End

Class TileMapRect
	Field x%, y%, w%, h%
End

Function ColorToInt%(str$)
	' TODO: convert a hex color string #rrggbb to a number
	Return 0
End

Function HexToDec%(hexstr$)
	Local chars$ = "0123456789abcdef"
	Local rv% = 0
	hexstr = hexstr.ToLower()
	For Local i% = 0 To hexstr.Length - 1
		rv = rv Shl 4
		Local idx% = chars.Find(hexstr[i])
		If idx >= 0 Then rv += idx
	Next
	Return rv
End

Const PROP_MAP_WRAP_X$ = "wrap_x"
Const PROP_MAP_WRAP_Y$ = "wrap_y"

Const PROP_LAYER_PARALLAX_OFFSET_X$ = "parallax_offset_x"
Const PROP_LAYER_PARALLAX_OFFSET_Y$ = "parallax_offset_y"
Const PROP_LAYER_PARALLAX_SCALE_X$  = "parallax_scale_x"
Const PROP_LAYER_PARALLAX_SCALE_Y$  = "parallax_scale_y"

Const PROP_TILE_ANIM_DELAY$     = "anim_delay"
Const PROP_TILE_ANIM_NEXT$      = "anim_next"
Const PROP_TILE_ANIM_DIRECTION$ = "anim_direction"

Const DATA_ENCODING_RAW$    = ""
Const DATA_ENCODING_CSV$    = "csv"
Const DATA_ENCODING_BASE64$ = "base64"

Const MAP_ORIENTATION_ORTHOGONAL$   = "orthogonal"
Const MAP_ORIENTATION_ISOMETRIC$    = "isometric"

Const ATTR_MAP_VERSION$         = "version"
Const ATTR_MAP_ORIENTATION$     = "orientation"
Const ATTR_MAP_WIDTH$           = "width"
Const ATTR_MAP_HEIGHT$          = "height"
Const ATTR_MAP_TILEWIDTH$       = "tilewidth"
Const ATTR_MAP_TILEHEIGHT$      = "tileheight"
Const ATTR_TILESET_FIRSTGID$    = "firstgid"
Const ATTR_TILESET_NAME$        = "name"
Const ATTR_TILESET_TILEWIDTH$   = "tilewidth"
Const ATTR_TILESET_TILEHEIGHT$  = "tileheight"
Const ATTR_TILESET_SPACING$     = "spacing"
Const ATTR_TILESET_MARGIN$      = "margin"
Const ATTR_TILESET_SOURCE$      = "source"
Const ATTR_IMAGE_SOURCE$        = "source"
Const ATTR_IMAGE_WIDTH$         = "width"
Const ATTR_IMAGE_HEIGHT$        = "height"
Const ATTR_IMAGE_TRANS$         = "trans"
Const ATTR_TILE_ID$             = "id"
Const ATTR_LAYER_NAME$          = "name"
Const ATTR_LAYER_WIDTH$         = "width"
Const ATTR_LAYER_HEIGHT$        = "height"
Const ATTR_LAYER_VISIBLE$       = "visible"
Const ATTR_LAYER_OPACITY$       = "opacity"
Const ATTR_DATA_ENCODING$       = "encoding"
Const ATTR_DATA_COMPRESSION$    = "compression"
Const ATTR_PROPERTY_NAME$       = "name"
Const ATTR_PROPERTY_VALUE$      = "value"
Const ATTR_OBJECTGROUP_COLOR$   = "color"
Const ATTR_OBJECTGROUP_NAME$    = "name"
Const ATTR_OBJECTGROUP_WIDTH$   = "width"
Const ATTR_OBJECTGROUP_HEIGHT$  = "height"
Const ATTR_OBJECT_NAME$         = "name"
Const ATTR_OBJECT_TYPE$         = "type"
Const ATTR_OBJECT_X$            = "x"
Const ATTR_OBJECT_Y$            = "y"
Const ATTR_OBJECT_WIDTH$        = "width"
Const ATTR_OBJECT_HEIGHT$       = "height"

Const NODE_MAP$                 = "map"
Const NODE_TILESET$             = "tileset"
Const NODE_IMAGE$               = "image"
Const NODE_TILE$                = "tile"
Const NODE_LAYER$               = "layer"
Const NODE_DATA$                = "data"
Const NODE_PROPERTIES$          = "properties"
Const NODE_PROPERTY$            = "property"
Const NODE_OBJECTGROUP$         = "objectgroup"
Const NODE_OBJECT$              = "object"

Strict

Import monkey.map
Import collections
Import framework
Import xml

' TileMapPropertyContainer
' Classes that extend this will automatically instantiate a property container and expose it.
Class TileMapPropertyContainer
Private
	Field properties:TileMapProperties = New TileMapProperties

Public
	Method Properties:TileMapProperties() Property
		Return properties
	End
End

' TileMapPostLoad
' Classes that implement this interface will have PostLoad automatically called once the object has been created.
Interface TileMapPostLoad
	Method PostLoad:Void()
End

' TileMapReader
' This can be extended to handle any map file format.
Class TileMapReader Abstract
	Field tileMap:TileMap

	Method LoadMap:TileMap(filename:String) Abstract

	' override this to create a custom tilemap class
	Method CreateMap:TileMap()
		Return New TileMap
	End
End

' TiledTileMapReader
' Extends TileMapReader to add support for the Tiled map editor.
Class TiledTileMapReader Extends TileMapReader
	Field doc:XMLDocument

	' Overrides TileMapReader
	Method LoadMap:TileMap(filename:String)
		' open file and get root node
		Local parser:XMLParser = New XMLParser
		doc = parser.ParseString(LoadString(filename)) ' TODO: at the moment it assumes filename is actually the loaded string
		Return ReadMap(doc.Root)
	End

	Method ReadMap:TileMap(node:XMLElement)
		tileMap = CreateMap()
		ReadProperties(node, tileMap)

		' extract map properties
		If tileMap.properties.Has(PROP_MAP_WRAP_X) Then tileMap.wrapX = tileMap.properties.Get(PROP_MAP_WRAP_X).GetBool()
		If tileMap.properties.Has(PROP_MAP_WRAP_Y) Then tileMap.wrapY = tileMap.properties.Get(PROP_MAP_WRAP_Y).GetBool()

		' read root node's attributes
		If node.HasAttribute(ATTR_MAP_VERSION) Then tileMap.version = node.GetAttribute(ATTR_MAP_VERSION)
		If node.HasAttribute(ATTR_MAP_ORIENTATION) Then tileMap.orientation = node.GetAttribute(ATTR_MAP_ORIENTATION)
		If node.HasAttribute(ATTR_MAP_WIDTH) Then tileMap.width = Int(node.GetAttribute(ATTR_MAP_WIDTH))
		If node.HasAttribute(ATTR_MAP_HEIGHT) Then tileMap.height = Int(node.GetAttribute(ATTR_MAP_HEIGHT))
		If node.HasAttribute(ATTR_MAP_TILEWIDTH) Then tileMap.tileWidth = Int(node.GetAttribute(ATTR_MAP_TILEWIDTH))
		If node.HasAttribute(ATTR_MAP_TILEHEIGHT) Then tileMap.tileHeight = Int(node.GetAttribute(ATTR_MAP_TILEHEIGHT))

		tileMap.maxTileWidth = tileMap.tileWidth
		tileMap.maxTileHeight = tileMap.tileHeight

		' parse children
		If Not node.Children.IsEmpty() Then
			For Local mapchild:XMLElement = EachIn node.Children
				' tileset
				If mapchild.Name = NODE_TILESET Then
					Local ts:TileMapTileset = ReadTileset(mapchild)
					tileMap.tilesets.Set(ts.name, ts)

				' tile layer
				ElseIf mapchild.Name = NODE_LAYER Then
					Local layer:TileMapLayer = ReadTileLayer(mapchild)
					tileMap.layers.Add(layer)

				' object layer
				ElseIf mapchild.Name = NODE_OBJECTGROUP Then
					Local layer:TileMapLayer = ReadObjectLayer(mapchild)
					tileMap.layers.Add(layer)
				EndIf
			Next
		EndIf

		DoPostLoad(tileMap)

		Return tileMap
	End

	Method DoPostLoad:Void(obj:Object)
		If TileMapPostLoad(obj) <> Null Then TileMapPostLoad(obj).PostLoad()
	End

	Method ReadProperties:Void(node:XMLElement, obj:Object)
		Local cont:TileMapPropertyContainer = TileMapPropertyContainer(obj)
		If cont <> Null Then
			For Local propNode:XMLElement = EachIn node.Children
				If propNode.Name = NODE_PROPERTIES Then
					For Local child:XMLElement = EachIn propNode.Children
						If child.Name = NODE_PROPERTY Then
							Local prop:TileMapProperty = ReadProperty(child)
							cont.properties.props.Set(prop.name, prop)
						EndIf
					Next
					Return
				End
			Next
		End
	End

	Method ReadProperty:TileMapProperty(node:XMLElement)
		Return New TileMapProperty(node.GetAttribute(ATTR_PROPERTY_NAME, "default"), node.GetAttribute(ATTR_PROPERTY_VALUE, ""))
	End

	Method ReadTileset:TileMapTileset(node:XMLElement, target:TileMapTileset=Null)
		Local rv:TileMapTileset = target
		ReadProperties(node, rv)
		If rv = Null Then rv = tileMap.CreateTileset()
		If node.HasAttribute(ATTR_TILESET_FIRSTGID) Then rv.firstGid = Int(node.GetAttribute(ATTR_TILESET_FIRSTGID))

		If node.HasAttribute(ATTR_TILESET_SOURCE) Then
			rv.source = node.GetAttribute(ATTR_TILESET_SOURCE)
			Local parser:XMLParser = New XMLParser
			Local tilesetdoc:XMLDocument = parser.ParseFile(rv.source)
			Return ReadTileset(tilesetdoc.Root, rv)
		Else
			If node.HasAttribute(ATTR_TILESET_NAME) Then rv.name = node.GetAttribute(ATTR_TILESET_NAME)
			If node.HasAttribute(ATTR_TILESET_TILEWIDTH) Then rv.tileWidth = Int(node.GetAttribute(ATTR_TILESET_TILEWIDTH))
			If node.HasAttribute(ATTR_TILESET_TILEHEIGHT) Then rv.tileHeight = Int(node.GetAttribute(ATTR_TILESET_TILEHEIGHT))
			If node.HasAttribute(ATTR_TILESET_SPACING) Then rv.spacing = Int(node.GetAttribute(ATTR_TILESET_SPACING))
			If node.HasAttribute(ATTR_TILESET_MARGIN) Then rv.margin = Int(node.GetAttribute(ATTR_TILESET_MARGIN))

			If Not node.Children.IsEmpty() Then
				For Local child:XMLElement = EachIn node.Children
					If child.Name = NODE_IMAGE Then
						rv.imageNode = ReadImage(child)
					ElseIf child.Name = NODE_TILE Then
						rv.tileNodes.Add(ReadTile(child))
					End
				Next
			End
		End
		DoPostLoad(rv)
		Return rv
	End

	Method ReadLayerAttributes:Void(node:XMLElement, layer:TileMapLayer)
		If node.HasAttribute(ATTR_LAYER_NAME) Then layer.name = node.GetAttribute(ATTR_LAYER_NAME)
		If node.HasAttribute(ATTR_LAYER_WIDTH) Then layer.width = Int(node.GetAttribute(ATTR_LAYER_WIDTH))
		If node.HasAttribute(ATTR_LAYER_HEIGHT) Then layer.height = Int(node.GetAttribute(ATTR_LAYER_HEIGHT))
		layer.visible = Not node.HasAttribute(ATTR_LAYER_VISIBLE) Or Int(node.GetAttribute(ATTR_LAYER_VISIBLE)) <> 0
		If node.HasAttribute(ATTR_LAYER_OPACITY) Then layer.opacity = Float(node.GetAttribute(ATTR_LAYER_OPACITY))
	End

	Method ReadTileLayer:TileMapTileLayer(node:XMLElement)
		Local rv:TileMapTileLayer = tileMap.CreateTileLayer()
		ReadProperties(node, rv)
		ReadLayerAttributes(node, rv)

		If rv.properties.Has(PROP_LAYER_PARALLAX_OFFSET_X) Then rv.parallaxOffsetX = rv.properties.Get(PROP_LAYER_PARALLAX_OFFSET_X).GetFloat()
		If rv.properties.Has(PROP_LAYER_PARALLAX_OFFSET_Y) Then rv.parallaxOffsetY = rv.properties.Get(PROP_LAYER_PARALLAX_OFFSET_Y).GetFloat()
		If rv.properties.Has(PROP_LAYER_PARALLAX_SCALE_X) Then rv.parallaxScaleX = rv.properties.Get(PROP_LAYER_PARALLAX_SCALE_X).GetFloat()
		If rv.properties.Has(PROP_LAYER_PARALLAX_SCALE_Y) Then rv.parallaxScaleY = rv.properties.Get(PROP_LAYER_PARALLAX_SCALE_Y).GetFloat()

		For Local child:XMLElement = EachIn node.Children
			If child.Name = NODE_DATA Then
				rv.mapData = ReadTileData(child, rv)
			End
		Next

		DoPostLoad(rv)
		Return rv
	End

	Method ReadObjectLayer:TileMapObjectLayer(node:XMLElement)
		Local rv:TileMapObjectLayer = tileMap.CreateObjectLayer()
		ReadProperties(node, rv)
		ReadLayerAttributes(node, rv)

		If node.HasAttribute(ATTR_OBJECTGROUP_COLOR) Then rv.color = ColorToInt(node.GetAttribute(ATTR_OBJECTGROUP_COLOR))

		For Local child:XMLElement = EachIn node.Children
			If child.Name = NODE_OBJECT Then
				rv.objects.Add(ReadObject(child, rv))
			End
		Next

		DoPostLoad(rv)
		Return rv
	End

	Method ReadImage:TileMapImage(node:XMLElement)
		Local rv:TileMapImage = tileMap.CreateImage()
		ReadProperties(node, rv)

		If node.HasAttribute(ATTR_IMAGE_SOURCE) Then rv.source = StripDir(node.GetAttribute(ATTR_IMAGE_SOURCE))
		If node.HasAttribute(ATTR_IMAGE_WIDTH) Then rv.width = Int(node.GetAttribute(ATTR_IMAGE_WIDTH))
		If node.HasAttribute(ATTR_IMAGE_HEIGHT) Then rv.height = Int(node.GetAttribute(ATTR_IMAGE_HEIGHT))
		If node.HasAttribute(ATTR_IMAGE_TRANS) Then rv.trans = node.GetAttribute(ATTR_IMAGE_TRANS)
		If rv.trans.Length > 0 Then
			rv.transR = HexToDec(rv.trans[0..2])
			rv.transG = HexToDec(rv.trans[2..4])
			rv.transB = HexToDec(rv.trans[4..6])
		EndIf

		DoPostLoad(rv)
		Return rv
	End

	Method ReadTile:TileMapTile(node:XMLElement)
		Local id:Int = Int(node.GetAttribute(ATTR_TILE_ID, "0"))
		Local rv:TileMapTile = tileMap.CreateTile(id)
		ReadProperties(node, rv)
		DoPostLoad(rv)
		Return rv
	End

	Method ReadObject:TileMapObject(node:XMLElement, layer:TileMapObjectLayer)
		Local rv:TileMapObject = tileMap.CreateObject()
		ReadProperties(node, rv)
		If node.HasAttribute(ATTR_OBJECT_NAME) Then rv.name = node.GetAttribute(ATTR_OBJECT_NAME)
		If node.HasAttribute(ATTR_OBJECT_TYPE) Then rv.objectType = node.GetAttribute(ATTR_OBJECT_TYPE)
		If node.HasAttribute(ATTR_OBJECT_X) Then rv.x = Int(node.GetAttribute(ATTR_OBJECT_X))
		If node.HasAttribute(ATTR_OBJECT_Y) Then rv.y = Int(node.GetAttribute(ATTR_OBJECT_Y))
		If node.HasAttribute(ATTR_OBJECT_WIDTH) Then rv.width = Int(node.GetAttribute(ATTR_OBJECT_WIDTH))
		If node.HasAttribute(ATTR_OBJECT_HEIGHT) Then rv.height = Int(node.GetAttribute(ATTR_OBJECT_HEIGHT))
		DoPostLoad(rv)
		Return rv
	End

	Method ReadTileData:TileMapData(node:XMLElement, layer:TileMapTileLayer)
		Local rv:TileMapData = tileMap.CreateData(layer.width, layer.height)

		' default to raw xml (ugly)
		Local encoding$ = DATA_ENCODING_RAW
		If node.HasAttribute(ATTR_DATA_ENCODING) Then encoding = node.GetAttribute(ATTR_DATA_ENCODING)

		If encoding = DATA_ENCODING_RAW Then
			' TODO: raw xml
		ElseIf encoding = DATA_ENCODING_CSV Then
			' TODO: csv encoding
		ElseIf encoding = DATA_ENCODING_BASE64 Then
			Local bytes:Int[] = DecodeBase64Bytes(node.Value)
			If node.HasAttribute(ATTR_DATA_COMPRESSION) Then
				' TODO: compression
			End
			For Local i% = 0 Until bytes.Length Step 4
				' little endian
				Local gid% = bytes[i]
				gid += bytes[i + 1] Shl 8
				gid += bytes[i + 2] Shl 16
				gid += bytes[i + 3] Shl 24
				rv.tiles[i / 4] = gid
				rv.cells[i / 4] = tileMap.CreateCell(gid, (i / 4) Mod rv.width, (i / 4) / rv.width)
			Next
		End
		Return rv
	End
End

' TileMapProperties
' Container for properties.
Class TileMapProperties
	Field props:StringMap<TileMapProperty> = New StringMap<TileMapProperty>

	Method Has:Bool(name:String)
		Return props.Contains(name)
	End

	Method Get:TileMapProperty(name:String)
		Return props.Get(name)
	End

	Method Set:Void(name:String, prop:TileMapProperty)
		props.Set(name, prop)
	End
End

' TileMap
' The main Map class.
Class TileMap Extends TileMapPropertyContainer Implements TileMapPostLoad

	' attributes
	Field version:String = "1.0"
	Field orientation:String = MAP_ORIENTATION_ORTHOGONAL
	Field width:Int
	Field height:Int
	Field tileWidth:Int = 32
	Field tileHeight:Int = 32

	' children
	Field tilesets:StringMap<TileMapTileset> = New StringMap<TileMapTileset>
	Field layers:ArrayList<TileMapLayer> = New ArrayList<TileMapLayer>

	' post-load
	Field layerNames:StringMap<TileMapLayer> = New StringMap<TileMapLayer>
	Field tiles:TileMapTile[]
	Field maxTileWidth:Int
	Field maxTileHeight:Int
	Field wrapX:Bool = False
	Field wrapY:Bool = False

	' override this to configure a layer (called on every render)
	Method ConfigureLayer:Void(tileLayer:TileMapLayer)
	End

	' override this to draw a tile
	Method DrawTile:Void(tileLayer:TileMapTileLayer, mapTile:TileMapTile, x:Int, y:Int)
	End

	' override this to create a custom tile class
	Method CreateTile:TileMapTile(id:Int)
		Return New TileMapTile(id)
	End

	' override this to create a custom tileset class
	Method CreateTileset:TileMapTileset()
		Return New TileMapTileset
	End

	' override this to create a custom tile layer class
	Method CreateTileLayer:TileMapTileLayer()
		Return New TileMapTileLayer
	End

	' override this to create a custom object layer class
	Method CreateObjectLayer:TileMapObjectLayer()
		Return New TileMapObjectLayer
	End

	' override this to create a custom image class
	Method CreateImage:TileMapImage()
		Return New TileMapImage
	End

	' override this to create a custom object class
	Method CreateObject:TileMapObject()
		Return New TileMapObject
	End

	' override this to create a custom cell class
	Method CreateCell:TileMapCell(gid:Int, x:Int, y:Int)
		Return New TileMapCell(gid, x, y)
	End

	' override this to create a custom data class
	Method CreateData:TileMapData(width:Int, height:Int)
		Return New TileMapData(width, height)
	End

	' override this to perform additional post-loading functionality (remember to call Super.PostLoad() first)
	Method PostLoad:Void()
		Local totaltiles% = 0, ts:TileMapTileset
		Local alltiles:ArrayList<TileMapTile> = New ArrayList<TileMapTile>
		For Local ts:TileMapTileset = EachIn tilesets.Values()
			' load the image
			ts.image = game.images.LoadTileset(ts.imageNode.source, ts.tileWidth, ts.tileHeight, ts.margin, ts.spacing)
			' get the cell count
			ts.tileCount = ts.image.tileCount

			' update max tile size
			If maxTileWidth < ts.tileWidth Then maxTileWidth = ts.tileWidth
			If maxTileHeight < ts.tileHeight Then maxTileHeight = ts.tileHeight

			' build tile list
			ts.tiles = New TileMapTile[ts.tileCount]
			For Local t:TileMapTile = EachIn ts.tileNodes
				ts.tiles[t.id] = t
			Next
			For Local i% = 0 Until ts.tiles.Length
				If ts.tiles[i] = Null Then
					ts.tiles[i] = CreateTile(i)
				End
				ts.tiles[i].gid = ts.firstGid + i
				ts.tiles[i].image = ts.image
				ts.tiles[i].width = ts.tileWidth
				ts.tiles[i].height = ts.tileHeight
				alltiles.Add(ts.tiles[i])
			Next
			' update total tiles
			totaltiles += ts.tileCount
		Next

		' make our cache
		tiles = New TileMapTile[totaltiles]
		For Local t:TileMapTile = EachIn alltiles
			tiles[t.gid - 1] = t
		Next

		' calculate the max tile size per layer
		For Local l:TileMapLayer = EachIn layers
			If TileMapTileLayer(l) <> Null Then
				Local tl:TileMapTileLayer = TileMapTileLayer(l)
				For Local i% = 0 Until tl.mapData.tiles.Length
					If tl.mapData.tiles[i] > 0 Then
						If tl.maxTileWidth < tiles[tl.mapData.tiles[i] - 1].width Then tl.maxTileWidth = tiles[tl.mapData.tiles[i] - 1].width
						If tl.maxTileHeight < tiles[tl.mapData.tiles[i] - 1].height Then tl.maxTileHeight = tiles[tl.mapData.tiles[i] - 1].height
					End
				Next
			End
		Next
	End

	#Rem
	Method WorldToMap:TPoint(worldPoint:TPoint)
		If worldPoint.X < 0 Or worldPoint.Y < 0 Or worldPoint.X > Width * TileWidth Or worldPoint.Y > Height * TileHeight Then
			' out of range!
			Return Null
		EndIf
		Local rv:TPoint = New TPoint.CreatePoint(worldPoint.X / TileWidth, worldPoint.Y / TileHeight)
		If worldPoint.X = Width * TileWidth Then rv.X:-1
		If worldPoint.Y = Height * TileHeight Then rv.Y:-1
		Return rv
	End
	#End

	Method GetAllObjects:ArrayList<TileMapObject>()
		#Rem
		Local layer:TTiledLayer
		Local obj:TTiledObject
		Local rv:TList = New TList
		For layer = EachIn Layers
			If TTiledObjectLayer(layer) <> Null Then
				For obj = EachIn TTiledObjectLayer(layer).Objects
					rv.AddLast(obj)
				Next
			EndIf
		Next
		Return rv
		#End
	End

	Method FindObjectByName:TileMapObject(name:String)
		#Rem
		Local layer:TTiledLayer, obj:TTiledObject
		For layer = EachIn Layers
			If TTiledObjectLayer(layer) <> Null Then
				For obj = EachIn TTiledObjectLayer(layer).Objects
					If obj.Name = name Then Return obj
				Next
			EndIf
		Next
		#End
		Return Null
	End

	' bx,by,bw,bh = render bounds (screen)
	' sx,sy = scale x/y (float, defaults to 1) i'll do this later
	' wx,wy = wrap x/y (boolean, defaults to false)
	Method RenderMap:Void(bx%, by%, bw%, bh%, sx# = 1, sy# = 1)
		Local x%, y%, rx%, ry%, mx%, my%, mx2%, my2%, modx%, mody%
		For Local layer:TileMapLayer = EachIn layers
			If layer.visible And TileMapTileLayer(layer) <> Null Then
				Local tl:TileMapTileLayer = TileMapTileLayer(layer)
				Local mapTile:TileMapTile, gid%
				ConfigureLayer(layer)
				' ortho
				If orientation = MAP_ORIENTATION_ORTHOGONAL Then
					modx = (bx * tl.parallaxScaleX) mod tileWidth
					mody = (by * tl.parallaxScaleY) mod tileHeight
					y = by
					my = Int(Floor(Float(by * tl.parallaxScaleY) / Float(tileHeight)))
					While y < by + bh + tl.maxTileHeight
						x = bx - tl.maxTileWidth
						mx = Int(Floor(Float(bx * tl.parallaxScaleX) / Float(tileWidth)))
						While x < bx + bw + tl.maxTileWidth
							If (wrapX Or (mx >= 0 And mx < width)) And (wrapY Or (my >= 0 And my < height)) Then
								mx2 = mx
								my2 = my
								While mx2 < 0
									mx2 += width
								End
								While mx2 >= width
									mx2 -= width
								End
								While my2 < 0
									my2 += height
								End
								While my2 >= height
									my2 -= height
								End
								gid = tl.mapData.GetCell(mx2, my2).gid
								If gid > 0 Then
									mapTile = tiles[gid - 1]

									If modx < 0 Then modx += tileWidth
									If mody < 0 Then mody += tileHeight
									rx = x - modx - bx
									ry = y - mody - by
									DrawTile(tl, mapTile, rx, ry)
									'DrawText(my, rx, ry + 10)
								End
							End
							x += tileWidth
							mx += 1
						End
						y += tileHeight
						my += 1
					End

				' iso
				ElseIf orientation = MAP_ORIENTATION_ISOMETRIC Then
					' TODO: wrapping
					For y = 0 Until tl.width + tl.height
						ry = y
						rx = 0
						While ry >= tl.height
							ry -= 1
							rx += 1
						Wend
						While ry >= 0 And rx < tl.width
							'gid = tl.MapData.Get(rx, ry)
							gid = tl.mapData.GetCell(rx, ry).gid
							If gid > 0 Then
								mapTile = tiles[gid - 1]
								DrawTile(tl, mapTile, (rx - ry - 1) * tileWidth / 2, (rx + ry + 2) * tileHeight / 2 - mapTile.height)
							EndIf
							ry -= 1
							rx += 1
						End
					Next
				End
			End
		Next
	End

	Method GetBounds:TileMapRect()
		Local rv:TileMapRect = New TileMapRect
		If orientation = MAP_ORIENTATION_ORTHOGONAL Then
			rv.x = 0
			rv.y = tileHeight - maxTileHeight
			rv.w = (width - 1) * tileWidth + maxTileWidth
			rv.h = (height - 1) * tileHeight + maxTileHeight
		ElseIf orientation = MAP_ORIENTATION_ISOMETRIC Then
			rv.x = -height * tileWidth / 2
			rv.y = tileHeight - maxTileHeight
			rv.w = (width - 2) * tileWidth / 2 + maxTileWidth - rv.X
			rv.h = (width + height) * tileHeight / 2 - rv.Y
		EndIf
		Return rv
	End

	#Rem
	Method ForEachMapCell(func:Int(layer:TTiledTileLayer, cell:TTiledMapCell, delta:Long), delta:Long)
		Local layer:TTiledTileLayer
		Local i%
		For layer = EachIn Layers
			For i = 0 To layer.MapData.Cells.Length - 1
				func(layer, layer.MapData.Cells[i], delta)
			Next
		Next
	End
	#End

<<<<<<< .mine
	Method UpdateAnimation:Void(timePassed:Int)
=======
	Method UpdateAnimation:Void(delta:Float)
>>>>>>> .r140
		Local layer:TileMapLayer, tl:TileMapTileLayer, cell:TileMapCell, t:TileMapTile
		' loop on each layer
		For layer = EachIn layers
			' cast
			tl = TileMapTileLayer(layer)

			' if the layer is a tile layer
			If tl <> Null Then
				' loop on each cell
				For cell = EachIn tl.mapData.cells
					' if the cell exists and has a value
					If cell <> Null And cell.gid > 0 Then
						' get the tile
						t = tiles[cell.gid-1]

						' if the direction is 0 (paused), do nothing
						If t <> Null And cell.direction <> 0 Then
							' add our time to the time passed for the cell
							cell.timePassed += timePassed

							' if this tile has animation information
							If t.animated Then
								' get the new direction if we have one
								If t.hasAnimDirection Then cell.direction = t.animDirection

								' while it's not paused and we're not up to the current frame
								While cell.direction <> 0 And cell.timePassed >= t.animDelay
									' move to the next frame
									cell.timePassed -= t.animDelay
									cell.gid += cell.direction * t.animNext

									' get the tile for the new frame
									t = tiles[cell.gid-1]

									' if there's animation information, get it
									If t <> Null And t.animated Then
										' if the tile has a direction assigned to it, use it (we might be turning around)
										If t.hasAnimDirection Then cell.direction = t.animDirection

									' otherwise, pause and die
									Else
										cell.direction = 0
										Exit
									End
								End

							' no animation information, so pause
							Else
								cell.direction = 0
							End
						End
					End
				Next
			End
		Next
	End
End

Class TileMapTileset Implements TileMapPostLoad
	' attributes
	Field firstGid:Int
	Field name:String
	Field tileWidth:Int
	Field tileHeight:Int
	Field spacing:Int
	Field margin:Int
	Field source:String

	' children
	Field imageNode:TileMapImage
	Field tileNodes:ArrayList<TileMapTile> = New ArrayList<TileMapTile>

	' post load
	Field tiles:TileMapTile[]
	Field image:GameImage
	Field tileCount:Int

	Method PostLoad:Void()
	End
End

Class TileMapImage Implements TileMapPostLoad
	' attributes
	Field source$
	Field width%
	Field height%
	Field trans$ = ""

	' post-load
	Field transR%, transG%, transB%

	Method PostLoad:Void()
	End
End

'<layer> and <objectgroup>
Class TileMapLayer Extends TileMapPropertyContainer Implements TileMapPostLoad Abstract
	' attributes
	Field name$
	Field width%
	Field height%
	Field visible% = True
	Field opacity:Float = 1

	Method PostLoad:Void()
	End
End

Class TileMapData
	Field width%
	Field height%
	Field tiles:Int[]
	Field cells:TileMapCell[]

	Method New(width%, height%)
		Self.width = width
		Self.height = height
		Self.tiles = New Int[width * height]
		Self.cells = New TileMapCell[width * height]
	End Method

	Method Get%(x%, y%)
		Return tiles[x + y * width]
	End

	Method Set:Void(x%, y%, gid%)
		tiles[x + y * width] = gid
	End

	Method GetCell:TileMapCell(x%, y%)
		Return cells[x + y * width]
	End

	Method SetCell:Void(x%, y%, cell:TileMapCell)
		cells[x + y * width] = cell
	End
End

Class TileMapTileLayer Extends TileMapLayer
	Field mapData:TileMapData
	Field maxTileWidth%
	Field maxTileHeight%
	Field parallaxOffsetX# = 0
	Field parallaxOffsetY# = 0
	Field parallaxScaleX# = 1
	Field parallaxScaleY# = 1
End

Class TileMapObjectLayer Extends TileMapLayer
	' attributes
	Field color%
	' children
	Field objects:ArrayList<TileMapObject> = New ArrayList<TileMapObject>
End

Class TileMapObject Extends TileMapPropertyContainer
	' attributes
	Field name:String
	Field objectType:String
	Field x:Int
	Field y:Int
	Field width:Int
	Field height:Int
End

Class TileMapProperty
Private
	Field valueType% = 0 ' 0=int, 1=float, 2=bool, 3=string
	Field name$ = ""
	Field rawValue$ = ""

Public
	Method New(name:String="default", value:String="")
		Self.name = name
		Self.rawValue = value
		Self.valueType = 3
	End

	Method Set:Void(value:Int)
		rawValue = value
		valueType = 0
	End

	Method Set:Void(value:Float)
		RawValue = value
		ValueType = 1
	End

	Method Set:Void(value:Bool)
		If value Then
			rawValue = "true"
		Else
			rawValue = "false"
		EndIf
		ValueType = 2
	End

	Method Set:Void(value:String)
		rawValue = value
		valueType = 3
	End

	Method GetInt:Int()
		Return Int(rawValue)
		'Local rv% = 0
		'rv = RawValue.ToInt()
		'Catch ex:Object
		'End
		'Return rv
	End

	Method GetFloat:Float()
		Return Float(rawValue)
		'Local rv:Float = 0
		'Try
		'	rv = RawValue.ToFloat()
		'Catch ex:Object
		'EndTry
		'Return rv
	End

	Method GetBool:Bool()
		Local val:String = rawValue.ToLower()
		If val = "true" Or val = "t" Or val = "y" Then Return True
		Return False
		'If val = "false" Or val = "f" Or val = "n" Then Return False
		'Return GetInt() <> 0
	End

	Method GetString:String()
		Return rawValue
	End
End

Class TileMapTile Extends TileMapPropertyContainer Implements TileMapPostLoad
	Field id%
	Field image:GameImage
	Field width:Int
	Field height:Int
	Field gid:Int

	Field animDelay:Float
	Field animNext:Int
	Field animDirection:Int
	Field hasAnimDirection:Bool
	Field animated:Bool

	Method New(id:Int)
		Self.id = id
	End

	Method PostLoad:Void()
		If properties.Has(PROP_TILE_ANIM_DELAY) Then
			animDelay = game.CalcAnimLength(properties.Get(PROP_TILE_ANIM_DELAY).GetInt())
			animated = True
		End
		If properties.Has(PROP_TILE_ANIM_NEXT) Then animNext = properties.Get(PROP_TILE_ANIM_NEXT).GetInt()
		If properties.Has(PROP_TILE_ANIM_DIRECTION) Then
			animDirection = properties.Get(PROP_TILE_ANIM_DIRECTION).GetInt()
			hasAnimDirection = True
		End
	End
End

Class TileMapCell
	' mandatory fields
	Field gid%
	Field x%
	Field y%

	' animation stuff
	Field originalGid%
	Field timePassed:Float = 0 ' the time that has passed since the last frame change
	Field direction% = 1 ' >0 = forward, <0 = backward, 0 = paused

	Method New(gid%, x%, y%)
		Self.gid = gid
		Self.x = x
		Self.y = y
		originalGid = gid
	End
End

Class TileMapRect
	Field x%, y%, w%, h%
End

Function ColorToInt%(str$)
	' TODO: convert a hex color string #rrggbb to a number
	Return 0
End

Function HexToDec%(hexstr$)
	Local chars$ = "0123456789abcdef"
	Local rv% = 0
	hexstr = hexstr.ToLower()
	For Local i% = 0 To hexstr.Length - 1
		rv = rv Shl 4
		Local idx% = chars.Find(hexstr[i])
		If idx >= 0 Then rv += idx
	Next
	Return rv
End

Const PROP_MAP_WRAP_X$ = "wrap_x"
Const PROP_MAP_WRAP_Y$ = "wrap_y"

Const PROP_LAYER_PARALLAX_OFFSET_X$ = "parallax_offset_x"
Const PROP_LAYER_PARALLAX_OFFSET_Y$ = "parallax_offset_y"
Const PROP_LAYER_PARALLAX_SCALE_X$  = "parallax_scale_x"
Const PROP_LAYER_PARALLAX_SCALE_Y$  = "parallax_scale_y"

Const PROP_TILE_ANIM_DELAY$     = "anim_delay"
Const PROP_TILE_ANIM_NEXT$      = "anim_next"
Const PROP_TILE_ANIM_DIRECTION$ = "anim_direction"

Const DATA_ENCODING_RAW$    = ""
Const DATA_ENCODING_CSV$    = "csv"
Const DATA_ENCODING_BASE64$ = "base64"

Const MAP_ORIENTATION_ORTHOGONAL$   = "orthogonal"
Const MAP_ORIENTATION_ISOMETRIC$    = "isometric"

Const ATTR_MAP_VERSION$         = "version"
Const ATTR_MAP_ORIENTATION$     = "orientation"
Const ATTR_MAP_WIDTH$           = "width"
Const ATTR_MAP_HEIGHT$          = "height"
Const ATTR_MAP_TILEWIDTH$       = "tilewidth"
Const ATTR_MAP_TILEHEIGHT$      = "tileheight"
Const ATTR_TILESET_FIRSTGID$    = "firstgid"
Const ATTR_TILESET_NAME$        = "name"
Const ATTR_TILESET_TILEWIDTH$   = "tilewidth"
Const ATTR_TILESET_TILEHEIGHT$  = "tileheight"
Const ATTR_TILESET_SPACING$     = "spacing"
Const ATTR_TILESET_MARGIN$      = "margin"
Const ATTR_TILESET_SOURCE$      = "source"
Const ATTR_IMAGE_SOURCE$        = "source"
Const ATTR_IMAGE_WIDTH$         = "width"
Const ATTR_IMAGE_HEIGHT$        = "height"
Const ATTR_IMAGE_TRANS$         = "trans"
Const ATTR_TILE_ID$             = "id"
Const ATTR_LAYER_NAME$          = "name"
Const ATTR_LAYER_WIDTH$         = "width"
Const ATTR_LAYER_HEIGHT$        = "height"
Const ATTR_LAYER_VISIBLE$       = "visible"
Const ATTR_LAYER_OPACITY$       = "opacity"
Const ATTR_DATA_ENCODING$       = "encoding"
Const ATTR_DATA_COMPRESSION$    = "compression"
Const ATTR_PROPERTY_NAME$       = "name"
Const ATTR_PROPERTY_VALUE$      = "value"
Const ATTR_OBJECTGROUP_COLOR$   = "color"
Const ATTR_OBJECTGROUP_NAME$    = "name"
Const ATTR_OBJECTGROUP_WIDTH$   = "width"
Const ATTR_OBJECTGROUP_HEIGHT$  = "height"
Const ATTR_OBJECT_NAME$         = "name"
Const ATTR_OBJECT_TYPE$         = "type"
Const ATTR_OBJECT_X$            = "x"
Const ATTR_OBJECT_Y$            = "y"
Const ATTR_OBJECT_WIDTH$        = "width"
Const ATTR_OBJECT_HEIGHT$       = "height"

Const NODE_MAP$                 = "map"
Const NODE_TILESET$             = "tileset"
Const NODE_IMAGE$               = "image"
Const NODE_TILE$                = "tile"
Const NODE_LAYER$               = "layer"
Const NODE_DATA$                = "data"
Const NODE_PROPERTIES$          = "properties"
Const NODE_PROPERTY$            = "property"
Const NODE_OBJECTGROUP$         = "objectgroup"
Const NODE_OBJECT$              = "object"


Updated SpaceBugs.monkey

Updated SpaceBugs.monkey

--HG--
extra : convert_revision : svn%3Ae934d3cd-0d57-f34a-94d0-9e8d31ae1c29/trunk%40117

' Strict code mode please
Strict

' The modules
Import mojo
Import diddy

' Starting Point
Function Main:Int()
	game = new MyGame()
End

' Screens in the game
Global titleScreen:Screen = New TitleScreen()
Global gameScreen:Screen = New GameScreen()
Global nextLevelScreen:Screen = New NextLevelScreen()
Global gameOverScreen:Screen = New GameOverScreen()

' The Game
Class MyGame Extends DiddyApp
	Method OnCreate:Int()
		Super.OnCreate()

		' Set the font
		SetFont(LoadImage("graphics/font_16.png",16,16,64))

		LoadImages()
		LoadSounds()

		titleScreen.PreStart()

		Return 0
	End

	'***********************
	'* Load Images
	'***********************
	Method LoadImages:Void()
		' create tmpImage for animations
		Local tmpImage:Image

		images.Load("galaxy2.png", "", False)
		images.LoadAnim("Ship1.png", 64, 64, 7, tmpImage)
		images.LoadAnim("rusher.png", 64, 32, 24, tmpImage)
		images.LoadAnim("missile.png", 16, 16, 2, tmpImage)

	End

	'***********************
	'* Load Sounds
	'***********************
	Method LoadSounds:Void()
		sounds.Load("lazer")
		sounds.Load("boom3")
	End
End

Class TitleScreen Extends Screen
	Field background:GameImage

	Method New()
		name = "Title"
	End

	Method Start:Void()
		background = game.images.Find("galaxy2")
		game.MusicPlay("ShowYourMoves.ogg", True)
		game.screenFade.Start(50, false)
	End

	Method Render:Void()
		DrawImage background.image, 0, 0
		Scale 2, 2
		DrawText "ATTACK OF THE", SCREEN_WIDTH2 / 2, (SCREEN_HEIGHT2-30) / 2, 0.5, 0.5
		DrawText "SPACE-BUGS", SCREEN_WIDTH2 / 2, (SCREEN_HEIGHT2) / 2, 0.5, 0.5
		Scale .5, .5
		DrawText "SPACE TO PLAY!", SCREEN_WIDTH2, SCREEN_HEIGHT2 + 60, 0.5, 0.5
		DrawText "GRAPHICS FROM XENON 2000: PROJECT PCF", SCREEN_WIDTH2, SCREEN_HEIGHT - 40, 0.5, 0.5
		DrawText "MUSIC BY KEVIN MACLEOD", SCREEN_WIDTH2, SCREEN_HEIGHT - 20, 0.5, 0.5
	End

	Method Update:Void()
		If KeyHit(KEY_SPACE) or MouseHit(0)
			game.screenFade.Start(50, True, True, True)
			game.nextScreen = gameScreen
		End
		If KeyHit(KEY_ESCAPE)
			game.screenFade.Start(50, True, True, True)
			game.nextScreen = game.exitScreen
		End
	End
End

Class GameScreen Extends Screen
	Field background:GameImage
	Field player:Player
	Field lifeImage:GameImage
	Field missileImage:GameImage

	Method New()
		name = "Game Screen"
	End

	Method Start:Void()
		background = game.images.Find("galaxy2")
		Local gi:GameImage = game.images.Find("Ship1")
		player = New Player(gi, SCREEN_WIDTH2, SCREEN_HEIGHT - gi.h, game.images.Find("missile"))

		StartLevel()
		game.MusicPlay("SpaceFighterLoop.ogg", True)
		'start fade
		game.screenFade.Start(50, False, True, True)
	End

	Method ClearLevel:Void()
		Enemy.list.Clear()
	End

	Method StartLevel:Void(level% = 1)
		ClearLevel()

		'create a few enemies
		Local maxAliensAcross%
		Local maxAliensDown%

		#if TARGET="android"
			maxAliensAcross = 2
			maxAliensDown = 2
		#else
			maxAliensAcross = 7
			maxAliensDown = 4
		#endif
		Local gi:GameImage = game.images.Find("rusher")

		Local e:Enemy
		for Local i% = 0 to maxAliensAcross
			for Local j% = 0 to maxAliensDown
				e = new Alien(gi, 64 * i, (40 * j) + 34)
				e.frame = 0
				e.maxFrame = 23
				e.dy = 0
				e.dx = 0.2 + (level/5)
				e.movement = 1
				e.SetFrame(0, 23, 80, True)
				e.score = 10
			next
		next
	End

	Method Render:Void()
		DrawImage background.image, 0, 0
		Alien.DrawAll()
		Bullet.DrawAll()
		player.Draw()
		DrawGUI()
	End

	Method DrawGUI:Void()
		DrawText "SCORE: "+ player.score, 0, 0
	End

	Method Update:Void()
		player.Update()
		Alien.UpdateAll()
		Bullet.UpdateAll()
		CheckCollisions()
		If KeyHit(KEY_ESCAPE)
			game.screenFade.Start(50, True, True, True)
			game.nextScreen = titleScreen
		End
	End

	Method CheckCollisions:Void()
		Local b:Bullet
		Local e:Enemy
		Local hit:Bool = False

		For Local i% = 0 Until Enemy.list.Size
			e = Enemy.list.Get(i)
			For Local j% = 0 Until Bullet.list.Size
				b = Bullet.list.Get(j)
				if b.Collide(e)
					player.score+=e.score
					Bullet.list.Remove(b)
					Enemy.list.Remove(e)
				End
			Next
		Next
	End
End

Class Player Extends Sprite
	Field score:Int
	Field lives:Int
	Field level:Int
	Field frame:Int
	Field frameDelay:Int
	Field maxFrameDelay:Int = 3
	Field missileImage:GameImage

	Method New(img:GameImage, x#, y#, missileImage:GameImage)
		Super.New(img, x, y)
		score = 0
		lives = 3
		level = 1
		frame = 3
		speedX = 1
		maxXSpeed = 5
		Self.missileImage = missileImage
	End

	Method Update:Void()
		If KeyDown(KEY_LEFT)
			Self.dx-=Self.speedX
			RollLeft()
		Else If KeyDown(KEY_RIGHT)
			Self.dx+=Self.speedX
			RollRight()
		Else
			SlowShip()
		End
		If KeyHit(KEY_SPACE)
			New Bullet(missileImage, x, y)
		End
		If dx > Self.maxXSpeed
			dx = Self.maxXSpeed
		End
		If dx < -Self.maxXSpeed
			dx = -Self.maxXSpeed
		End
		Self.Move()
		' limit the player to the screen
		If x < 0 + image.w2
			x = image.w2
		End
		If x > SCREEN_WIDTH - image.w2
			x = SCREEN_WIDTH - image.w2
		End
	End

	Method RollLeft:Void()
		If frame > 0
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame-=1
				frameDelay = 0
			End
		End
	End

	Method RollRight:Void()
		If frame < 6
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame+=1
				frameDelay = 0
			End
		End
	End

	Method SlowShip:Void()
		If frame < 3
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame+=1
				frameDelay = 0
			End
		Else If frame > 3
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame-=1
				frameDelay = 0
			End
		End
		If dx > 0
			dx-=Self.speedX/4
		Else If dx < 0
			dx+=Self.speedX/4
		End
	End
End

Class Alien Extends Enemy

	Method New(img:GameImage, x#, y#)
		Super.New(img, x, y)
		Self.frame = 0
		Self.dy = Rnd(1, 3)
		Self.list.Add(Self)
	End Method

	Method Update:Void()
		Super.Update()
		Select movement
			Case 1
				if x > SCREEN_WIDTH
					dx = -dx
					x = SCREEN_WIDTH - 1
					moveCounter = 50

				else if x < 0
					dx = -dx
					x = 0 + 1
					moveCounter = 50

				EndIf
				if moveCounter > 1
					dy = 1
					moveCounter-=1 * dt.delta
				else
					dy = 0
					moveCounter = 0
				end if
		End
	End
End

Class Enemy Extends Sprite
	Global list:ArrayList<Enemy> = New ArrayList<Enemy>
	Field movement:Int
	Field moveCounter:Float
	Field type:Int
	Field score:Int

	Method New(img:GameImage, x#, y#)
		Super.New(img, x, y)
		Self.frame = 0
		Self.dy = Rnd(1, 3)
		list.Add(Self)
	End

	Function UpdateAll:Void()
		For Local i% = 0 Until list.Size
			Local e:Enemy = list.Get(i)
			e.Update()
		Next
	End

	Method Update:Void()
		UpdateAnimation()
		Move()
		if y > SCREEN_HEIGHT + image.h
			list.Remove(self)
		EndIf
	End

	Function DrawAll:Void()
		For Local i% = 0 Until list.Size
			Local e:Enemy = list.Get(i)
			e.Draw()
		Next
	End
End

Class Bullet Extends Sprite
	Global list:ArrayList<Bullet> = New ArrayList<Bullet>

	Method New(img:GameImage, x#, y#)
		Super.New(img, x, y)
		Self.speedY = -6
		list.Add(Self)
	End

	Function UpdateAll:Void()
		For Local i% = 0 Until list.Size
			Local b:Bullet = list.Get(i)
			b.Update()
		Next
	End

	Method Update:Void()
		Self.UpdateAnimation()
		dy = Self.speedY
		Move()
		if y < -image.h then
			list.Remove(Self)
		End
	End

	Function DrawAll:Void()
		For Local i% = 0 Until list.Size
			Local b:Bullet = list.Get(i)
			b.Draw()
		Next
	End

End

Class NextLevelScreen Extends Screen
	Method New()
		name = "Next Level"
	End

	Method Start:Void()
		game.screenFade.Start(25, false)
	End

	Method Render:Void()
		Cls
	End

	Method Update:Void()

	End
End

Class GameOverScreen Extends Screen
	Method New()
		name = "Game Over"
	End

	Method Start:Void()
		game.screenFade.Start(25, false)
	End

	Method Render:Void()
		Cls
	End

	Method Update:Void()
	End
End

' Strict code mode please
Strict

' The modules
Import mojo

Import diddy

' Starting Point
Function Main:Int()
	game = new MyGame()
End

' Screens in the game
Global titleScreen:Screen = New TitleScreen()
Global gameScreen:Screen = New GameScreen()
Global nextLevelScreen:Screen = New NextLevelScreen()
Global gameOverScreen:Screen = New GameOverScreen()

' The Game
Class MyGame Extends DiddyApp
	Method OnCreate:Int()
		Super.OnCreate()

		' Set the font
		SetFont(LoadImage("graphics/font_16.png",16,16,64))

		LoadImages()
		LoadSounds()

		titleScreen.PreStart()

		Return 0
	End

	'***********************
	'* Load Images
	'***********************
	Method LoadImages:Void()
		' create tmpImage for animations
		Local tmpImage:Image

		images.Load("galaxy2.png", "", False)
		images.LoadAnim("Ship1.png", 64, 64, 7, tmpImage)
		images.LoadAnim("rusher.png", 64, 32, 24, tmpImage)
	End

	'***********************
	'* Load Sounds
	'***********************
	Method LoadSounds:Void()
		sounds.Load("lazer")
		sounds.Load("boom3")
	End
End

Class TitleScreen Extends Screen
	Field background:GameImage

	Method New()
		name = "Title"
	End

	Method Start:Void()
		background = game.images.Find("galaxy2")

		game.screenFade.Start(25, false)
	End

	Method Render:Void()
		DrawImage background.image, 0, 0
		Scale 2, 2
		DrawText "ATTACK OF THE", SCREEN_WIDTH2 / 2, (SCREEN_HEIGHT2-30) / 2, 0.5, 0.5
		DrawText "SPACE-BUGS", SCREEN_WIDTH2 / 2, (SCREEN_HEIGHT2) / 2, 0.5, 0.5
		Scale .5, .5
		DrawText "SPACE TO PLAY!", SCREEN_WIDTH2, SCREEN_HEIGHT2 + 60, 0.5, 0.5
		DrawText "GRAPHICS FROM XENON 2000: PROJECT PCF", SCREEN_WIDTH2, SCREEN_HEIGHT - 20, 0.5, 0.5
	End

	Method Update:Void()
		If KeyHit(KEY_SPACE) or MouseHit(0)
			game.screenFade.Start(25, true)
			game.nextScreen = gameScreen
		End
		If KeyHit(KEY_ESCAPE)
			game.screenFade.Start(25, true)
			game.nextScreen = game.exitScreen
		End
	End
End

Class GameScreen Extends Screen
	Field background:GameImage
	Field player:Player
	Field lIfeImage:GameImage

	Method New()
		name = "Game Screen"
	End

	Method Start:Void()
		background = game.images.Find("galaxy2")
		Local gi:GameImage = game.images.Find("Ship1")
		player = New Player(gi, SCREEN_WIDTH2, SCREEN_HEIGHT - gi.h)

		StartLevel()

		'start fade
		game.screenFade.Start(25, false)
	End

	Method ClearLevel:Void()
		If Alien.list <> Null Alien.list.Clear()
	End

	Method StartLevel:Void(level% = 1)
		ClearLevel()

		'create a few enemies
		Local maxAliensAcross%
		Local maxAliensDown%

		#if TARGET="android"
			maxAliensAcross = 2
			maxAliensDown = 2
		#else
			maxAliensAcross = 7
			maxAliensDown = 4
		#endif
		Local gi:GameImage = game.images.Find("rusher")

		Local e:Enemy
		for Local i% = 0 to maxAliensAcross
			for Local j% = 0 to maxAliensDown
				e = new Alien(gi, 64 * i, (40 * j) + 34)
				e.frame = 0
				e.maxFrame = 23
				e.dy = 0
				e.dx = 1 + (level/5)
				e.movement = 1
				e.SetFrame(0, 23, 80, True)
			next
		next
	End

	Method Render:Void()
		DrawImage background.image, 0, 0
		Alien.DrawAll()
		player.Draw()
	End

	Method Update:Void()
		player.Update()
		Alien.UpdateAll()
		If KeyHit(KEY_ESCAPE)
			game.screenFade.Start(25, true)
			game.nextScreen = titleScreen
		End
	End
End

Class Player Extends Sprite
	Field score:Int
	Field lives:Int
	Field level:Int
	Field frame:Int
	Field frameDelay:Int
	Field maxFrameDelay:Int = 3

	Method New(img:GameImage, x#, y#)
		Super.New(img, x, y)
		score = 0
		lives = 3
		level = 1
		frame = 3
		speedX = 1
		maxXSpeed = 5
	End Method

	Method Update:Void()
		If KeyDown(KEY_LEFT)
			Self.dx-=Self.speedX
			RollLeft()
		Else If KeyDown(KEY_RIGHT)
			Self.dx+=Self.speedX
			RollRight()
		Else
			SlowShip()
		End
		If dx > Self.maxXSpeed
			dx = Self.maxXSpeed
		End
		If dx < -Self.maxXSpeed
			dx = -Self.maxXSpeed
		End
		Self.Move()
		' limit the player to the screen
		If x < 0 + image.w2
			x = image.w2
		End
		If x > SCREEN_WIDTH - image.w2
			x = SCREEN_WIDTH - image.w2
		End
	End

	Method RollLeft:Void()
		If frame > 0
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame-=1
				frameDelay = 0
			End
		End
	End

	Method RollRight:Void()
		If frame < 6
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame+=1
				frameDelay = 0
			End
		End
	End

	Method SlowShip:Void()
		If frame < 3
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame+=1
				frameDelay = 0
			End
		Else If frame > 3
			frameDelay+=1
			If frameDelay > maxFrameDelay
				frame-=1
				frameDelay = 0
			End
		End
		If dx > 0
			dx-=Self.speedX/4
		Else If dx < 0
			dx+=Self.speedX/4
		End
	End
End

Class Alien Extends Enemy
	Method New(img:GameImage, x#, y#)
		Super.New(img, x, y)
		if list = null then list = new List<Enemy>
		self.frame = 0
		self.dy = Rnd(1, 3)
		list.AddLast self
	End Method

	Method Update:Void()
		Super.Update()
		Select movement
			Case 1
				if x > SCREEN_WIDTH
					dx = -dx
					x = SCREEN_WIDTH
					moveCounter = 50

				else if x < 0
					dx = -dx
					x = 0
					moveCounter = 50

				EndIf
				if moveCounter > 1
					dy = 1
					moveCounter-=1 * dt.delta
				else
					dy = 0
					moveCounter = 0
				end if
		End
	End
End

Class Enemy Extends Sprite
	Global list:List<Enemy>
	Field movement:Int
	Field moveCounter#
	field type%

	Method New(img:GameImage, x#, y#)
		Super.New(img, x, y)
		if list = null then list = new List<Enemy>
		self.frame = 0
		self.dy = Rnd(1, 3)
		list.AddLast self
	End Method

	Function UpdateAll:Void()
		If not list Return
		For Local b:Enemy = Eachin list
			b.Update()
		Next
	End Function

	Method Update:Void()
		UpdateAnimation()
		Move()
		if y > SCREEN_HEIGHT + image.h
			list.Remove(self)
		EndIf
	End Method

	Function DrawAll:Void()
		If not list Return
		For Local b:Enemy = Eachin list
			b.Draw()
		Next
	End Function
End Class

Class NextLevelScreen Extends Screen
	Method New()
		name = "Next Level"
	End

	Method Start:Void()
		game.screenFade.Start(25, false)
	End

	Method Render:Void()
		Cls
	End

	Method Update:Void()

	End
End

Class GameOverScreen Extends Screen
	Method New()
		name = "Game Over"
	End

	Method Start:Void()
		game.screenFade.Start(25, false)
	End

	Method Render:Void()
		Cls
	End

	Method Update:Void()
	End
End


don't trigger OnTouchMove if move is below minDistance

Strict

Private

Import bono
Import mojo.input

Public

Class TouchEmitter Implements Updateable, Suspendable
    Private

    Field _touchFingers:Int = MAX_TOUCH_FINGERS
    Field isTouchDown:Bool[MAX_TOUCH_FINGERS]
    Field touchDownDispatched:Bool[MAX_TOUCH_FINGERS]
    Field touchEvents:TouchEvent[MAX_TOUCH_FINGERS]
    Field touchHasMoved:Bool[MAX_TOUCH_FINGERS]

    Public

    Const MAX_TOUCH_FINGERS:Int = 31
    Const RETAIN_UNLIMITED:Int = -1
    Field minDistance:Float = 0
    Field retainSize:Int = RETAIN_UNLIMITED
    Field active:Bool = True
    Field handler:Touchable

    Method OnResume:Void()
    End

    Method OnSuspend:Void()
        For Local i:Int = 0 Until _touchFingers
            touchEvents[i] = Null
        End
    End

    Method OnUpdate:Void(deltatimer:DeltaTimer)
        If Not active Then Return
        If Not handler Then Return

        ReadTouch()
        ProcessTouch()
    End

    Method touchFingers:Void(number:Int) Property
        If number > MAX_TOUCH_FINGERS
            Error("Only " + MAX_TOUCH_FINGERS + " can be tracked.")
        End
        If Not number > 0
            Error("Number of fingers must be greater than 0.")
        End

        _touchFingers = number
    End

    Private

    Method ProcessTouch:Void()
        For Local i:Int = 0 Until _touchFingers
            If touchEvents[i] = Null Then Continue

            If Not touchDownDispatched[i]
                handler.OnTouchDown(touchEvents[i].Copy())
                touchDownDispatched[i] = True
            ElseIf Not isTouchDown[i]
                handler.OnTouchUp(touchEvents[i].Copy())
                touchEvents[i] = Null
            ElseIf touchHasMoved[i]
                handler.OnTouchMove(touchEvents[i])
                touchHasMoved[i] = False
            End
        End
    End

    Method ReadTouch:Void()
        Local diffVector:Vector2D
        Local vector:Vector2D
        Local lastTouchDown:Bool

        For Local i:Int = 0 Until _touchFingers
            lastTouchDown = isTouchDown[i]
            isTouchDown[i] = Bool(TouchDown(i))

            If Not isTouchDown[i] And Not lastTouchDown Then Continue

            If touchEvents[i] = Null
                touchDownDispatched[i] = False
                touchEvents[i] = New TouchEvent(i)
            End

            vector = New Vector2D(TouchX(i), TouchY(i))
            diffVector = vector.Copy().Sub(touchEvents[i].prevPos)

            If diffVector.Length() >= minDistance
                touchEvents[i].Add(vector)
                touchHasMoved[i] = True
                If retainSize > -1 Then touchEvents[i].Trim(retainSize)
            End
        End
    End
End

Strict

Private

Import bono
Import mojo.input

Public

Class TouchEmitter Implements Updateable, Suspendable
    Private

    Field _touchFingers:Int = MAX_TOUCH_FINGERS
    Field isTouchDown:Bool[MAX_TOUCH_FINGERS]
    Field touchDownDispatched:Bool[MAX_TOUCH_FINGERS]
    Field touchEvents:TouchEvent[MAX_TOUCH_FINGERS]

    Public

    Const MAX_TOUCH_FINGERS:Int = 31
    Const RETAIN_UNLIMITED:Int = -1
    Field minDistance:Float = 0
    Field retainSize:Int = RETAIN_UNLIMITED
    Field active:Bool = True
    Field handler:Touchable

    Method OnResume:Void()
    End

    Method OnSuspend:Void()
        For Local i:Int = 0 Until _touchFingers
            touchEvents[i] = Null
        End
    End

    Method OnUpdate:Void(deltatimer:DeltaTimer)
        If Not active Then Return
        If Not handler Then Return

        ReadTouch()
        ProcessTouch()
    End

    Method touchFingers:Void(number:Int) Property
        If number > MAX_TOUCH_FINGERS
            Error("Only " + MAX_TOUCH_FINGERS + " can be tracked.")
        End
        If Not number > 0
            Error("Number of fingers must be greater than 0.")
        End

        _touchFingers = number
    End

    Private

    Method ProcessTouch:Void()
        For Local i:Int = 0 Until _touchFingers
            If touchEvents[i] = Null Then Continue

            If Not touchDownDispatched[i]
                handler.OnTouchDown(touchEvents[i].Copy())
                touchDownDispatched[i] = True
            ElseIf Not isTouchDown[i]
                handler.OnTouchUp(touchEvents[i].Copy())
                touchEvents[i] = Null
            Else
                handler.OnTouchMove(touchEvents[i])
            End
        End
    End

    Method ReadTouch:Void()
        Local diffVector:Vector2D
        Local vector:Vector2D
        Local lastTouchDown:Bool

        For Local i:Int = 0 Until _touchFingers
            lastTouchDown = isTouchDown[i]
            isTouchDown[i] = Bool(TouchDown(i))

            If Not isTouchDown[i] And Not lastTouchDown Then Continue

            If touchEvents[i] = Null
                touchDownDispatched[i] = False
                touchEvents[i] = New TouchEvent(i)
            End

            vector = New Vector2D(TouchX(i), TouchY(i))
            diffVector = vector.Copy().Sub(touchEvents[i].prevPos)

            If diffVector.Length() >= minDistance
                touchEvents[i].Add(vector)
                If retainSize > -1 Then touchEvents[i].Trim(retainSize)
            End
        End
    End
End


_BuildLines simplfy

_BuildLines simplfy

Strict

Import flixel.flxtext
Import flixel.flxtext.driver
Import flixel.flxtext.fontmanager

Import mojo
Import fontmachine.fontmachine

Import "../../data/flx_system_fm_font_8.txt"
Import "../../data/flx_system_fm_font_8_P_1.png"
Import "../../data/flx_system_fm_font_9.txt"
Import "../../data/flx_system_fm_font_9_P_1.png"
Import "../../data/flx_system_fm_font_10.txt"
Import "../../data/flx_system_fm_font_10_P_1.png"
Import "../../data/flx_system_fm_font_11.txt"
Import "../../data/flx_system_fm_font_11_P_1.png"
Import "../../data/flx_system_fm_font_12.txt"
Import "../../data/flx_system_fm_font_12_P_1.png"
Import "../../data/flx_system_fm_font_13.txt"
Import "../../data/flx_system_fm_font_13_P_1.png"
Import "../../data/flx_system_fm_font_14.txt"
Import "../../data/flx_system_fm_font_14_P_1.png"
Import "../../data/flx_system_fm_font_15.txt"
Import "../../data/flx_system_fm_font_15_P_1.png"
Import "../../data/flx_system_fm_font_16.txt"
Import "../../data/flx_system_fm_font_16_P_1.png"

Class FontMachineDriver Extends TextDriver

Private
	Field _width:Int
	Field _text:String
	Field _textLines:StringStack
	Field _multiline:Bool
	Field _countLines:Int
	Field _font:BitmapFont

	Field _fontName:String
	Field _fontHeight:Int = 0
	Field _size:Int = FlxText.MIN_SIZE
	Field _alignment:Float

Public
	Method New()
		_textLines = New StringStack();
	End Method

	Method SetFormat:Void(fontName:String, size:Int, alignment:Int)
		SetAlignment(alignment)
		_fontName = fontName
		_size = size
		_InitFont(fontName, size)
		If (_text.Length > 0) _BuildLines()
	End Method

	Method GetName:String()
		Return "fm"
	End Method

	Method SetWidth:Void(width:Int)
		_width = width
		If (_text.Length > 0) _BuildLines()
	End Method

	Method SetFontName:Void(fontName:String)
		_fontName = fontName
		_InitFont(fontName, _size)
		If (_text.Length > 0) _BuildLines()
	End Method

	Method GetFontName:String()
		Return _fontName
	End Method

	Method SetSize:Void(size:Int)
		_size = size
		_InitFont(_fontName, size)
		If (_text.Length > 0) _BuildLines()
	End Method

	Method GetSize:Int()
		Return _size
	End Method

	Method SetText:Void(text:String)
		_text = text
		If (_width <> 0) _BuildLines()
	End Method

	Method GetText:String()
		Return _text
	End Method

	Method SetAlignment:Void(alignment:Float)
		_alignment = alignment
	End Method

	Method GettAlignment:Float()
		Return _alignment
	End Method

	Method Draw:Void(x:Float, y:Float)
		If (Not _multiline) Then
			_font.DrawText(_text, x, y)
		Else
			For Local line:Int = 0 Until _countLines
				_font.DrawText(_textLines.Get(line), x, y + line*_fontHeight)
			Next
		End If
	End Method

	Method Destroy:Void()
	End Method

Private
	Method _InitFont:Void(fontName:String, size:Int)
		_font = _fontManager.GetFont(fontName, size)
		If (_font = Null) Then
			_font = New BitmapFont(Self.GetFileName(fontName) + size + ".txt", False)

			If (_font = Null And _defaultFont = Null) Then
				Error ("Font " + fontName +  " can't be loaded")
			ElseIf (_font = Null) Then
				_font = _defaultFont
				_fontHeight = _font.GetFontHeight()
				Return
			End If

			_fontManager.AddFont(fontName, size, _font)
			If (_defaultFont = Null) _defaultFont = _font
		End If

		_fontHeight = _font.GetFontHeight()
	End Method

	Method _BuildLines:Void()
		_multiline = False
		_countLines = 0
		_textLines.Clear()

		Local textWidth:Int = _font.GetTxtWidth(_text)

		If (_width < textWidth) Then
			_multiline = True

			Local textLength:Int = _text.Length
			Local range:Int = Ceil(textLength/Float(Floor(textWidth/Float(_width))+1))+1
			Local maxOffset:Int = range
			Local minOffset:Int = 0
			Local offset:Int = maxOffset

			Repeat
				Repeat
					offset-=1
					While (_text[offset] <> KEY_SPACE And offset > minOffset)
						offset-=1
					Wend
					If (offset <= minOffset) Exit
				Until(_font.GetTxtWidth(_text[minOffset..offset]) <= _width)

				If (offset <= minOffset) Then
					While(_font.GetTxtWidth(_text[minOffset..offset+1]) < _width And offset < textLength)
						offset+=1
					Wend
				End If

				If (textLength - minOffset > range) Then
					offset+=1
					_textLines.Push(_text[minOffset..offset])
					minOffset = offset

					maxOffset = minOffset + range
					offset = maxOffset
				Else
					_textLines.Push(_text[minOffset..])
					Exit
				End If
			Forever

			_countLines = _textLines.Length()
		End If
	End Method

Public

End Class

Private
	Global _fontManager:FontManager<BitmapFont> = New FontManager<BitmapFont>()
	Global _defaultFont:BitmapFont

Strict

Import flixel.flxtext
Import flixel.flxtext.driver
Import flixel.flxtext.fontmanager

Import mojo
Import fontmachine.fontmachine

Import "../../data/flx_system_fm_font_8.txt"
Import "../../data/flx_system_fm_font_8_P_1.png"
Import "../../data/flx_system_fm_font_9.txt"
Import "../../data/flx_system_fm_font_9_P_1.png"
Import "../../data/flx_system_fm_font_10.txt"
Import "../../data/flx_system_fm_font_10_P_1.png"
Import "../../data/flx_system_fm_font_11.txt"
Import "../../data/flx_system_fm_font_11_P_1.png"
Import "../../data/flx_system_fm_font_12.txt"
Import "../../data/flx_system_fm_font_12_P_1.png"
Import "../../data/flx_system_fm_font_13.txt"
Import "../../data/flx_system_fm_font_13_P_1.png"
Import "../../data/flx_system_fm_font_14.txt"
Import "../../data/flx_system_fm_font_14_P_1.png"
Import "../../data/flx_system_fm_font_15.txt"
Import "../../data/flx_system_fm_font_15_P_1.png"
Import "../../data/flx_system_fm_font_16.txt"
Import "../../data/flx_system_fm_font_16_P_1.png"

Class FontMachineDriver Extends TextDriver

Private
	Field _width:Int
	Field _text:String
	Field _textLines:StringStack
	Field _multiline:Bool
	Field _countLines:Int
	Field _font:BitmapFont

	Field _fontName:String
	Field _fontHeight:Int = 0
	Field _size:Int = FlxText.MIN_SIZE
	Field _alignment:Float

Public
	Method New()
		_textLines = New StringStack();
	End Method

	Method SetFormat:Void(fontName:String, size:Int, alignment:Int)
		SetAlignment(alignment)
		_fontName = fontName
		_size = size
		_InitFont(fontName, size)
		If (_text.Length > 0) _BuildLines()
	End Method

	Method GetName:String()
		Return "fm"
	End Method

	Method SetWidth:Void(width:Int)
		_width = width
		If (_text.Length > 0) _BuildLines()
	End Method

	Method SetFontName:Void(fontName:String)
		_fontName = fontName
		_InitFont(fontName, _size)
		If (_text.Length > 0) _BuildLines()
	End Method

	Method GetFontName:String()
		Return _fontName
	End Method

	Method SetSize:Void(size:Int)
		_size = size
		_InitFont(_fontName, size)
		If (_text.Length > 0) _BuildLines()
	End Method

	Method GetSize:Int()
		Return _size
	End Method

	Method SetText:Void(text:String)
		_text = text
		If (_width <> 0) _BuildLines()
	End Method

	Method GetText:String()
		Return _text
	End Method

	Method SetAlignment:Void(alignment:Float)
		_alignment = alignment
	End Method

	Method GettAlignment:Float()
		Return _alignment
	End Method

	Method Draw:Void(x:Float, y:Float)
		If (Not _multiline) Then
			_font.DrawText(_text, x, y)
		Else
			For Local line:Int = 0 Until _countLines
				_font.DrawText(_textLines.Get(line), x, y + line*_fontHeight)
			Next
		End If
	End Method

	Method Destroy:Void()
	End Method

Private
	Method _InitFont:Void(fontName:String, size:Int)
		_font = _fontManager.GetFont(fontName, size)
		If (_font = Null) Then
			_font = New BitmapFont(Self.GetFileName(fontName) + size + ".txt", False)

			If (_font = Null And _defaultFont = Null) Then
				Error ("Font " + fontName +  " can't be loaded")
			ElseIf (_font = Null) Then
				_font = _defaultFont
				_fontHeight = _font.GetFontHeight()
				Return
			End If

			_fontManager.AddFont(fontName, size, _font)
			If (_defaultFont = Null) _defaultFont = _font
		End If

		_fontHeight = _font.GetFontHeight()
	End Method

	Method _BuildLines:Void()
		Local textWidth:Int = _font.GetTxtWidth(_text)

		If (_width < textWidth) Then
			_multiline = True
			_textLines.Clear()

			Local textLength:Int = _text.Length
			Local range:Int = Ceil(textLength/Float(Floor(textWidth/Float(_width))+1))+1
			Local maxOffset:Int = range
			Local minOffset:Int = 0
			Local offset:Int = maxOffset

			Repeat
				Repeat
					offset-=1
					While (_text[offset] <> KEY_SPACE And offset > minOffset)
						offset-=1
					Wend
					If (offset <= minOffset) Exit
				Until(_font.GetTxtWidth(_text[minOffset..offset]) <= _width)

				If (offset <= minOffset) Then
					While(_font.GetTxtWidth(_text[minOffset..offset+1]) < _width And offset < textLength)
						offset+=1
					Wend
				End If

				If (textLength - minOffset > range) Then
					offset+=1
					_textLines.Push(_text[minOffset..offset])
					minOffset = offset

					maxOffset = minOffset + range
					offset = maxOffset
				Else
					_textLines.Push(_text[minOffset..])
					Exit
				End If
			Forever

			_countLines = _textLines.Length()
			Return
		End If
		_multiline = False
		_countLines = 0
		_textLines.Clear()
	End Method

Public

End Class

Private
	Global _fontManager:FontManager<BitmapFont> = New FontManager<BitmapFont>()
	Global _defaultFont:BitmapFont