Change target FPS and rescale things to match
[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 ColourWedges
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, LIT_BY_FILTER)
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_by_type(light_type):
106     """ Render a light fitting image for a light type. """
107     return BaseLight.find_cls(light_type).FITTING_IMG
108
109
110 class BaseLight(object):
111     """ Common light functionality. """
112
113     # defaults
114     RAY_MANAGER = RayPolyManager
115     FITTING_IMG = None
116     FITTING_RADIUS = 24.0
117
118     # cached surfaces
119     _surface_cache = {}
120
121     def __init__(
122             self, colours, position, intensity=1.0, radius_limits=None,
123             direction=None, spread=None):
124         self.colour_cycle = colours
125         self.colour_pos = 0
126         self.colour = colours[0]
127         self.on = True
128         self.intensity = intensity
129         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
130         self.body.light = self
131         self.ray_manager = self.RAY_MANAGER(
132             self.body, position, ray_filter=LIGHT_FILTER,
133             radius_limits=radius_limits, direction=direction, spread=spread)
134         self.fitting = pymunk.Circle(
135             self.body, self.FITTING_RADIUS, self.ray_manager.position)
136         self.fitting.filter = FITTINGS_FILTER
137         self._fitting_image = None
138         self._colour_mult_image = None
139
140     @property
141     def position(self):
142         return self.ray_manager.position
143
144     @classmethod
145     def load(cls, config):
146         kw = config.copy()
147         light_type = kw.pop("type")
148         light_class = cls.find_cls(light_type)
149         return light_class(**kw)
150
151     @classmethod
152     def find_cls(cls, light_type):
153         [light_class] = [
154             c for c in cls.__subclasses__()
155             if c.__name__.lower() == light_type]
156         return light_class
157
158     def add(self, space):
159         if self.body.space is not None:
160             space.remove(self.body, *self.body.shapes)
161         space.add(self.body, self.fitting)
162         self.ray_manager.set_space(space)
163         self.ray_manager.update_shapes()
164
165     def _cached_surface(self, name, surface):
166         surf = self._surface_cache.get(name)
167         if surf is None:
168             surf = self._surface_cache[name] = pygame.surface.Surface(
169                 surface.get_size(), pgl.SWSURFACE
170             ).convert_alpha()
171         return surf
172
173     def light_colour(self):
174         light_colour = COLOURS[self.colour]
175         intensity = int(255 * self.intensity)
176         return light_colour + (intensity,)
177
178     def render_light(self, surface):
179         if not self.on:
180             return
181
182         dt = DetailedTimer("render_light")
183         dt.start()
184
185         max_radius = self.ray_manager.max_radius
186         min_radius = self.ray_manager.min_radius
187         dest_rect = self.ray_manager.pygame_rect(surface)
188
189         white, black = (255, 255, 255, 255), (0, 0, 0, 0)
190         light_colour = self.light_colour()
191
192         radius_mask = self._cached_surface('radius_mask', surface)
193         radius_mask.set_clip(dest_rect)
194         ray_mask = self._cached_surface('ray_mask', surface)
195         ray_mask.set_clip(dest_rect)
196
197         ray_mask.fill(black)
198         for pygame_poly in self.ray_manager.pygame_polys(surface):
199             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
200             pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
201         dt.lap("ray mask rendered")
202
203         radius_mask.fill(black)
204         centre = self.ray_manager.pygame_position(surface)
205         pygame.draw.circle(
206             radius_mask, light_colour, centre, int(max_radius), 0)
207         pygame.draw.circle(
208             radius_mask, black, centre, int(min_radius), 0)
209         dt.lap("radius mask rendered")
210
211         ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
212         dt.lap("blitted radius mask to ray mask")
213
214         surface.blit(ray_mask, dest_rect, dest_rect)
215         dt.lap("blitted surface")
216         dt.end()
217
218     def fitting_image(self):
219         if self._fitting_image is None:
220             self._fitting_image = loader.load_image(
221                 "48", self.FITTING_IMG,
222                 transform=ColourWedges(colours=self.colour_cycle))
223         return self._fitting_image
224
225     def invalidate_fitting_image(self):
226         self._fitting_image = None
227
228     def render_fitting(self, surface):
229         rx, ry = self.ray_manager.pygame_position(surface)
230         surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
231
232     def power_usage(self):
233         if not self.on:
234             return 0.0
235         area = math.pi * (self.ray_manager.max_radius ** 2)  # radius
236         area = area * (self.ray_manager.spread / (2 * math.pi))  # spread
237         return 5 * area * self.intensity / 6400  # 80x80 unit area
238
239     def base_damage(self):
240         return 10 * self.intensity
241
242     def toggle(self):
243         self.colour_pos += 1
244         if self.colour_pos >= len(self.colour_cycle):
245             self.colour = self.colour_cycle[0]
246             self.colour_pos = -1
247             self.on = False
248         else:
249             self.colour = self.colour_cycle[self.colour_pos]
250             self.on = True
251
252     def tick(self):
253         pass
254
255
256 class Lamp(BaseLight):
257
258     FITTING_IMG = "lamp.png"
259
260
261 class PulsatingLamp(BaseLight):
262
263     FITTING_IMG = "lamp.png"
264     DEFAULT_PULSE_RANGE = (20, 100)
265     DEFAULT_PULSE_VELOCITY = 2
266     DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
267     DEFAULT_INTENSITY_VELOCITY = 0.1
268
269     def __init__(self, **kw):
270         self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
271         self.pulse_velocity = kw.pop(
272             "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
273         self.intensity_range = kw.pop(
274             "intensity_range", self.DEFAULT_INTENSITY_RANGE)
275         self.intensity_velocity = kw.pop(
276             "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
277         super(PulsatingLamp, self).__init__(**kw)
278
279     def _update_range(self, value, velocity, value_range):
280         value += velocity
281         if value < value_range[0]:
282             value = value_range[0]
283             velocity = -velocity
284         elif value > value_range[1]:
285             value = value_range[1]
286             velocity = -velocity
287         return value, velocity
288
289     def tick(self):
290         self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
291             self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
292         self.intensity, self.intensity_velocity = self._update_range(
293             self.intensity, self.intensity_velocity, self.intensity_range)
294
295
296 class SpotLight(BaseLight):
297
298     FITTING_IMG = "spotlight.png"
299
300     def __init__(self, **kw):
301         self.angular_velocity = kw.pop("angular_velocity", None)
302         super(SpotLight, self).__init__(**kw)
303
304     def fitting_image(self):
305         fitting_image = super(SpotLight, self).fitting_image()
306         rot_fitting_image = pygame.transform.rotozoom(
307             fitting_image, self.ray_manager.direction - 90, 1)
308
309         rot_rect = fitting_image.get_rect().copy()
310         rot_rect.center = rot_fitting_image.get_rect().center
311         rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
312
313         return rot_fitting_image
314
315     def tick(self):
316         if self.angular_velocity:
317             self.ray_manager.direction -= self.angular_velocity
318             self.ray_manager.update_shapes()