variable name oops
[tabakrolletjie.git] / tabakrolletjie / lights.py
1 """ May it be a light for you in dark places, when all other lights go out.
2 """
3
4 import pymunk
5 import pymunk.pygame_util
6 import pygame.display
7 import pygame.draw
8 import pygame.locals as pgl
9 import pygame.rect
10
11 from .constants import LIGHT_CATEGORY, FITTINGS_CATEGORY
12 from .rays import RayPolyManager
13 from .utils import DetailedTimer
14 from .loader import loader
15
16 LIGHT_FILTER = pymunk.ShapeFilter(
17     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
18         LIGHT_CATEGORY | FITTINGS_CATEGORY),
19     categories=LIGHT_CATEGORY)
20
21 FITTINGS_FILTER = pymunk.ShapeFilter(
22     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
23         LIGHT_CATEGORY | FITTINGS_CATEGORY),
24     categories=FITTINGS_CATEGORY)
25
26 # Just match lights, nothing else
27 LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
28
29
30 class LightManager(object):
31     """ Manages a set of lights. """
32
33     def __init__(self, space, gamestate):
34         self._space = space
35         self._lights = [
36             BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
37         for light in self._lights:
38             light.add(self._space)
39
40     def toggle_nearest(self, *args, **kw):
41         light = self.nearest(*args, **kw)
42         if light:
43             light.toggle()
44
45     def nearest(self, pos, surfpos=False, max_distance=1.0):
46         if surfpos:
47             surface = pygame.display.get_surface()
48             pos = pymunk.pygame_util.from_pygame(pos, surface)
49         point_info = self._space.point_query_nearest(
50             pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
51         if point_info is not None:
52             return point_info.shape.body.light
53         return None
54
55     def lit_by(self, pos, surfpos=False, max_distance=0.0):
56         if surfpos:
57             surface = pygame.display.get_surface()
58             pos = pymunk.pygame_util.from_pygame(pos, surface)
59         point_info_list = self._space.point_query(
60             pos, max_distance, pymunk.ShapeFilter(mask=LIGHT_CATEGORY))
61         lights = [p.shape.body.light for p in point_info_list]
62         return [light for light in lights if light.on]
63
64     def light_query(self, shape):
65         """Query the lights by shape"""
66         old_filter = shape.filter
67         # We need to restrict matches to only the lights
68         shape.filter = LIT_BY_FILTER
69         shape_info_list = self._space.shape_query(shape)
70         shape.filter = old_filter
71         lights = [p.shape.body.light for p in shape_info_list]
72         return [light for light in lights if light.on]
73
74     def render_light(self, surface):
75         for light in self._lights:
76             light.render_light(surface)
77
78     def render_fittings(self, surface):
79         for light in self._lights:
80             light.render_fitting(surface)
81
82     def tick(self):
83         for light in self._lights:
84             light.tick()
85
86
87 class BaseLight(object):
88     """ Common light functionality. """
89
90     COLOURS = {
91         "red": (255, 0, 0),
92         "green": (0, 255, 0),
93         "blue": (0, 255, 255),
94         "yellow": (255, 255, 0),
95         "white": (255, 255, 255),
96     }
97
98     FITTING_IMG = None
99
100     # cached surfaces
101     _surface_cache = {}
102
103     def __init__(
104             self, colour, position, intensity=1.0,
105             radius_limits=(None, None), angle_limits=None):
106         self.colour = colour
107         self.position = pymunk.Vec2d(position)
108         self.on = True
109         self.intensity = intensity
110         self.radius_limits = radius_limits
111         self.angle_limits = angle_limits
112         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
113         self.fitting = pymunk.Circle(self.body, 10.0, self.position)
114         self.fitting.filter = FITTINGS_FILTER
115         self.body.light = self
116         self.ray_manager = RayPolyManager(self.body, LIGHT_FILTER)
117         self._image = None
118
119     @classmethod
120     def load(cls, config):
121         kw = config.copy()
122         light_type = kw.pop("type")
123         [light_class] = [
124             c for c in cls.__subclasses__()
125             if c.__name__.lower() == light_type]
126         return light_class(**kw)
127
128     def add(self, space):
129         if self.body.space is not None:
130             space.remove(self.body, *self.body.shapes)
131         self.ray_manager.generate_rays(space, self.position)
132         self.ray_manager.set_angle_limits(self.angle_limits)
133         ray_shapes = self.ray_manager.polys()
134         space.add(self.body, self.fitting, *ray_shapes)
135
136     def shapes_for_ray_polys(self, ray_polys):
137         return ray_polys
138
139     def toggle(self):
140         self.on = not self.on
141
142     def _cached_surfaces(self, surface):
143         radius_mask = self._surface_cache.get('radius_mask')
144         if radius_mask is None:
145             radius_mask = self._surface_cache['radius_mask'] = (
146                 pygame.surface.Surface(
147                     surface.get_size(), pgl.SWSURFACE)).convert_alpha()
148
149         ray_mask = self._surface_cache.get('ray_mask')
150         if ray_mask is None:
151             ray_mask = self._surface_cache['ray_mask'] = (
152                 pygame.surface.Surface(
153                     surface.get_size(), pgl.SWSURFACE)).convert_alpha()
154
155         return radius_mask, ray_mask
156
157     def render_light(self, surface):
158         if not self.on:
159             return
160
161         dt = DetailedTimer("render_light")
162         dt.start()
163         dt.show("%s, %s" % (self.ray_manager._start, self.ray_manager._end))
164
165         max_radius = self.radius_limits[1] or 50.0
166         min_radius = self.radius_limits[0] or 0
167
168         rw = max_radius * 2
169         rx, ry = pymunk.pygame_util.to_pygame(self.position, surface)
170         dest_rect = pygame.rect.Rect(rx, ry, rw, rw)
171         dest_rect.move_ip(- max_radius, - max_radius)
172
173         white, black = (255, 255, 255, 255), (0, 0, 0, 0)
174
175         radius_mask, ray_mask = self._cached_surfaces(surface)
176         radius_mask.set_clip(dest_rect)
177         ray_mask.set_clip(dest_rect)
178
179         ray_mask.fill(black)
180         for pygame_poly in self.ray_manager.pygame_polys(surface):
181             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
182             pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
183         dt.lap("ray mask rendered")
184
185         light_colour = self.COLOURS[self.colour]
186         intensity = int(255 * self.intensity)
187         light_colour = light_colour + (intensity,)
188
189         radius_mask.fill(black)
190         centre = pymunk.pygame_util.to_pygame(self.position, surface)
191         pygame.draw.circle(
192             radius_mask, light_colour, centre, int(max_radius), 0)
193         pygame.draw.circle(
194             radius_mask, black, centre, int(min_radius), 0)
195         dt.lap("radius mask rendered")
196
197         ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
198         dt.lap("blitted radius mask to ray mask")
199
200         surface.blit(ray_mask, dest_rect, dest_rect)
201         dt.lap("blitted surface")
202         dt.end()
203
204     def get_image(self):
205         if self._image is None:
206             self._image = loader.load_image("64", self.FITTING_IMG).copy()
207             fitting_colour = self.COLOURS[self.colour]
208             self._image.fill(fitting_colour, None, pgl.BLEND_RGBA_MULT)
209         return self._image
210
211     def render_fitting(self, surface):
212         rx, ry = pymunk.pygame_util.to_pygame(self.position, surface)
213         surface.blit(self.get_image(), (rx - 32, ry - 32), None, 0)
214
215     def tick(self):
216         pass
217
218
219 class SpotLight(BaseLight):
220     FITTING_IMG = "spotlight.png"
221     
222     def __init__(self, **kw):
223         kw.pop("direction", None)
224         kw.pop("spread", None)
225         self.angular_velocity = kw.pop("angular_velocity", None)
226         super(SpotLight, self).__init__(**kw)
227
228     def tick(self):
229         if self.angular_velocity:
230             start, end = self.angle_limits
231             start = (start + self.angular_velocity) % 360.0
232             end = (end + self.angular_velocity) % 360.0
233             self.angle_limits = (start, end)
234             self.ray_manager.set_angle_limits(self.angle_limits)