summaryrefslogtreecommitdiff
path: root/pydggin.py
blob: 581bcab7abaa0b3fc8637124814ada959d8f69fd (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
#! /usr/bin/python3
"""Interactive slippy map for viewing DGGS data."""
import pyglet
import sys, random, tempfile
import os, subprocess
from collections import namedtuple
from pyglet.gl import *

# 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] != "-"]

origin = "P6704"
for arg in sys.argv[1:]:
	if arg[0] == "-": origin = arg[1:]

window = pyglet.window.Window(width=800, height=600,
		caption = tilepaths[0] if len(tilepaths) else "RHealPix Grid",
		resizable=True)

## Utilities
image_cache = {}
no_loaded_this_frame = 0
MAX_LOADED_THIS_FRAME = 6
def load_image(filepath):
	global no_loaded_this_frame
	if filepath not in image_cache and no_loaded_this_frame < MAX_LOADED_THIS_FRAME:
		image_cache[filepath] = pyglet.image.load(filepath)
		no_loaded_this_frame += 1
	return image_cache.get(filepath)

## 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(".", 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

## Geometric Maths
class Point(namedtuple("Point", "x y")):
	def __add__(self, other):
		return Point(self.x + other.x, self.y + other.y)

	def __sub__(self, other):
		return Point(self.x - other.x, self.y - other.y)
Pt = Point

class Rect(namedtuple("Rect", "x y width height")):
	def __add__(self, other):
		return Rect(self.x + other.x, self.y + other.y, self.width, self.height)

	def __sub__(self, other):
		return Rect(self.x - other.x, self.y - other.y, self.width, self.height)

	def centred(self):
		return self - Pt(self.width/2, self.height/2)

	@property
	def right(self): return self.x + self.width
	@property
	def left(self): return self.x
	@property
	def top(self): return self.y
	@property
	def bottom(self): return self.y + self.height
R = Rect

## 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
size = 200
offset = Pt(0,0)

active_renders = {}
def render_cell(rect, zone):
	hastile = False

	for i, tilepath in enumerate(tilepaths):
		try:
			img = None
			if "?" in tilepath:
				img = load_image(tilepath.replace("?", zone))
			else:
				# Geometry renderer is in render.c
				path = os.path.join(CACHE, str(i) +"-"+zone)
				if not os.access(path, os.F_OK) and path not in active_renders:
					active_renders[path] = subprocess.Popen(["./dggs-render", zone, tilepath, path])
					continue
				elif path in active_renders:
					if active_renders[path].poll() is None: continue
					else: del active_renders[path]
				img = load_image(path)
			# Scale & efficiently composite using Pyglet's Sprite/Batch system
			if img is None: continue
			sprite = pyglet.sprite.Sprite(img, x = rect.x, y = rect.y)
			sprite.update(scale_x = size/img.width, scale_y = size/img.height)
			sprite.draw()
		except: continue
		hastile = True
		# print (zone, groups[i], tilepath)
	if not hastile:
		pyglet.text.Label(zone, font_size=10, x = rect.x, y = rect.y).draw()

def render_row(rect, zone):
	render_cell(rect, zone)

	leftzone, rightzone = left(zone), right(zone)
	leftrect, rightrect = rect - Pt(size, 0), rect + Pt(size, 0)
	while leftrect.right > 0:
		render_cell(leftrect, leftzone)
		leftrect -= Pt(size, 0)
		leftzone = left(leftzone)
	while rightrect.left < window.width:
		render_cell(rightrect, rightzone)
		rightrect += Pt(size, 0)
		rightzone = right(rightzone)

@window.event
def on_draw(dt=None):
	global no_loaded_this_frame
	no_loaded_this_frame = 0
	window.clear()

	rect = Rect(window.width/2, window.height/2, size, size).centred() + offset
	render_row(rect, origin)

	above, below = up(origin), down(origin)
	above_rect, below_rect = rect + Pt(0, size), rect - Pt(0, size)
	while above_rect.top < window.height:
		render_row(above_rect, above)
		above_rect += Pt(0, size)
		above = up(above)

	while below_rect.bottom > 0:
		render_row(below_rect, below)
		below_rect -= Pt(0, size)
		below = down(below)

	if no_loaded_this_frame >= MAX_LOADED_THIS_FRAME or active_renders:
		# Trigger redraw to load images whilst keeping good performance
		pyglet.clock.schedule_once(on_draw, 0.01)

## Interactivity
dragging = False
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
	global offset, origin, dragging
	offset += Pt(dx, dy)
	if offset.x < 0:
		offset += Pt(size, 0)
		origin = right(origin)
	elif offset.x > size:
		offset -= Pt(size, 0)
		origin = left(origin)
	if offset.y < 0:
		offset += Pt(0, size)
		origin = up(origin)
	elif offset.y > size:
		offset -= Pt(0, size)
		origin = down(origin)

	dragging = True

@window.event
def on_mouse_scroll(x, y, scroll_x, scroll_y):
	global size, origin
	size -= scroll_y*5
	if size*2 > window.width or size*2 > window.height:
		size = size // 3
		origin += "4"
	if size*9 < window.width or size*9 < window.height:
		if len(origin) == 2: size += 5
		else:
			size *= 3
			origin = origin[:-1]

### Retrieve layer info
geoms = None
@window.event
def on_mouse_release(x, y, buttons, mods):
	import info
	global geoms, dragging

	# Discard drag gestures
	if dragging:
		dragging = False
		return

	# Find correct base zone
	rect = Rect(window.width/2,window.height/2, size,size).centred() + offset
	zone = origin
	while y < rect.bottom:
		zone = down(zone)
		rect += Pt(0, -size)
	while y > rect.bottom:
		zone = up(zone)
		rect += Pt(0, size)
	while x < rect.left:
		zone = left(zone)
		rect += Pt(-size, 0)
	while x > rect.right:
		zone = right(zone)
		rect += Pt(size, 0)

	# Lazily initialize geometry tables
	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)

	# Apply hittesting & output results
	x -= rect.left
	y = size - (y - rect.top) # Pyglet has y increasing upwords, whereas info.py expects it to increase downwards.
	child = False
	for geom in reversed(geoms):
		child, data = info.zone4point(geom, zone, x, y, size, size)
		if child:
			print(child, data)
			break
	if not child: print(zone)

pyglet.app.run()