home · contact · privacy
More refactoring.
[plomrogue2-experiments] / new / plomrogue / mapping.py
1 from plomrogue.errors import ArgError
2 import collections
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 Map:
20
21     def __init__(self, size=YX(0, 0), init_char = '?'):
22         self.size = size
23         self.terrain = init_char*self.size_i
24
25     def __getitem__(self, yx):
26         return self.terrain[self.get_position_index(yx)]
27
28     def __setitem__(self, yx, c):
29         pos_i = self.get_position_index(yx)
30         if type(c) == str:
31             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
32         else:
33             self.terrain[pos_i] = c
34
35     def __iter__(self):
36         """Iterate over YX position coordinates."""
37         for y in range(self.size.y):
38             for x in range(self.size.x):
39                 yield YX(y, x)
40
41     @property
42     def size_i(self):
43         return self.size.y * self.size.x
44
45     def set_line(self, y, line):
46         height_map = self.size.y
47         width_map = self.size.x
48         if y >= height_map:
49             raise ArgError('too large row number %s' % y)
50         width_line = len(line)
51         if width_line > width_map:
52             raise ArgError('too large map line width %s' % width_line)
53         self.terrain = self.terrain[:y * width_map] + line +\
54                        self.terrain[(y + 1) * width_map:]
55
56     def get_position_index(self, yx):
57         return yx.y * self.size.x + yx.x
58
59     def lines(self):
60         width = self.size.x
61         for y in range(self.size.y):
62             yield (y, self.terrain[y * width:(y + 1) * width])
63
64
65
66 class MapGeometry():
67
68     def get_directions(self):
69         directions = []
70         for name in dir(self):
71             if name[:5] == 'move_':
72                 directions += [name[5:]]
73         return directions
74
75     def get_neighbors(self, pos, map_size):
76         neighbors = {}
77         if not hasattr(self, 'neighbors_to'):
78             self.neighbors_to = {}
79         if not map_size in self.neighbors_to:
80             self.neighbors_to[map_size] = {}
81         if pos in self.neighbors_to[map_size]:
82             return self.neighbors_to[map_size][pos]
83         for direction in self.get_directions():
84             neighbors[direction] = self.move(pos, direction, map_size)
85         self.neighbors_to[map_size][pos] = neighbors
86         return neighbors
87
88     def undouble_coordinate(self, maps_size, coordinate):
89         y = maps_size.y * coordinate[0].y + coordinate[1].y
90         x = maps_size.x * coordinate[0].x + coordinate[1].x
91         return YX(y, x)
92
93     def get_view_offset(self, maps_size, center, radius):
94         yx_to_origin = self.undouble_coordinate(maps_size, center)
95         return yx_to_origin - YX(radius, radius)
96
97     def pos_in_view(self, pos, offset, maps_size):
98         return self.undouble_coordinate(maps_size, pos) - offset
99
100     def get_view(self, maps_size, get_map, radius, view_offset):
101         m = Map(size=YX(radius*2+1, radius*2+1)
102         for pos in m:
103             seen_pos = self.correct_double_coordinate(maps_size, (0,0),
104                                                       pos + view_offset)
105             seen_map = get_map(seen_pos[0], False)
106             if seen_map is None:
107                 seen_map = Map(size=maps_size)
108             m[pos] = seen_map[seen_pos[1]]
109         return m
110
111     def get_correcting_map_size(self, size, offset):
112         return size
113
114     def correct_double_coordinate(self, map_size, big_yx, little_yx):
115
116         def adapt_axis(axis):
117             maps_crossed = little_yx[axis] // map_size[axis]
118             new_big = big_yx[axis] + maps_crossed
119             new_little = little_yx[axis] % map_size[axis]
120             return new_big, new_little
121
122         new_big_y, new_little_y = adapt_axis(0)
123         new_big_x, new_little_x = adapt_axis(1)
124         return YX(new_big_y, new_big_x), YX(new_little_y, new_little_x)
125
126     def move(self, start_pos, direction, map_size):
127         mover = getattr(self, 'move_' + direction)
128         big_yx, little_yx = start_pos
129         uncorrected_target = mover(little_yx)
130         return self.correct_double_coordinate(map_size, big_yx,
131                                               uncorrected_target)
132
133
134
135 class MapGeometryWithLeftRightMoves(MapGeometry):
136
137     def move_LEFT(self, start_pos):
138         return YX(start_pos.y, start_pos.x - 1)
139
140     def move_RIGHT(self, start_pos):
141         return YX(start_pos.y, start_pos.x + 1)
142
143
144
145 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
146
147     def move_UP(self, start_pos):
148         return YX(start_pos.y - 1, start_pos.x)
149
150     def move_DOWN(self, start_pos):
151         return YX(start_pos.y + 1, start_pos.x)
152
153
154
155 class MapGeometryHex(MapGeometryWithLeftRightMoves):
156
157     def __init__(self, *args, **kwargs):
158         super().__init__(*args, **kwargs)
159         self.fov_map_type = FovMapHex
160
161     def move_UPLEFT(self, start_pos):
162         if start_pos.y % 2 == 1:
163             return YX(start_pos.y - 1, start_pos.x - 1)
164         else:
165             return YX(start_pos.y - 1, start_pos.x)
166
167     def move_UPRIGHT(self, start_pos):
168         if start_pos.y % 2 == 1:
169             return YX(start_pos.y - 1, start_pos.x)
170         else:
171             return YX(start_pos.y - 1, start_pos.x + 1)
172
173     def move_DOWNLEFT(self, start_pos):
174         if start_pos.y % 2 == 1:
175              return YX(start_pos.y + 1, start_pos.x - 1)
176         else:
177                return YX(start_pos.y + 1, start_pos.x)
178
179     def move_DOWNRIGHT(self, start_pos):
180         if start_pos.y % 2 == 1:
181             return YX(start_pos.y + 1, start_pos.x)
182         else:
183             return YX(start_pos.y + 1, start_pos.x + 1)
184
185
186 class FovMap(Map):
187
188     def __init__(self, source_map, center):
189         self.source_map = source_map
190         self.size = self.source_map.size
191         self.fov_radius = (self.size.y / 2) - 0.5
192         self.terrain = '?' * self.size_i
193         self[center] = '.'
194         self.shadow_cones = []
195         self.circle_out(center, self.shadow_process_hex)
196
197     def shadow_process_hex(self, yx, distance_to_center, dir_i, dir_progress):
198         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
199         # skip all.
200         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
201
202         def correct_arm(arm):
203             if arm < 0:
204                 arm += CIRCLE
205             return arm
206
207         def in_shadow_cone(new_cone):
208             for old_cone in self.shadow_cones:
209                 if old_cone[0] >= new_cone[0] and \
210                     new_cone[1] >= old_cone[1]:
211                     #print('DEBUG shadowed by:', old_cone)
212                     return True
213                 # We might want to also shade hexes whose middle arm is inside a
214                 # shadow cone for a darker FOV. Note that we then could not for
215                 # optimization purposes rely anymore on the assumption that a
216                 # shaded hex cannot add growth to existing shadow cones.
217             return False
218
219         def merge_cone(new_cone):
220             import math
221             for old_cone in self.shadow_cones:
222                 if new_cone[0] > old_cone[0] and \
223                     (new_cone[1] < old_cone[0] or
224                      math.isclose(new_cone[1], old_cone[0])):
225                     #print('DEBUG merging to', old_cone)
226                     old_cone[0] = new_cone[0]
227                     #print('DEBUG merged cone:', old_cone)
228                     return True
229                 if new_cone[1] < old_cone[1] and \
230                     (new_cone[0] > old_cone[1] or
231                      math.isclose(new_cone[0], old_cone[1])):
232                     #print('DEBUG merging to', old_cone)
233                     old_cone[1] = new_cone[1]
234                     #print('DEBUG merged cone:', old_cone)
235                     return True
236             return False
237
238         def eval_cone(cone):
239             #print('DEBUG CONE', cone, '(', step_size, distance_to_center, number_steps, ')')
240             if in_shadow_cone(cone):
241                 return
242             self[yx] = '.'
243             if self.source_map[yx] != '.':
244                 #print('DEBUG throws shadow', cone)
245                 unmerged = True
246                 while merge_cone(cone):
247                     unmerged = False
248                 if unmerged:
249                     self.shadow_cones += [cone]
250
251         #print('DEBUG', yx)
252         step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
253         number_steps = dir_i * distance_to_center + dir_progress
254         left_arm = correct_arm(-(step_size/2) - step_size*number_steps)
255         right_arm = correct_arm(left_arm - step_size)
256         # Optimization potential: left cone could be derived from previous
257         # right cone. Better even: Precalculate all cones.
258         if right_arm > left_arm:
259             eval_cone([left_arm, 0])
260             eval_cone([CIRCLE, right_arm])
261         else:
262             eval_cone([left_arm, right_arm])
263
264     def basic_circle_out_move(self, pos, direction):
265         """Move position pos into direction. Return whether still in map."""
266         mover = getattr(self.geometry, 'move_' + direction)
267         pos = mover(pos)
268         if pos.y < 0 or pos.x < 0 or \
269             pos.y >= self.size.y or pos.x >= self.size.x:
270             return pos, False
271         return pos, True
272
273     def circle_out(self, yx, f):
274         # Optimization potential: Precalculate movement positions. (How to check
275         # circle_in_map then?)
276         # Optimization potential: Precalculate what hexes are shaded by what hex
277         # and skip evaluation of already shaded hexes. (This only works if hex
278         # shading implies they completely lie in existing shades; otherwise we
279         # would lose shade growth through hexes at shade borders.)
280
281         # TODO: Start circling only in earliest obstacle distance.
282         # TODO: get rid of circle_in_map logic
283         circle_in_map = True
284         distance = 1
285         yx = YX(yx.y, yx.x)
286         #print('DEBUG CIRCLE_OUT', yx)
287         while circle_in_map:
288             if distance > self.fov_radius:
289                 break
290             circle_in_map = False
291             yx, _ = self.basic_circle_out_move(yx, 'RIGHT')
292             for dir_i in range(len(self.circle_out_directions)):
293                 for dir_progress in range(distance):
294                     direction = self.circle_out_directions[dir_i]
295                     yx, test = self.circle_out_move(yx, direction)
296                     if test:
297                         f(yx, distance, dir_i, dir_progress)
298                         circle_in_map = True
299             distance += 1
300
301
302
303 class FovMapHex(FovMap):
304     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
305                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
306
307     def __init__(self, *args, **kwargs):
308         self.geometry = MapGeometryHex()
309         super().__init__(*args, **kwargs)
310
311     def circle_out_move(self, yx, direction):
312         return self.basic_circle_out_move(yx, direction)
313
314
315
316 class FovMapSquare(FovMap):
317     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
318                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
319
320     def __init__(self, *args, **kwargs):
321         self.geometry = MapGeometrySquare()
322         super().__init__(*args, **kwargs)
323
324     def circle_out_move(self, yx, direction):
325         self.basic_circle_out_move(yx, direction[0])
326         return self.basic_circle_out_move(yx, direction[1])
327