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