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