summaryrefslogtreecommitdiff
path: root/slippy2.py
blob: 32204ceaa954fd6e71bd17f922f7ffa7ba4be11a (plain)
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
import sys, pygame
pygame.init()
import subprocess, tempfile, os
import info
import random


SIZE = WIDTH, HEIGHT = 960, 640
BLACK = 0,0,0
WHITE = 255,255,255
size = 200
offset = [-50, -50]
origin = "P6704"

# Commandline interface: Final -... arg indicates initial center zone,
#	   Rest indicates a layer to display.
tilepaths = [arg for arg in sys.argv[1:] if arg[0] != "-"]
for arg in sys.argv[1:]:
	if arg[0] == "-": origin = arg[1:]


## Reformat CSV files for consistant rendering options
CACHE = tempfile.mkdtemp()
for i, tilepath in enumerate(tilepaths):
	if "?" in tilepath: continue # Don't reformat image layers

	with open(tilepath) as f:
		if "," not in f.readline(): continue # It's already an Indental file.

		# Reformat into an Indental file so we have consistant formatting between frames.
		path = os.path.join(CACHE, str(i) + ".indental")
		with open(path, "w") as out:
			for line in f:
				if "," not in line: continue # Invalid line...
				name, value = line.split(",") # Parse line

				# Choose rendering parameters
				print(name.strip(), file=out)
				print("\tlabel:", name.strip(), file=out)
				print("\tred:", random.random(), file=out)
				print("\tgreen:", random.random(), file=out)
				print("\tblue:", random.random(), file=out)
				print("\talpha: 0.5", file=out)

				# Output appropriate zoneIDs.
				for zone in value.strip().split():
					# normalize zone ID
					zone = zone.strip()
					if "#" in zone: zone = zone.split("#")[1]
					print("\t"+zone, file=out)
		tilepaths[i] = path

## Utils
def add2(a, b):
	return [a[0] + b[0], a[1] + b[1]]

image_cache = {}
def image_load(path):
	if path not in image_cache:
		image_cache[path] = pygame.image.load(path).convert_alpha()
	return image_cache[path]

## Navigation
INVERSE = "876543210"
CW = "630741852"
CCW = "258147036"

def rotate(cell, matrix):
	"""Corrects for the fold when navigating to/from the North/South face.

		Because when that happens, we're usually crossing an unusual edge
	for the direction we're heading."""
	if len(cell) <= 1 or matrix is None: return "".join(cell)
	else: return cell[0] + "".join(matrix[int(p)] for p in cell[1:])

# Compute adjacent zones, would be nice to figure out how to handle these more generically.
def up(cell):
	cell = list(cell)

	# Start from little end and go up as needed.
	for i, pos in reversed(list(enumerate(cell))):
		if i == 0:
			# It's navigating a root zone, may need to apply a rotation.
			cell[i] = {"N":"Q", "S":"R"}.get(pos, "N")
			return rotate(cell, {
				"N": INVERSE,
				"O": CCW, "Q": CW, "R": INVERSE
			}.get(pos, None))
		else:
			pos = int(pos) - 3
			# Crossed the parent zone boundary, correct and head up.
			if pos < 0: cell[i] = str(pos + 9)
			else:
				# Within same zone, we're done.
				cell[i] = str(pos)
				break

	return "".join(cell)
assert up("O5") == "O2"

def down(cell):
	cell = list(cell)
	for i, pos in reversed(list(enumerate(cell))):
		if i == 0:
			cell[i] = {"N": "P", "S": "O"}.get(pos, "N")
			return rotate(cell, {
				"S": INVERSE,
				"O": INVERSE, "P": CW, "R": CCW
			}.get(pos, None))
		else:
			pos = int(pos) + 3
			if pos > 8: cell[i] = str(pos - 9)
			else:
				cell[i] = str(pos)
				break
	return "".join(cell)
assert down("O5") == "O8"

def left(cell):
	cell = list(cell)
	for i, pos in reversed(list(enumerate(cell))):
		if i == 0:
			cell[i] = {"N": "O", "S": "P",
					"O": "R", "P": "O", "Q": "P", "R": "Q"}[pos]
			return rotate(cell, {"N":CW, "S":CCW}.get(pos, None))
		else:
			row, col = int(pos) // 3, int(pos) % 3
			if col == 0: cell[i] = str(row * 3 + 2)
			else:
				cell[i] = str(row * 3 + col - 1)
				break
	return "".join(cell)
assert left("O5") == "O4"

def right(cell):
	cell = list(cell)
	for i, pos in reversed(list(enumerate(cell))):
		if i == 0:
			cell[i] = {"N": "Q", "S": "R",
					"R": "O", "O": "P", "P": "Q", "Q": "R"}[pos]
			return rotate(cell, {"N": CCW, "S": CW}.get(pos, None))
		else:
			row, col = int(pos) // 3, int(pos) % 3
			if col == 2: cell[i] = str(row * 3)
			else:
				cell[i] = str(row * 3 + col + 1)
				break
	return "".join(cell)
assert right("O5") == "P3"

## Rendering
screen = pygame.display.set_mode(SIZE)
font = pygame.font.Font(pygame.font.get_default_font(), 10)
def render_cell(rect, zone):
    """Renders all layers within a particular zone, or labels it."""
    """
    hastile = False # Whether to fallback to showing text

    # Render multiple layers
    toptile = pygame.Surface((size,size))
    for tilepath in tilepaths:
        try:
            if "?" in tilepath:
                # Directory protocol, load correct tile image.
                tile = image_load(tilepath.replace("?", zone)).convert_alpha()
            else:
                # Geometry renderer is in render.c
                path = os.path.join(CACHE, zone)
                if not os.access(path, os.F_OK):
                    subprocess.check_call(["./dggs-render", zone, tilepath, path])
                tile = image_load(path).convert_alpha()
            tile = pygame.transform.scale(tile, (size, size))
            tile = tile.convert_alpha()
            toptile.blit(tile, (0,0))
        except:
            continue
        hastile = True
    screen.blit(toptile, rect.topleft)
    # label the zone if not otherwise rendered.
    if not hastile:
        tile = font.render(zone, True, BLACK, WHITE)
        screen.blit(tile, rect.topleft)
    pygame.draw.rect(screen, BLACK, rect, 1) # Display grid, might remove?
"""
	hastile = False # Whether to fallback to showing text

	# Render multiple layers
	temp = pygame.Surface((size, size), pygame.SRCALPHA)
	for tilepath in tilepaths:
		try:
			if "?" in tilepath:
				# Directory protocol, load correct tile image.
				tile = image_load(tilepath.replace("?", zone)).convert_alpha()
			else:
				# Geometry renderer is in render.c
				path = os.path.join(CACHE, str(i)+"-"+zone)
				if not os.access(path, os.F_OK):
					subprocess.check_call(["./dggs-render", zone, tilepath, path])
				tile = image_load(path)
			tile = pygame.transform.scale(tile, (size, size))
			temp.blit(tile, (0,0))
		except:
			continue
		hastile = True
	# label the zone if not otherwise rendered.
	if not hastile:
		tile = font.render(zone, True, BLACK, WHITE)
		screen.blit(tile, rect.topleft)
	else:
		screen.blit(temp, rect.topleft)
	pygame.draw.rect(screen, BLACK, rect, 1) # Display grid, might remove?

def render_row(rect, zone):
	"""Displays all zones in a single screen row."""
	render_cell(rect, zone)
	leftzone, rightzone = left(zone), right(zone)
	leftrect, rightrect = rect.move(-size, 0), rect.move(size, 0)
	while leftrect.right > 0:
		render_cell(leftrect, leftzone)
		leftzone = left(leftzone)
		leftrect = leftrect.move(-size, 0)
	while rightrect.left < WIDTH:
		render_cell(rightrect, rightzone)
		rightzone = right(rightzone)
		rightrect = rightrect.move(size, 0)

def render():
	"""Renders all zones onscreen, by row."""
	screen.fill(WHITE)

	rect = pygame.Rect(WIDTH/2,HEIGHT/2, size,size).move(offset)
	render_row(rect, origin)

	above, below = up(origin), down(origin)
	above_rect = rect.move(0, -size)
	while above_rect.bottom > 0:
		render_row(above_rect, above)
		above = up(above)
		above_rect = above_rect.move(0, -size)

	below_rect = rect.move(0, size)
	while below_rect.top < HEIGHT:
		render_row(below_rect, below)
		below = down(below)
		below_rect = below_rect.move(0, size)

	pygame.display.flip()
render()

def hittest(x,y):
	"""Determines which rendered zone has been clicked."""
	rect = pygame.Rect(WIDTH/2,HEIGHT/2, size,size).move(offset)
	zone = origin
	while y < rect.bottom:
		zone = up(zone)
		rect = rect.move(0, -size)
	while y > rect.bottom:
		zone = down(zone)
		rect = rect.move(0, size)
	while x < rect.left:
		zone = left(zone)
		rect = rect.move(-size, 0)
	while x > rect.right:
		zone = right(zone)
		rect = rect.move(size, 0)
	return zone, rect

# Main
dragging = False
dragged = False
geoms = None
while True:
"""
    changed = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        # Drag pans the display, click prints info about the zone under the cursor.
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            dragging, dragged = True, False
        elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            if not dragged:
                # Handle click case
                if geoms is None:
                    geoms = []
                    # Load geometry lazily.
                    for arg in sys.argv[1:]:
                        if not arg or arg[0] == "-" or "?" in arg: continue
                        data = info.parse_indental(arg)
                        geom = {}
                        for item in data.values(): geom = dict(geom, **item)
                        geoms.append(geom)

                base, rect = hittest(*event.pos)
                x, y = event.pos[0] - rect.left, event.pos[1] - rect.top
                zone = False
                for geom in reversed(geoms):
                    zone, data = info.zone4point(geom, base, x, y, rect.width, rect.height)
                    if zone:
                        print (zone, data)
                        break
                if not zone: print (base)
            dragging = False
        # Handle pan, by adjusting offset & origin globals.
        elif dragging and event.type == pygame.MOUSEMOTION:
            offset = add2(offset, event.rel)
            dragged = changed = True

            # Make sure to correct configured center zone when it changes.
            if offset[0] < 0:
                offset[0] += size
                origin = right(origin)
            if offset[0] > size:
                offset[0] -= size
                origin = left(origin)
            if offset[1] < 0:
                offset[1] += size
                origin = down(origin)
            if offset[1] > size:
                offset[1] -= size
                origin = up(origin)
        # Scroll wheel API is a bit weird.
        # Scroll to zoom in or out, by adjusting size & origin globals.
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 5:
            size += 15
            if size*2 > WIDTH or size*2 > HEIGHT:
                size = size // 3
                origin += "4"
            changed = True
        elif event.type == pygame.MOUSEBUTTONUP and event.button == 4:
            size -= 15
            if size*9 < WIDTH or size*9 < HEIGHT:
                if len(origin) == 2: size += 1
                else:
                    size *= 3
                    origin = origin[:-1]
            changed = True

    if changed: render() # Only rerender when necessary.
    pygame.time.wait(10) # Reduce CPU usage.
"""
	changed = False
	for event in pygame.event.get():
		if event.type == pygame.QUIT: sys.exit()
		# Drag pans the display, click prints info about the zone under the cursor.
		elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
			dragging, dragged = True, False
		elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
			if not dragged:
				# Handle click case
				if geoms is None:
					geoms = []
					# Load geometry lazily.
					for arg in sys.argv[1:]:
						if not arg or arg[0] == "-" or "?" in arg: continue
						data = info.parse_indental(arg)
						geom = {}
						for item in data.values(): geom = dict(geom, **item)
						geoms.append(geom)

				base, rect = hittest(*event.pos)
				x, y = event.pos[0] - rect.left, event.pos[1] - rect.top
				zone = False
				for geom in reversed(geoms):
					zone, data = info.zone4point(geom, base, x, y, rect.width, rect.height)
					if zone:
						print (zone, data)
						break
				if not zone: print (base)
			dragging = False
		# Handle pan, by adjusting offset & origin globals.
		elif dragging and event.type == pygame.MOUSEMOTION:
			offset = add2(offset, event.rel)
			dragged = changed = True

			# Make sure to correct configured center zone when it changes.
			if offset[0] < 0:
				offset[0] += size
				origin = right(origin)
			if offset[0] > size:
				offset[0] -= size
				origin = left(origin)
			if offset[1] < 0:
				offset[1] += size
				origin = down(origin)
			if offset[1] > size:
				offset[1] -= size
				origin = up(origin)
		# Scroll wheel API is a bit weird.
		# Scroll to zoom in or out, by adjusting size & origin globals.
		elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 5:
			size += 15
			if size*2 > WIDTH or size*2 > HEIGHT:
				size = size // 3
				origin += "4"
			changed = True
		elif event.type == pygame.MOUSEBUTTONUP and event.button == 4:
			size -= 15
			if size*9 < WIDTH or size*9 < HEIGHT:
				if len(origin) == 2: size += 1
				else:
					size *= 3
					origin = origin[:-1]
			changed = True

	if changed: render() # Only rerender when necessary.
	pygame.time.wait(100) # Reduce CPU usage.