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