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