home · contact · privacy
e3c071f85251ae9e947183a474fe69d78294e2bf
[plomrogue2] / plomrogue / mapping.py
1 import collections
2 from plomrogue.errors import ArgError
3
4
5
6 class YX(collections.namedtuple('YX', ('y', 'x'))):
7
8     def __add__(self, other):
9         return YX(self.y + other.y, self.x + other.x)
10
11     def __sub__(self, other):
12         return YX(self.y - other.y, self.x - other.x)
13
14     def __str__(self):
15         return 'Y:%s,X:%s' % (self.y, self.x)
16
17
18
19 class MapGeometry():
20
21     def __init__(self, size):
22         self.size = size
23         self.neighbors_i = {}
24         self.directions = self.get_directions()
25
26     def get_directions(self):
27         directions = []
28         prefix = 'move__'
29         for name in dir(self):
30             if name[:len(prefix)] == prefix:
31                 directions += [name[len(prefix):]]
32         return directions
33
34     def get_neighbors_yxyx(self, yxyx):
35         neighbors = {}
36         for direction in self.directions:
37             neighbors[direction] = self.move_yxyx(yxyx, direction)
38         return neighbors
39
40     def get_neighbors_yx(self, pos):
41         neighbors = {}
42         for direction in self.directions:
43             neighbors[direction] = self.move_yx(pos, direction)
44         return neighbors
45
46     def get_neighbors_i(self, i):
47         if i in self.neighbors_i:
48             return self.neighbors_i[i]
49         pos = YX(i // self.size.x, i % self.size.x)
50         neighbors_pos = self.get_neighbors_yx(pos)
51         neighbors_i = {}
52         for direction in neighbors_pos:
53             pos = neighbors_pos[direction]
54             if pos is None:
55                 neighbors_i[direction] = None
56             else:
57                 neighbors_i[direction] = pos.y * self.size.x + pos.x
58         self.neighbors_i[i] = neighbors_i
59         return self.neighbors_i[i]
60
61     def move_yx(self, start_yx, direction, check=True):
62         mover = getattr(self, 'move__' + direction)
63         target = mover(start_yx)
64         # TODO refactor with SourcedMap.inside?
65         if target.y < 0 or target.x < 0 or \
66            target.y >= self.size.y or target.x >= self.size.x:
67             return None
68         return target
69
70     def move_yxyx(self, start_yxyx, direction):
71         mover = getattr(self, 'move__' + direction)
72         start_yx = self.undouble_yxyx(*start_yxyx)
73         target_yx = mover(start_yx)
74         return self.double_yx(target_yx)
75
76     def double_yx(self, absolute_yx):
77         big_y = absolute_yx.y // self.size.y
78         little_y = absolute_yx.y % self.size.y
79         big_x = absolute_yx.x // self.size.x
80         little_x = absolute_yx.x % self.size.x
81         return YX(big_y, big_x), YX(little_y, little_x)
82
83     def undouble_yxyx(self, big_yx, little_yx):
84         y = big_yx.y * self.size.y + little_yx.y
85         x = big_yx.x * self.size.x + little_yx.x
86         return YX(y, x)
87
88
89
90 class MapGeometryWithLeftRightMoves(MapGeometry):
91
92     def move__LEFT(self, start_pos):
93         return YX(start_pos.y, start_pos.x - 1)
94
95     def move__RIGHT(self, start_pos):
96         return YX(start_pos.y, start_pos.x + 1)
97
98
99
100 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
101
102     def __init__(self, *args, **kwargs):
103         super().__init__(*args, **kwargs)
104         self.fov_map_class = FovMapSquare
105
106     def define_segment(self, source_center, radius):
107         source_center = self.undouble_yxyx(*source_center)
108         size = YX(2 * radius + 1, 2 * radius + 1)
109         offset = YX(source_center.y - radius, source_center.x - radius)
110         center = YX(radius, radius)
111         return size, offset, center
112
113     def move__UP(self, start_pos):
114         return YX(start_pos.y - 1, start_pos.x)
115
116     def move__DOWN(self, start_pos):
117         return YX(start_pos.y + 1, start_pos.x)
118
119
120 class MapGeometryHex(MapGeometryWithLeftRightMoves):
121
122     def __init__(self, *args, **kwargs):
123         super().__init__(*args, **kwargs)
124         self.fov_map_class = FovMapHex
125
126     def define_segment(self, source_center, radius):
127         source_center = self.undouble_yxyx(*source_center)
128         indent = 1 if (source_center.y % 2) else 0
129         size = YX(2 * radius + 1 + indent, 2 * radius + 1)
130         offset = YX(source_center.y - radius - indent, source_center.x - radius)
131         center = YX(radius + indent, radius)
132         return size, offset, center
133
134     def move__UPLEFT(self, start_pos):
135         start_indented = start_pos.y % 2
136         if start_indented:
137             return YX(start_pos.y - 1, start_pos.x)
138         else:
139             return YX(start_pos.y - 1, start_pos.x - 1)
140
141     def move__UPRIGHT(self, start_pos):
142         start_indented = start_pos.y % 2
143         if start_indented:
144             return YX(start_pos.y - 1, start_pos.x + 1)
145         else:
146             return YX(start_pos.y - 1, start_pos.x)
147
148     def move__DOWNLEFT(self, start_pos):
149         start_indented = start_pos.y % 2
150         if start_indented:
151             return YX(start_pos.y + 1, start_pos.x)
152         else:
153             return YX(start_pos.y + 1, start_pos.x - 1)
154
155     def move__DOWNRIGHT(self, start_pos):
156         start_indented = start_pos.y % 2
157         if start_indented:
158             return YX(start_pos.y + 1, start_pos.x + 1)
159         else:
160             return YX(start_pos.y + 1, start_pos.x)
161
162
163
164 class Map():
165
166     def __init__(self, map_geometry):
167         self.geometry = map_geometry
168         self.terrain = '.' * self.size_i  # TODO: use Game.get_flatland()?
169
170     def __getitem__(self, yx):
171         return self.terrain[self.get_position_index(yx)]
172
173     def __setitem__(self, yx, c):
174         pos_i = self.get_position_index(yx)
175         if type(c) == str:
176             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
177         else:
178             self.terrain[pos_i] = c
179
180     def __iter__(self):
181         """Iterate over YX position coordinates."""
182         for y in range(self.geometry.size.y):
183             for x in range(self.geometry.size.x):
184                 yield YX(y, x)
185
186     @property
187     def size_i(self):
188         return self.geometry.size.y * self.geometry.size.x
189
190     def set_line(self, y, line):
191         height_map = self.geometry.size.y
192         width_map = self.geometry.size.x
193         if y >= height_map:
194             raise ArgError('too large row number %s' % y)
195         width_line = len(line)
196         if width_line != width_map:
197             raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
198         self.terrain = self.terrain[:y * width_map] + line +\
199             self.terrain[(y + 1) * width_map:]
200
201     def get_position_index(self, yx):
202         return yx.y * self.geometry.size.x + yx.x
203
204     def lines(self):
205         width = self.geometry.size.x
206         for y in range(self.geometry.size.y):
207             yield (y, self.terrain[y * width:(y + 1) * width])
208
209
210
211 class SourcedMap(Map):
212
213     def __init__(self, block_chars, things, source_maps, source_center, radius,
214                  get_map):
215         self.block_chars = block_chars
216         self.radius = radius
217         example_map = get_map(YX(0, 0))
218         self.source_geometry = example_map.geometry
219         size, self.offset, self.center = \
220             self.source_geometry.define_segment(source_center, radius)
221         self.geometry = self.source_geometry.__class__(size)
222         for yx in self:
223             big_yx, _ = self.source_yxyx(yx)
224             get_map(big_yx)
225         self.source_map_segment = ''
226         obstacles = {}
227         for yxyx in [t.position for t in things if t.blocking]:
228             if yxyx == source_center:
229                 continue
230             if yxyx[0] not in obstacles:
231                 obstacles[yxyx[0]] = []
232             obstacles[yxyx[0]] += [yxyx[1]]
233         for yx in self:  # TODO: iter and source_yxyx expensive, cache earlier?
234             big_yx, little_yx = self.source_yxyx(yx)
235             if big_yx in obstacles and little_yx in obstacles[big_yx]:
236                 self.source_map_segment += self.block_chars[0]
237             else:
238                 self.source_map_segment += source_maps[big_yx][little_yx]
239
240     def source_yxyx(self, yx):
241         absolute_yx = yx + self.offset
242         big_yx, little_yx = self.source_geometry.double_yx(absolute_yx)
243         return big_yx, little_yx
244
245     def target_yx(self, big_yx, little_yx, check=False):
246         target_yx = self.source_geometry.undouble_yxyx(big_yx, little_yx) - self.offset
247         if check and not self.inside(target_yx):
248             return False
249         return target_yx
250
251     def inside(self, yx):
252         if yx.y < 0 or yx.x < 0 or \
253            yx.y >= self.geometry.size.y or yx.x >= self.geometry.size.x:
254             return False
255         return True
256
257
258
259 class DijkstraMap(SourcedMap):
260
261     def __init__(self, *args, **kwargs):
262         # TODO: check potential optimizations:
263         # - do a first pass circling out from the center
264         # - somehow ignore tiles that have the lowest possible value (we can
265         #   compare with a precalculated map for given starting position)
266         # - check if Python offers more efficient data structures to use here
267         # - shorten radius to nearest possible target
268         super().__init__(*args, **kwargs)
269         self.terrain = [255] * self.size_i
270         self[self.center] = 0
271         shrunk = True
272         while shrunk:
273             shrunk = False
274             for i in range(self.size_i):
275                 if self.source_map_segment[i] in self.block_chars:
276                     continue
277                 neighbors = self.geometry.get_neighbors_i(i)
278                 for direction in [d for d in neighbors if neighbors[d]]:
279                     j = neighbors[direction]
280                     if self.terrain[j] < self.terrain[i] - 1:
281                         self.terrain[i] = self.terrain[j] + 1
282                         shrunk = True
283         # print('DEBUG Dijkstra')
284         # line_to_print = []
285         # x = 0
286         # for n in self.terrain:
287         #     line_to_print += ['%3s' % n]
288         #     x += 1
289         #     if x >= self.geometry.size.x:
290         #         x = 0
291         #         print(' '.join(line_to_print))
292         #         line_to_print = []
293
294
295
296 class FovMap(SourcedMap):
297     # TODO: player visibility asymmetrical (A can see B when B can't see A):
298     # does this make sense, or not?
299
300     def __init__(self, *args, **kwargs):
301         super().__init__(*args, **kwargs)
302         self.terrain = '?' * self.size_i
303         self[self.center] = '.'
304         self.shadow_cones = []
305         #self.circle_out(self.center, self.shadow_process)
306
307     def init_terrain(self):
308         # we outsource this to allow multiprocessing some stab at it,
309         # and return it since multiprocessing does not modify its
310         # processing sources
311         self.circle_out(self.center, self.shadow_process)
312         return self
313
314     def throws_shadow(self, yx):
315         return self.source_map_segment[self.get_position_index(yx)]\
316             in self.block_chars
317
318     def shadow_process(self, yx, distance_to_center, dir_i, dir_progress):
319         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
320         # skip all.
321         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
322
323         def correct_arm(arm):
324             if arm > CIRCLE:
325                 arm -= CIRCLE
326             return arm
327
328         def in_shadow_cone(new_cone):
329             for old_cone in self.shadow_cones:
330                 if old_cone[0] <= new_cone[0] and \
331                    new_cone[1] <= old_cone[1]:
332                     return True
333                 # We might want to also shade tiles whose middle arm is inside a
334                 # shadow cone for a darker FOV. Note that we then could not for
335                 # optimization purposes rely anymore on the assumption that a
336                 # shaded tile cannot add growth to existing shadow cones.
337             return False
338
339         def merge_cone(new_cone):
340             import math
341             for old_cone in self.shadow_cones:
342                 if new_cone[0] < old_cone[0] and \
343                     (new_cone[1] > old_cone[0] or
344                      math.isclose(new_cone[1], old_cone[0])):
345                     old_cone[0] = new_cone[0]
346                     return True
347                 if new_cone[1] > old_cone[1] and \
348                     (new_cone[0] < old_cone[1] or
349                      math.isclose(new_cone[0], old_cone[1])):
350                     old_cone[1] = new_cone[1]
351                     return True
352             return False
353
354         def eval_cone(cone):
355             if in_shadow_cone(cone):
356                 return
357             self[yx] = '.'
358             if self.throws_shadow(yx):
359                 unmerged = True
360                 while merge_cone(cone):
361                     unmerged = False
362                 if unmerged:
363                     self.shadow_cones += [cone]
364
365         step_size = (CIRCLE / len(self.circle_out_directions)) / distance_to_center
366         number_steps = dir_i * distance_to_center + dir_progress
367         left_arm = correct_arm(step_size / 2 + step_size * number_steps)
368         right_arm = correct_arm(left_arm + step_size)
369
370         # Optimization potential: left cone could be derived from previous
371         # right cone. Better even: Precalculate all cones.
372         if right_arm < left_arm:
373             eval_cone([left_arm, CIRCLE])
374             eval_cone([0, right_arm])
375         else:
376             eval_cone([left_arm, right_arm])
377
378     def basic_circle_out_move(self, pos, direction):
379         mover = getattr(self.geometry, 'move__' + direction)
380         return mover(pos)
381
382     def circle_out(self, yx, f):
383         # Optimization potential: Precalculate movement positions.
384         # Optimization potential: Precalculate what tiles are shaded by what tile
385         # and skip evaluation of already shaded tile. (This only works if tiles
386         # shading implies they completely lie in existing shades; otherwise we
387         # would lose shade growth through tiles at shade borders.)
388         distance = 1
389         yx = YX(yx.y, yx.x)
390         while distance <= self.radius:
391             yx = self.basic_circle_out_move(yx, 'RIGHT')
392             for dir_i in range(len(self.circle_out_directions)):
393                 for dir_progress in range(distance):
394                     direction = self.circle_out_directions[dir_i]
395                     yx = self.circle_out_move(yx, direction)
396                     f(yx, distance, dir_i, dir_progress)
397             distance += 1
398
399
400
401
402 class FovMapHex(FovMap):
403     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
404                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
405
406     def circle_out_move(self, yx, direction):
407         return self.basic_circle_out_move(yx, direction)
408
409
410
411 class FovMapSquare(FovMap):
412     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
413                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
414
415     def circle_out_move(self, yx, direction):
416         yx = self.basic_circle_out_move(yx, direction[0])
417         return self.basic_circle_out_move(yx, direction[1])