/zoeplat

To get this branch, use:
bzr branch http://9ix.org/bzr/zoeplat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
-- Class: Map
-- A map saves memory and CPU time by acting as if it were a grid of sprites.
-- Each different type of sprite in the grid is represented via a single
-- object. Each sprite must have the same size, however.
-- 
-- This works very similarly to a tilemap, but there is additional flexibility
-- in using a sprite, e.g. animation and other display effects. (If you want it
-- to act like a tilemap, use its loadTiles method.) However, changing a sprite's
-- x or y position has no effect. Changing the scale will have weird effects as
-- a map expects every sprite to be the same size.
--
-- Extends:
--		<Sprite>

Map = Sprite:extend
{
	-- Constant: NO_SPRITE
	-- Represents a map entry with no sprite.
	NO_SPRITE = -1,

	-- Property: sprites
	-- An ordered table of <Sprite> objects to be used in conjunction with the map property.
	sprites = {},

	-- Property: map
	-- A two-dimensional table of values, each corresponding to an entry in the sprites property.
	-- nb. The tile at (0, 0) visually is stored in [1, 1].
	map = {},

	-- Method: empty
	-- Creates an empty map.
	--
	-- Arguments:
	--		width - width of the map in sprites
	--		height - height of the map in sprites
	-- 
	-- Returns:
	--		self, for chaining

	empty = function (self, width, height)
		local x, y
		
		-- empty the map

		for x = 1, width do
			self.map[x] = {}
			
			for y = 1, height do
				self.map[x][y] = Map.NO_SPRITE
			end
		end
		
		-- set bounds
		
		self.width = width * self.spriteWidth
		self.height = height * self.spriteHeight
		
		return self
	end,

	-- Method: loadMap
	-- Loads map data from a file, typically comma-separated values.
	-- Each entry corresponds to an index in self.sprites, and all rows
	-- must have the same number of columns.
	--
	-- Arguments:
	--		file - filename of source text to use
	--		colSeparator - character to use as separator of columns, default ','
	--		rowSeparator - character to use as separator of rows, default newline
	--
	-- Returns:
	--		self, for chaining

	loadMap = function (self, file, colSeparator, rowSeparator)
		colSeparator = colSeparator or ','
		rowSeparator = rowSeparator or '\n'
		
		-- load data
		
		local x, y
		local source = Cached:text(file)
		local rows = split(source, rowSeparator)
		
		for y = 1, #rows do
			local cols = split(rows[y], colSeparator)
			
			for x = 1, #cols do
				if not self.map[x] then self.map[x] = {} end
				self.map[x][y] = tonumber(cols[x])
			end
		end
		
		-- set bounds
		
		self.width = #self.map[1] * self.spriteWidth
		self.height = #self.map * self.spriteHeight
		
		return self
	end,

	-- Method: loadTiles
	--- Loads the sprites group with slices of a source image.
	--  By default, this uses the Tile class for sprites, but you
	--  may pass as replacement class.
	--
	--  Arguments:
	--		image - source image to use for tiles
	--		class - class to create objects with; constructor
	--				  will be called with properties: image, width,
	--				  height, imageOffset (with x and y sub-properties)
	--		startIndex - starting index of tiles in self.sprites, default 0
	--
	--  Returns:
	--		self, for chaining

	loadTiles = function (self, image, class, startIndex)
		assert(self.spriteWidth and self.spriteHeight, 'sprite size must be set before loading tiles')
		if type(startIndex) ~= 'number' then startIndex = 0 end
		
		class = class or Tile
		self.sprites = self.sprites or {}
		
		local imageObj = Cached:image(image)
		local imageWidth = imageObj:getWidth()
		local imageHeight = imageObj:getHeight()
		 
		local i = startIndex
		
		for y = 0, imageHeight - self.spriteHeight, self.spriteHeight do
			for x = 0, imageWidth - self.spriteWidth, self.spriteWidth do
				self.sprites[i] = class:new{ image = image, width = self.spriteWidth,
											  height = self.spriteHeight,
											  imageOffset = { x = x, y = y }}
				i = i + 1
			end
		end
		
		return self
	end,

	-- Method: subcollide
	-- This acts as a wrapper to multiple collide() calls, as if
	-- there really were all the sprites in their particular positions.
	-- This is much more useful than Map:collide(), which simply checks
	-- if a sprite or group is touching the map at all. 
	--
	-- Arguments:
	--		other - other <Sprite> or <Group>
	--
	-- Returns:
	--		boolean, whether any collision was detected

	subcollide = function (self, other)
		local hit = false
		local others

		if other.sprites then
			others = other.sprites
		else
			others = { other }
		end

		for _, othSpr in pairs(others) do
			if othSpr.solid then
				if othSpr.sprites then
					-- recurse into subgroups
					-- order is important here to avoid short-circuiting inappopriately
				
					hit = self:subcollide(othSpr.sprites) or hit
				else
					local startX, startY = self:pixelToMap(othSpr.x - self.x, othSpr.y - self.y)
					local endX, endY = self:pixelToMap(othSpr.x + othSpr.width - self.x,
													   othSpr.y + othSpr.height - self.y)
					local x, y
					
					for x = startX, endX do
						for y = startY, endY do
							local spr = self.sprites[self.map[x][y]]
							
							if spr and spr.solid then
								-- position our map sprite as if it were onscreen
								
								spr.x = self.x + (x - 1) * self.spriteWidth
								spr.y = self.y + (y - 1) * self.spriteHeight
								
								hit = spr:collide(othSpr) or hit
							end
						end
					end
				end
			end
		end

		return hit
	end,

	-- Method: subdisplace
	-- This acts as a wrapper to multiple displace() calls, as if
	-- there really were all the sprites in their particular positions.
	-- This is much more useful than Map:displace(), which pushes a sprite or group
	-- so that it does not touch the map in its entirety. 
	--
	-- Arguments:
	--		other - other <Sprite> or <Group> to displace
	--		xHint - force horizontal displacement in one direction, uses direction constants
	--		yHint - force vertical displacement in one direction, uses direction constants
	--
	-- Returns:
	--		nothing

	subdisplace = function (self, other, xHint, yHint)	
		local others

		if other.sprites then
			others = other.sprites
		else
			others = { other }
		end

		for _, othSpr in pairs(others) do
			if othSpr.solid then
				if othSpr.sprites then
					-- recurse into subgroups
					-- order is important here to avoid short-circuiting inappopriately
				
					self:subdisplace(othSpr.sprites)
				else
					-- determine sprites we might intersect with

					local startX, startY = self:pixelToMap(othSpr.x - self.x, othSpr.y - self.y)
					local endX, endY = self:pixelToMap(othSpr.x + othSpr.width - self.x,
													   othSpr.y + othSpr.height - self.y)
					local hit = true
					local loops = 0

					-- We displace the target sprite along the axis that would satisfy the
					-- most map sprites, but at the minimum distance for all of them.
					-- xVotes and yVotes track which axis should be used; this is a
					-- proportional vote, with sprites that have large amounts of overlap
					-- getting more of a chance to overrule the others. We run this loop
					-- repeatedly to make sure we end up with the target sprite not overlapping
					-- anything in the map.
					--
					-- This is based on the technique described at:
					-- http://go.colorize.net/xna/2d_collision_response_xna/

					while hit and loops < 3 do
						hit = false
						loops = loops + 1

						local xVotes, yVotes = 0, 0
						local minChangeX, minChangeY, absMinChangeX, absMinChangeY
						local origX, origY = othSpr.x, othSpr.y

						for x = startX, endX do
							for y = startY, endY do
								local spr = self.sprites[self.map[x][y]]
								
								if spr and spr.solid then
									-- position our map sprite as if it were onscreen
									
									spr.x = self.x + (x - 1) * self.spriteWidth
									spr.y = self.y + (y - 1) * self.spriteHeight
					
									-- displace and check to see if this displacement
									-- would result in a smaller shift than any so far

									spr:displace(othSpr)
									local xChange = othSpr.x - origX
									local yChange = othSpr.y - origY

									if xChange ~= 0 then
										xVotes = xVotes + math.abs(xChange)
										hit = true

										if not minChangeX or math.abs(xChange) < absMinChangeX then
											minChangeX = xChange
											absMinChangeX = math.abs(xChange)
										end
									end

									if yChange ~= 0 then
										yVotes = yVotes + math.abs(yChange)
										hit = true

										if not minChangeY or math.abs(yChange) < absMinChangeY then
											minChangeY = yChange
											absMinChangeY = math.abs(yChange)
										end
									end

									-- restore sprite to original position

									othSpr.x = origX
									othSpr.y = origY
								end
							end
						end

						if hit then
							if xVotes > 0 and xVotes > yVotes then
								othSpr.x = othSpr.x + minChangeX
							elseif yVotes > 0 then
								othSpr.y = othSpr.y + minChangeY
							end
						end
					end
				end
			end
		end
	end,

	-- Method: getMapSize
	-- Returns the size of the map in sprites.
	--
	-- Arguments:
	--		none
	--
	-- Returns:
	--		width and height in integers

	getMapSize = function (self)
		if #self.map == 0 then
			return 0, 0
		else
			return #self.map, #self.map[1]
		end
	end,

	draw = function (self, x, y)
		-- lock our x/y coordinates to integers
		-- to avoid gaps in the tiles
	
		x = math.floor(x or self.x)
		y = math.floor(y or self.y)
		if not self.visible or self.alpha <= 0 then return end
		if not self.spriteWidth or not self.spriteHeight then return end
		
		-- determine drawing bounds
		-- we draw to fill the entire app windoow
		
		local startX, startY = self:pixelToMap(-x, -y)
		local endX, endY = self:pixelToMap(the.app.width - x, the.app.height - y)
		
		-- queue each sprite drawing operation
		
		local toDraw = {}
		
		for drawY = startY, endY do
			for drawX = startX, endX do
				local sprite = self.sprites[self.map[drawX][drawY]]
				
				if sprite and sprite.visible then
					if not toDraw[sprite] then
						toDraw[sprite] = {}
					end
					
					table.insert(toDraw[sprite], { x + (drawX - 1) * self.spriteWidth,
												   y + (drawY - 1) * self.spriteHeight })
				end
			end
		end
		
		-- draw each sprite in turn
		
		for sprite, list in pairs(toDraw) do
			for _, coords in pairs(list) do
				sprite:draw(coords[1], coords[2])
			end
		end
		
		Sprite.draw(self)
	end,

	-- Method: pixelToMap
	-- Converts pixels to map coordinates.
	--
	-- Arguments:
	--		x - x coordinate in pixels
	--		y - y coordinate in pixels
	--		clamp - clamp to map bounds? defaults to true
	--
	-- Returns:
	--		x, y map coordinates

	pixelToMap = function (self, x, y, clamp)
		if type(clamp) == 'nil' then clamp = true end

		-- remember, Lua tables start at index 1

		local mapX = math.floor(x / self.spriteWidth) + 1
		local mapY = math.floor(y / self.spriteHeight) + 1
		
		-- clamp to map bounds
		
		if clamp then
			if mapX < 1 then mapX = 1 end
			if mapY < 1 then mapY = 1 end
			if mapX > #self.map then mapX = #self.map end
			if mapY > #self.map[1] then mapY = #self.map[1] end
		end

		return mapX, mapY
	end,

	-- makes sure all sprites receive startFrame messages

	startFrame = function (self, elapsed)
		for _, spr in pairs(self.sprites) do
			spr:startFrame(elapsed)
		end

		Sprite.startFrame(self, elapsed)
	end,

	-- makes sure all sprites receive update messages

	update = function (self, elapsed)
		for _, spr in pairs(self.sprites) do
			spr:update(elapsed)
		end

		Sprite.update(self, elapsed)
	end,

	-- makes sure all sprites receive endFrame messages

	endFrame = function (self, elapsed)
		for _, spr in pairs(self.sprites) do
			spr:endFrame(elapsed)
		end

		Sprite.endFrame(self, elapsed)
	end,

	__tostring = function (self)
		local result = 'Map (x: ' .. self.x .. ', y: ' .. self.y ..
					   ', w: ' .. self.width .. ', h: ' .. self.height .. ', '

		if self.active then
			result = result .. 'active, '
		else
			result = result .. 'inactive, '
		end

		if self.visible then
			result = result .. 'visible, '
		else
			result = result .. 'invisible, '
		end

		if self.solid then
			result = result .. 'solid'
		else
			result = result .. 'not solid'
		end

		return result .. ')'
	end
}