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