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