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