Merge branch 'master' of ctpug.org.za:tabakrolletjie
[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 math
5
6 import pymunk
7 import pymunk.pygame_util
8 import pygame.display
9 import pygame.draw
10 import pygame.locals as pgl
11 import pygame.rect
12
13 from .constants import LIGHT_CATEGORY, FITTINGS_CATEGORY, COLOURS
14 from .rays import RayPolyManager
15 from .utils import DetailedTimer
16 from .loader import loader
17 from .transforms import Multiply, MultiplyImage
18
19 LIGHT_FILTER = pymunk.ShapeFilter(
20     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
21         LIGHT_CATEGORY | FITTINGS_CATEGORY),
22     categories=LIGHT_CATEGORY)
23
24 FITTINGS_FILTER = pymunk.ShapeFilter(
25     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
26         LIGHT_CATEGORY | FITTINGS_CATEGORY),
27     categories=FITTINGS_CATEGORY)
28
29 # Just match lights, nothing else
30 LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
31
32
33 class LightManager(object):
34     """ Manages a set of lights. """
35
36     def __init__(self, space, gamestate):
37         self._space = space
38         self._lights = [
39             BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
40         for light in self._lights:
41             light.add(self._space)
42
43     def add_light(self, cfg):
44         light = BaseLight.load(cfg)
45         self._lights.append(light)
46         light.add(self._space)
47
48     def toggle_nearest(self, *args, **kw):
49         light = self.nearest(*args, **kw)
50         if light:
51             light.toggle()
52
53     def nearest(self, pos, surfpos=False, max_distance=1.0):
54         if surfpos:
55             surface = pygame.display.get_surface()
56             pos = pymunk.pygame_util.from_pygame(pos, surface)
57         point_info = self._space.point_query_nearest(
58             pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
59         if point_info is not None:
60             return point_info.shape.body.light
61         return None
62
63     def lit_by(self, pos, surfpos=False, max_distance=0.0):
64         if surfpos:
65             surface = pygame.display.get_surface()
66             pos = pymunk.pygame_util.from_pygame(pos, surface)
67         point_info_list = self._space.point_query(
68             pos, max_distance, pymunk.ShapeFilter(mask=LIGHT_CATEGORY))
69         lights = [p.shape.body.light for p in point_info_list]
70         return [
71             light for light in lights
72             if light.on and light.ray_manager.reaches(pos)
73         ]
74
75     def light_query(self, shape):
76         """Query the lights by shape"""
77         old_filter = shape.filter
78         # We need to restrict matches to only the lights
79         shape.filter = LIT_BY_FILTER
80         shape_info_list = self._space.shape_query(shape)
81         shape.filter = old_filter
82         lights = [p.shape.body.light for p in shape_info_list]
83         return [
84             light for light in lights
85             if light.on and light.ray_manager.reaches(shape.body.position)
86         ]
87
88     def total_power_usage(self):
89         return sum(light.power_usage() for light in self._lights)
90
91     def render_light(self, surface):
92         for light in self._lights:
93             light.render_light(surface)
94
95     def render_fittings(self, surface):
96         for light in self._lights:
97             light.render_fitting(surface)
98
99     def tick(self):
100         for light in self._lights:
101             light.tick()
102
103
104 class BaseLight(object):
105     """ Common light functionality. """
106
107     # defaults
108     RAY_MANAGER = RayPolyManager
109     FITTING_IMG = None
110     FITTING_RADIUS = 24.0
111
112     # cached surfaces
113     _surface_cache = {}
114
115     def __init__(
116             self, colours, position, intensity=1.0, radius_limits=None,
117             direction=None, spread=None):
118         self.colour_cycle = colours
119         self.colour_pos = 0
120         self.colour = colours[0]
121         self.on = True
122         self.intensity = intensity
123         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
124         self.body.light = self
125         self.ray_manager = self.RAY_MANAGER(
126             self.body, position, ray_filter=LIGHT_FILTER,
127             radius_limits=radius_limits, direction=direction, spread=spread)
128         self.fitting = pymunk.Circle(
129             self.body, self.FITTING_RADIUS, self.ray_manager.position)
130         self.fitting.filter = FITTINGS_FILTER
131         self._fitting_image = None
132         self._colour_mult_image = None
133
134     @property
135     def position(self):
136         return self.ray_manager.position
137
138     @classmethod
139     def load(cls, config):
140         kw = config.copy()
141         light_type = kw.pop("type")
142         [light_class] = [
143             c for c in cls.__subclasses__()
144             if c.__name__.lower() == light_type]
145         return light_class(**kw)
146
147     def add(self, space):
148         if self.body.space is not None:
149             space.remove(self.body, *self.body.shapes)
150         space.add(self.body, self.fitting)
151         self.ray_manager.set_space(space)
152         self.ray_manager.update_shapes()
153
154     def _cached_surface(self, name, surface):
155         surf = self._surface_cache.get(name)
156         if surf is None:
157             surf = self._surface_cache[name] = pygame.surface.Surface(
158                 surface.get_size(), pgl.SWSURFACE
159             ).convert_alpha()
160         return surf
161
162     def light_colour(self):
163         light_colour = COLOURS[self.colour]
164         intensity = int(255 * self.intensity)
165         return light_colour + (intensity,)
166
167     def render_light(self, surface):
168         if not self.on:
169             return
170
171         dt = DetailedTimer("render_light")
172         dt.start()
173
174         max_radius = self.ray_manager.max_radius
175         min_radius = self.ray_manager.min_radius
176         dest_rect = self.ray_manager.pygame_rect(surface)
177
178         white, black = (255, 255, 255, 255), (0, 0, 0, 0)
179         light_colour = self.light_colour()
180
181         radius_mask = self._cached_surface('radius_mask', surface)
182         radius_mask.set_clip(dest_rect)
183         ray_mask = self._cached_surface('ray_mask', surface)
184         ray_mask.set_clip(dest_rect)
185
186         ray_mask.fill(black)
187         for pygame_poly in self.ray_manager.pygame_polys(surface):
188             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
189             pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
190         dt.lap("ray mask rendered")
191
192         radius_mask.fill(black)
193         centre = self.ray_manager.pygame_position(surface)
194         pygame.draw.circle(
195             radius_mask, light_colour, centre, int(max_radius), 0)
196         pygame.draw.circle(
197             radius_mask, black, centre, int(min_radius), 0)
198         dt.lap("radius mask rendered")
199
200         ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
201         dt.lap("blitted radius mask to ray mask")
202
203         surface.blit(ray_mask, dest_rect, dest_rect)
204         dt.lap("blitted surface")
205         dt.end()
206
207     def fitting_image(self):
208         if self._fitting_image is None:
209             fitting_colours = [COLOURS[c] for c in self.colour_cycle]
210             ncolour = len(fitting_colours)
211             if ncolour > 3:
212                 print "Multicoloured light should not have more than 3 colours"
213                 ncolour = 3
214
215             if ncolour == 1:
216                 self._fitting_image = loader.load_image(
217                 "48", self.FITTING_IMG,
218                 transform=Multiply(colour=fitting_colours[0]))
219             else:
220                 if self._colour_mult_image is None:
221                     self._colour_mult_image = pygame.surface.Surface((48, 48))
222
223                     for i in range(ncolour):
224                         sector = loader.load_image(
225                             "48", "light_mask_%d_%d.png" % (ncolour, i + 1),
226                             transform=Multiply(colour=fitting_colours[i]))
227                         self._colour_mult_image.blit(sector, (0,0), None, 0)
228                     
229                 self._fitting_image = loader.load_image(
230                     "48", self.FITTING_IMG,
231                     transform=MultiplyImage(image=self._colour_mult_image))
232
233         return self._fitting_image
234
235     def invalidate_fitting_image(self):
236         self._fitting_image = None
237
238     def render_fitting(self, surface):
239         rx, ry = self.ray_manager.pygame_position(surface)
240         surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
241
242     def power_usage(self):
243         if not self.on:
244             return 0.0
245         area = math.pi * (self.ray_manager.max_radius ** 2)  # radius
246         area = area * (self.ray_manager.spread / (2 * math.pi))  # spread
247         return 5 * area * self.intensity
248
249     def base_damage(self):
250         return 5 * self.intensity
251
252     def toggle(self):
253         self.colour_pos += 1
254         if self.colour_pos >= len(self.colour_cycle):
255             self.colour = self.colour_cycle[0]
256             self.colour_pos = -1
257             self.on = False
258         else:
259             self.colour = self.colour_cycle[self.colour_pos]
260             self.on = True
261         self.invalidate_fitting_image()
262
263     def tick(self):
264         pass
265
266
267 class Lamp(BaseLight):
268
269     FITTING_IMG = "lamp.png"
270
271
272 class PulsatingLamp(BaseLight):
273
274     FITTING_IMG = "lamp.png"
275     DEFAULT_PULSE_RANGE = (20, 100)
276     DEFAULT_PULSE_VELOCITY = 2
277     DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
278     DEFAULT_INTENSITY_VELOCITY = 0.1
279
280     def __init__(self, **kw):
281         self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
282         self.pulse_velocity = kw.pop(
283             "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
284         self.intensity_range = kw.pop(
285             "intensity_range", self.DEFAULT_INTENSITY_RANGE)
286         self.intensity_velocity = kw.pop(
287             "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
288         super(PulsatingLamp, self).__init__(**kw)
289
290     def _update_range(self, value, velocity, value_range):
291         value += velocity
292         if value < value_range[0]:
293             value = value_range[0]
294             velocity = -velocity
295         elif value > value_range[1]:
296             value = value_range[1]
297             velocity = -velocity
298         return value, velocity
299
300     def tick(self):
301         self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
302             self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
303         self.intensity, self.intensity_velocity = self._update_range(
304             self.intensity, self.intensity_velocity, self.intensity_range)
305
306
307 class SpotLight(BaseLight):
308
309     FITTING_IMG = "spotlight.png"
310
311     def __init__(self, **kw):
312         self.angular_velocity = kw.pop("angular_velocity", None)
313         super(SpotLight, self).__init__(**kw)
314
315     def tick(self):
316         if self.angular_velocity:
317             self.ray_manager.direction -= self.angular_velocity
318             self.ray_manager.update_shapes()