1 """ May it be a light for you in dark places, when all other lights go out.
7 import pymunk.pygame_util
10 import pygame.locals as pgl
12 import pygame.transform
14 from .constants import (
15 LIGHT_CATEGORY, FITTINGS_CATEGORY, OBSTACLE_CATEGORY, TURNIP_CATEGORY,
17 from .rays import RayPolyManager
18 from .utils import DetailedTimer
19 from .loader import loader
20 from .transforms import ColourWedges
22 LIGHT_FILTER = pymunk.ShapeFilter(
23 mask=pymunk.ShapeFilter.ALL_MASKS ^ (
24 LIGHT_CATEGORY | FITTINGS_CATEGORY),
25 categories=LIGHT_CATEGORY)
27 FITTINGS_FILTER = pymunk.ShapeFilter(
28 mask=pymunk.ShapeFilter.ALL_MASKS ^ (
29 LIGHT_CATEGORY | FITTINGS_CATEGORY),
30 categories=FITTINGS_CATEGORY)
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)
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:
46 class LightManager(object):
47 """ Manages a set of lights. """
49 def __init__(self, space, gamestate):
51 self._battery_dead = False
53 BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
54 for light in self._lights:
55 light.add(self._space)
57 def add_light(self, cfg):
58 light = BaseLight.load(cfg)
59 self._lights.append(light)
60 light.add(self._space)
62 def battery_dead(self):
63 self._battery_dead = True
64 for light in self._lights:
67 def serialize_lights(self):
69 for light in self._lights:
70 result.append(light.serialize())
73 def toggle_nearest(self, *args, **kw):
74 if self._battery_dead:
76 light = self.nearest(*args, **kw)
80 def nearest(self, pos, surfpos=False, max_distance=1.0):
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
90 def lit_by(self, pos, surfpos=False, max_distance=0.0):
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]
98 light for light in lights
99 if light.on and light.ray_manager.reaches(pos)
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]
111 light for light in lights
112 if light.on and light.ray_manager.reaches(shape.body.position)
115 def total_power_usage(self):
116 return sum(light.power_usage() for light in self._lights)
118 def render_light(self, surface):
119 for light in self._lights:
120 light.render_light(surface)
122 def render_fittings(self, surface):
123 for light in self._lights:
124 light.render_fitting(surface)
127 for light in self._lights:
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
136 class BaseLight(object):
137 """ Common light functionality. """
140 RAY_MANAGER = RayPolyManager
142 FITTING_RADIUS = 24.0
148 self, colours, position, intensity=1.0, radius_limits=None,
149 direction=None, spread=None, on=True, start_colour=None,
150 bounding_radius=None):
151 self.colour_cycle = colours
153 self.colour = colours[0]
154 if start_colour and start_colour in colours:
155 self.colour_pos = colours.index(start_colour)
156 self.colour = start_colour
158 if not on and len(colours) > 1:
160 self.intensity = intensity
161 self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
162 self.body.light = self
163 self.ray_manager = self.RAY_MANAGER(
164 self.body, position, ray_filter=LIGHT_FILTER,
165 radius_limits=radius_limits, direction=direction, spread=spread,
166 bounding_radius=bounding_radius)
167 self.fitting = pymunk.Circle(
168 self.body, self.FITTING_RADIUS, self.ray_manager.position)
169 self.fitting.filter = FITTINGS_FILTER
170 self._fitting_image = None
171 self._colour_mult_image = None
174 result = self.ray_manager.serialize()
176 "type": self.__class__.__name__.lower(),
177 "colours": self.colour_cycle,
178 "position": self.position,
179 "intensity": self.intensity,
181 "start_colour": self.colour,
187 return self.ray_manager.position
190 def load(cls, config):
192 light_type = kw.pop("type")
193 light_class = cls.find_cls(light_type)
194 return light_class(**kw)
197 def find_cls(cls, light_type):
199 c for c in cls.__subclasses__()
200 if c.__name__.lower() == light_type]
203 def add(self, space):
204 if self.body.space is not None:
205 space.remove(self.body, *self.body.shapes)
206 space.add(self.body, self.fitting)
207 self.ray_manager.set_space(space)
208 self.ray_manager.update_shapes()
210 def _cached_surface(self, name, surface):
211 surf = self._surface_cache.get(name)
213 surf = self._surface_cache[name] = pygame.surface.Surface(
214 surface.get_size(), pgl.SWSURFACE
218 def light_colour(self):
219 light_colour = COLOURS[self.colour]
220 intensity = int(255 * self.intensity)
221 return light_colour + (intensity,)
223 def render_light(self, surface):
227 dt = DetailedTimer("render_light")
230 max_radius = self.ray_manager.max_radius
231 min_radius = self.ray_manager.min_radius
232 dest_rect = self.ray_manager.pygame_rect(surface)
234 white, black = (255, 255, 255, 255), (0, 0, 0, 0)
235 light_colour = self.light_colour()
237 radius_mask = self._cached_surface('radius_mask', surface)
238 radius_mask.set_clip(dest_rect)
239 ray_mask = self._cached_surface('ray_mask', surface)
240 ray_mask.set_clip(dest_rect)
243 for pygame_poly in self.ray_manager.pygame_polys(surface):
244 pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
245 pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
246 dt.lap("ray mask rendered")
248 radius_mask.fill(black)
249 centre = self.ray_manager.pygame_position(surface)
251 radius_mask, light_colour, centre, int(max_radius), 0)
253 radius_mask, black, centre, int(min_radius), 0)
254 dt.lap("radius mask rendered")
256 ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
257 dt.lap("blitted radius mask to ray mask")
259 surface.blit(ray_mask, dest_rect, dest_rect)
260 dt.lap("blitted surface")
263 def fitting_image(self):
264 if self._fitting_image is None:
265 self._fitting_image = loader.load_image(
266 "48", self.FITTING_IMG,
267 transform=ColourWedges(colours=self.colour_cycle))
268 return self._fitting_image
270 def invalidate_fitting_image(self):
271 self._fitting_image = None
273 def render_fitting(self, surface):
274 rx, ry = self.ray_manager.pygame_position(surface)
275 surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
277 def power_usage(self):
280 area = math.pi * (self.ray_manager.max_radius ** 2) # radius
281 area = area * (self.ray_manager.spread / (2 * math.pi)) # spread
282 return 5 * area * self.intensity / 6400 # 80x80 unit area
284 def base_damage(self):
285 return 10 * self.intensity
292 if self.colour_pos >= len(self.colour_cycle):
293 self.colour = self.colour_cycle[0]
297 self.colour = self.colour_cycle[self.colour_pos]
304 class Lamp(BaseLight):
306 FITTING_IMG = "lamp.png"
309 class PulsatingLamp(BaseLight):
311 FITTING_IMG = "lamp.png"
312 DEFAULT_PULSE_RANGE = (20, 100)
313 DEFAULT_PULSE_VELOCITY = 2
314 DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
315 DEFAULT_INTENSITY_VELOCITY = 0.1
317 def __init__(self, **kw):
318 self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
319 self.pulse_velocity = kw.pop(
320 "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
321 self.intensity_range = kw.pop(
322 "intensity_range", self.DEFAULT_INTENSITY_RANGE)
323 self.intensity_velocity = kw.pop(
324 "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
325 super(PulsatingLamp, self).__init__(
326 bounding_radius=self.pulse_range[1], **kw)
329 result = super(PulsatingLamp, self).serialize()
330 result["pulse_velocity"] = self.pulse_velocity
331 result["intensity_range"] = self.intensity_range
332 result["intensity_velocity"] = self.intensity_velocity
335 def _update_range(self, value, velocity, value_range):
337 if value < value_range[0]:
338 value = value_range[0]
340 elif value > value_range[1]:
341 value = value_range[1]
343 return value, velocity
346 self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
347 self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
348 self.intensity, self.intensity_velocity = self._update_range(
349 self.intensity, self.intensity_velocity, self.intensity_range)
352 class SpotLight(BaseLight):
354 FITTING_IMG = "spotlight.png"
356 def __init__(self, **kw):
357 self.angular_velocity = kw.pop("angular_velocity", None)
358 super(SpotLight, self).__init__(**kw)
361 result = super(SpotLight, self).serialize()
362 result["angular_velocity"] = self.angular_velocity
365 def fitting_image(self):
366 fitting_image = super(SpotLight, self).fitting_image()
367 rot_fitting_image = pygame.transform.rotozoom(
368 fitting_image, self.ray_manager.direction - 90, 1)
370 rot_rect = fitting_image.get_rect().copy()
371 rot_rect.center = rot_fitting_image.get_rect().center
372 rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
374 return rot_fitting_image
377 if self.angular_velocity:
378 self.ray_manager.direction -= self.angular_velocity
379 self.ray_manager.update_shapes()