source: tools/area_editor.py@ 157:76049c9e3d5c

Last change on this file since 157:76049c9e3d5c was 157:76049c9e3d5c, checked in by Stefano Rivera <stefano@…>, 8 years ago

Scroll wheel

  • Property exe set to *
File size: 12.1 KB
Line 
1#!/usr/bin/env python
2
3# The basic area editor
4#
5# To edit an existing level, use
6# editor levelname
7#
8# To create a new level:
9#
10# editor levelname <xsize> <ysiz>
11# (size specified in pixels
12#
13
14import os
15import sys
16
17import pygame
18import pygame.locals as pgl
19
20sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
21
22import pymunk
23
24from albow.root import RootWidget
25from albow.widget import Widget
26from albow.controls import Button
27from albow.dialogs import alert
28
29from nagslang.constants import SCREEN
30from nagslang.level import Level, POLY_COLORS
31
32
33# layout constants
34MENU_BUTTON_HEIGHT = 35
35MENU_PAD = 6
36MENU_HALF_PAD = MENU_PAD // 2
37MENU_LEFT = SCREEN[0] + MENU_HALF_PAD
38MENU_WIDTH = 200 - MENU_PAD
39
40
41class EditorLevel(Level):
42
43 def __init__(self, name, x=800, y=600):
44 super(EditorLevel, self).__init__(name)
45 self.x = x
46 self.y = y
47
48 def round_point(self, pos):
49 return (10 * (pos[0] // 10), 10 * (pos[1] // 10))
50
51 def point_to_pymunk(self, pos):
52 # inverse of point_to_pygame
53 # (this is also the same as point_to_pygame, but a additional
54 # function for sanity later in pyweek).
55 return (pos[0], self.y - pos[1])
56
57 def add_point(self, poly_index, pos):
58 self.polygons.setdefault(poly_index, [])
59 if not self.polygons[poly_index]:
60 point = self.point_to_pymunk(self.round_point(pos))
61 self.polygons[poly_index].append(point)
62 else:
63 add_pos = self.fix_angle(poly_index, pos)
64 self.polygons[poly_index].append(add_pos)
65
66 def fix_angle(self, index, pos):
67 # Last point
68 point1 = self.point_to_pygame(self.polygons[index][-1])
69 pos = self.round_point(pos)
70 # We want the line (point1 to pos) to be an angle of
71 # 0, 45, 90, 135, 180, 225, 270, 305
72 # However, we only need to consider half the circle
73 # This is a hack to approximate the right thing
74 pos0 = (pos[0], point1[1])
75 pos90 = (point1[0], pos[1])
76 dist = max(abs(point1[0] - pos[0]), abs(point1[1] - pos[1]))
77 pos45 = (point1[0] + dist, point1[1] + dist)
78 pos135 = (point1[0] + dist, point1[1] - dist)
79 pos225 = (point1[0] - dist, point1[1] - dist)
80 pos305 = (point1[0] - dist, point1[1] + dist)
81 min_dist = 9999999
82 new_pos = point1
83 for cand in [pos0, pos90, pos45, pos135, pos225, pos305]:
84 dist = (pos[0] - cand[0]) ** 2 + (pos[1] - cand[1]) ** 2
85 if dist < min_dist:
86 new_pos = cand
87 min_dist = dist
88 return self.point_to_pymunk(new_pos)
89
90 def delete_point(self, index):
91 if index in self.polygons and len(self.polygons[index]) > 0:
92 self.polygons[index].pop()
93
94 def close_poly(self, index):
95 """Attempts to close the current polygon.
96
97 We allow a small additional step to close the polygon, but
98 it's limited as it's a magic point addition"""
99 if len(self.polygons[index]) < 2:
100 # Too small
101 return False
102 first = self.polygons[index][0]
103 last = self.polygons[index][-1]
104 print first, last
105 print self.fix_angle(index, self.point_to_pygame(first))
106 if self.fix_angle(index, self.point_to_pygame(first)) == first:
107 self.add_point(index, self.point_to_pygame(first))
108 return True
109 candidates = [(first[0] + 10 * i, first[1]) for
110 i in (-3, -2, -1, 1, 2, 3)]
111 candidates.extend([(first[0], first[1] + 10 * i) for
112 i in (-3, -2, -1, 1, 2, 3)])
113 candidates.extend([(first[0] + 10 * i, first[1] + 10 * i) for
114 i in (-3, -2, -1, 1, 2, 3)])
115 candidates.extend([(first[0] + 10 * i, first[1] - 10 * i) for
116 i in (-3, -2, -1, 1, 2, 3)])
117 min_dist = 99999
118 poss = None
119 for cand in candidates:
120 if self.fix_angle(index, self.point_to_pygame(cand)) == cand:
121 dist = (first[0] - cand[0]) ** 2 + (first[1] - cand[1]) ** 2
122 if dist < min_dist:
123 poss = cand
124 if poss is not None:
125 self.add_point(index, self.point_to_pygame(poss))
126 self.add_point(index, self.point_to_pygame(first))
127 return True
128 return False
129
130 def draw(self, surface, topleft, mouse_pos, mouse_poly, filled):
131 self._draw_background(True)
132 # Draw polygons as needed for the editor
133 if filled:
134 self._draw_exterior(True)
135 for index, polygon in self.polygons.items():
136 color = POLY_COLORS[index]
137 if len(polygon) > 1:
138 pointlist = [self.point_to_pygame(p) for p in polygon]
139 pygame.draw.lines(self._surface, color, False, pointlist, 2)
140 if index == mouse_poly and mouse_pos:
141 endpoint = self.fix_angle(index, mouse_pos)
142 pygame.draw.line(self._surface, color,
143 self.point_to_pygame(polygon[-1]),
144 self.point_to_pygame(endpoint))
145 surface_area = pygame.rect.Rect(topleft, SCREEN)
146 surface.blit(self._surface, (0, 0), surface_area)
147
148
149class LevelWidget(Widget):
150
151 def __init__(self, level):
152 super(LevelWidget, self).__init__(pygame.rect.Rect(0, 0,
153 SCREEN[0], SCREEN[1]))
154 self.level = level
155 self.pos = (0, 0)
156 self.filled_mode = False
157 self.mouse_pos = None
158 self.cur_poly = None
159
160 def _level_coordinates(self, pos):
161 # Move positions to level values
162 if not pos:
163 return (0, 0)
164 return pos[0] + self.pos[0], pos[1] + self.pos[1]
165
166 def _move_view(self, offset):
167 new_pos = [self.pos[0] + offset[0], self.pos[1] + offset[1]]
168 if new_pos[0] < 0:
169 new_pos[0] = self.pos[0]
170 elif new_pos[0] > self.level.x - SCREEN[0]:
171 new_pos[0] = self.pos[0]
172 if new_pos[1] < 0:
173 new_pos[1] = self.pos[1]
174 elif new_pos[1] > self.level.y - SCREEN[1]:
175 new_pos[1] = self.pos[1]
176 self.pos = tuple(new_pos)
177
178 def draw(self, surface):
179 if (self.cur_poly is not None and self.cur_poly in self.level.polygons
180 and len(self.level.polygons[self.cur_poly])):
181 # We have an active polygon
182 mouse_pos = self._level_coordinates(self.mouse_pos)
183 else:
184 mouse_pos = None
185 level.draw(surface, self.pos, mouse_pos, self.cur_poly,
186 self.filled_mode)
187
188 def change_poly(self, new_poly):
189 self.cur_poly = new_poly
190 if self.cur_poly is not None:
191 self.filled_mode = False
192
193 def key_down(self, ev):
194 if ev.key == pgl.K_LEFT:
195 self._move_view((-10, 0))
196 elif ev.key == pgl.K_RIGHT:
197 self._move_view((10, 0))
198 elif ev.key == pgl.K_UP:
199 self._move_view((0, -10))
200 elif ev.key == pgl.K_DOWN:
201 self._move_view((0, 10))
202 elif ev.key in (pgl.K_1, pgl.K_2, pgl.K_3, pgl.K_4, pgl.K_5, pgl.K_6):
203 self.change_poly(ev.key - pgl.K_0)
204 elif ev.key == pgl.K_0:
205 self.change_poly(None)
206 elif ev.key == pgl.K_d and self.cur_poly:
207 self.level.delete_point(self.cur_poly)
208 elif ev.key == pgl.K_f:
209 self.set_filled()
210 elif ev.key == pgl.K_c:
211 self.close_poly()
212
213 def set_filled(self):
214 if level.all_closed():
215 self.cur_poly = None
216 self.filled_mode = True
217 else:
218 print 'Not all polygons closed, so not filling'
219
220 def mouse_move(self, ev):
221 old_pos = self.mouse_pos
222 self.mouse_pos = ev.pos
223 if self.cur_poly and old_pos != self.mouse_pos:
224 self.invalidate()
225
226 def mouse_down(self, ev):
227 if ev.button == 4: # Scroll up
228 self._move_view((0, -10))
229 elif ev.button == 5: # Scroll down
230 self._move_view((0, 10))
231 elif ev.button == 6: # Scroll left
232 self._move_view((-10, 0))
233 elif ev.button == 7: # Scroll right
234 self._move_view((10, 0))
235 elif self.cur_poly:
236 # Add a point
237 self.level.add_point(self.cur_poly,
238 self._level_coordinates(ev.pos))
239
240 def close_poly(self):
241 if self.cur_poly is None:
242 return
243 if self.level.close_poly(self.cur_poly):
244 alert("Successfully closed the polygon")
245 self.change_poly(None)
246 else:
247 alert("Failed to close the polygon")
248
249
250class PolyButton(Button):
251 """Button for coosing the correct polygon"""
252
253 def __init__(self, index, level_widget):
254 if index is not None:
255 text = "Draw: %s" % index
256 else:
257 text = 'Exit Draw Mode'
258 super(PolyButton, self).__init__(text)
259 self.index = index
260 self.level_widget = level_widget
261
262 def action(self):
263 self.level_widget.change_poly(self.index)
264
265
266class EditorApp(RootWidget):
267
268 def __init__(self, level, surface):
269 super(EditorApp, self).__init__(surface)
270 self.level = level
271 self.level_widget = LevelWidget(self.level)
272 self.add(self.level_widget)
273
274 # Add poly buttons
275 y = 15
276 for poly in range(1, 7):
277 but = PolyButton(poly, self.level_widget)
278 but.rect = pygame.rect.Rect(0, 0, MENU_WIDTH // 2 - MENU_PAD,
279 MENU_BUTTON_HEIGHT)
280 if poly % 2:
281 but.rect.move_ip(MENU_LEFT, y)
282 else:
283 but.rect.move_ip(MENU_LEFT + MENU_WIDTH // 2 - MENU_HALF_PAD,
284 y)
285 y += MENU_BUTTON_HEIGHT + MENU_PAD
286 self.add(but)
287
288 button_rect = pygame.rect.Rect(0, 0, MENU_WIDTH, MENU_BUTTON_HEIGHT)
289
290 end_poly_but = PolyButton(None, self.level_widget)
291 end_poly_but.rect = button_rect.copy()
292 end_poly_but.rect.move_ip(MENU_LEFT, y)
293 self.add(end_poly_but)
294 y += MENU_BUTTON_HEIGHT + MENU_PAD
295
296 fill_but = Button('Fill exterior', action=self.level_widget.set_filled)
297 fill_but.rect = button_rect.copy()
298 fill_but.rect.move_ip(MENU_LEFT, y)
299 self.add(fill_but)
300 y += MENU_BUTTON_HEIGHT + MENU_PAD
301
302 save_but = Button('Save Level', action=self.save)
303 save_but.rect = button_rect.copy()
304 save_but.rect.move_ip(MENU_LEFT, y)
305 self.add(save_but)
306 y += MENU_BUTTON_HEIGHT + MENU_PAD
307
308 close_poly_but = Button('Close Polygon',
309 action=self.level_widget.close_poly)
310 close_poly_but.rect = button_rect.copy()
311 close_poly_but.rect.move_ip(MENU_LEFT, y)
312 self.add(close_poly_but)
313 y += MENU_BUTTON_HEIGHT + MENU_PAD
314
315 quit_but = Button('Quit', action=self.quit)
316 quit_but.rect = button_rect.copy()
317 quit_but.rect.move_ip(MENU_LEFT, y)
318 self.add(quit_but)
319
320 def key_down(self, ev):
321 if ev.key == pgl.K_ESCAPE:
322 self.quit()
323 elif ev.key == pgl.K_s:
324 self.save()
325 else:
326 self.level_widget.key_down(ev)
327
328 def save(self):
329 closed, messages = self.level.all_closed()
330 if closed:
331 self.level.save()
332 # display success
333 alert("Level %s saved successfully." % self.level.name)
334 else:
335 # display errors
336 alert("Failed to save level.\n\n%s" % '\n'.join(messages))
337
338 def mouse_move(self, ev):
339 self.level_widget.mouse_move(ev)
340
341
342if __name__ == "__main__":
343 if len(sys.argv) == 2:
344 level = EditorLevel(sys.argv[1])
345 level.load(pymunk.Space())
346 elif len(sys.argv) == 4:
347 level = EditorLevel(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
348 else:
349 print 'Please supply a levelname or levelname and level size'
350 sys.exit()
351 pygame.display.init()
352 pygame.font.init()
353 pygame.display.set_mode((SCREEN[0] + MENU_WIDTH, SCREEN[1]),
354 pgl.SWSURFACE)
355 pygame.display.set_caption('Nagslang Area Editor')
356 pygame.key.set_repeat(200, 100)
357 app = EditorApp(level, pygame.display.get_surface())
358 app.run()
Note: See TracBrowser for help on using the repository browser.