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,
16 COLOURS, FPS, NIGHT_HOURS_PER_TICK)
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 remove_light(self, light):
63 self._lights.remove(light)
64 light.remove(self._space)
66 def battery_dead(self):
67 self._battery_dead = True
68 for light in self._lights:
71 def serialize_lights(self):
73 for light in self._lights:
74 result.append(light.serialize())
77 def toggle_nearest(self, *args, **kw):
78 if self._battery_dead:
80 light = self.nearest(*args, **kw)
84 def nearest(self, pos, surfpos=False, max_distance=1.0):
86 surface = pygame.display.get_surface()
87 pos = pymunk.pygame_util.from_pygame(pos, surface)
88 point_info = self._space.point_query_nearest(
89 pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
90 if point_info is not None:
91 return point_info.shape.body.light
94 def lit_by(self, pos, surfpos=False, max_distance=0.0):
96 surface = pygame.display.get_surface()
97 pos = pymunk.pygame_util.from_pygame(pos, surface)
98 point_info_list = self._space.point_query(
99 pos, max_distance, LIT_BY_FILTER)
100 lights = [p.shape.body.light for p in point_info_list]
102 light for light in lights
103 if light.on and light.ray_manager.reaches(pos)
106 def light_query(self, shape):
107 """Query the lights by shape"""
108 old_filter = shape.filter
109 # We need to restrict matches to only the lights
110 shape.filter = LIT_BY_FILTER
111 shape_info_list = self._space.shape_query(shape)
112 shape.filter = old_filter
113 lights = [p.shape.body.light for p in shape_info_list]
115 light for light in lights
116 if light.on and light.ray_manager.reaches(shape.body.position)
119 def total_power_usage(self):
120 return sum(light.power_usage() for light in self._lights)
122 def render_light(self, surface):
123 for light in self._lights:
124 light.render_light(surface)
126 def render_fittings(self, surface):
127 for light in self._lights:
128 light.render_fitting(surface)
131 for light in self._lights:
135 def light_fitting_by_type(light_type):
136 """ Render a light fitting image for a light type. """
137 return BaseLight.find_cls(light_type).FITTING_IMG
140 def seed_cost(light_config, num_colours):
141 """Calculate a seed cost for a light from its configuration. """
142 cls = BaseLight.find_cls(light_config["type"])
143 return cls.BASE_COST + int(cls.find_cost(light_config) / 10) + num_colours
145 def light_info(light_config):
146 """Generate info about a light to go in the tooltip. """
147 cls = BaseLight.find_cls(light_config["type"])
148 return cls.get_info(light_config)
151 def light_name(light_config):
152 """Find formatted light name. """
153 cls = BaseLight.find_cls(light_config["type"])
157 class BaseLight(object):
158 """ Common light functionality. """
161 RAY_MANAGER = RayPolyManager
163 FITTING_RADIUS = 24.0
171 self, colours, position, intensity=1.0, radius_limits=None,
172 direction=None, spread=None, on=True, start_colour=None,
173 bounding_radius=None):
174 self.colour_cycle = colours
176 self.colour = colours[0]
177 if start_colour and start_colour in colours:
178 self.colour_pos = colours.index(start_colour)
179 self.colour = start_colour
183 self.intensity = intensity
184 self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
185 self.body.light = self
186 self.ray_manager = self.RAY_MANAGER(
187 self.body, position, ray_filter=LIGHT_FILTER,
188 radius_limits=radius_limits, direction=direction, spread=spread,
189 bounding_radius=bounding_radius)
190 self.fitting = pymunk.Circle(
191 self.body, self.FITTING_RADIUS, self.ray_manager.position)
192 self.fitting.filter = FITTINGS_FILTER
193 self._fitting_image = None
194 self._colour_mult_image = None
197 result = self.ray_manager.serialize()
199 "type": self.__class__.__name__.lower(),
200 "colours": self.colour_cycle,
201 "position": self.position,
202 "intensity": self.intensity,
204 "start_colour": self.colour,
210 return self.ray_manager.position
213 def load(cls, config):
215 light_type = kw.pop("type")
216 light_class = cls.find_cls(light_type)
217 return light_class(**kw)
220 def find_cls(cls, light_type):
222 c for c in cls.__subclasses__()
223 if c.__name__.lower() == light_type]
227 def find_cost(cls, config):
228 cost = 5 * config["intensity"]
232 def get_info(cls, config):
233 spread = math.radians(config.get("spread", 360))
234 rl = config.get("radius_limits", (0, 50.0))
235 intensity = config["intensity"]
236 power_usage = (cls._power_usage(rl[0], rl[1], spread, intensity)
237 / (FPS * NIGHT_HOURS_PER_TICK))
239 "power usage: %d/h" % power_usage,
241 "intensity: %g" % intensity,
244 def add(self, space):
245 if self.body.space is not None:
246 space.remove(self.body, *self.body.shapes)
247 space.add(self.body, self.fitting)
248 self.ray_manager.set_space(space)
249 self.ray_manager.update_shapes()
251 def remove(self, space):
252 if self.body.space is not None:
253 space.remove(self.body, *self.body.shapes)
255 def _cached_surface(self, name, surface):
256 surf = self._surface_cache.get(name)
258 surf = self._surface_cache[name] = pygame.surface.Surface(
259 surface.get_size(), pgl.SWSURFACE
263 def light_colour(self):
264 light_colour = COLOURS[self.colour]
265 intensity = int(255 * self.intensity)
266 return light_colour + (intensity,)
268 def render_light(self, surface):
272 dt = DetailedTimer("render_light")
275 max_radius = self.ray_manager.max_radius
276 min_radius = self.ray_manager.min_radius
277 dest_rect = self.ray_manager.pygame_rect(surface)
279 white, black = (255, 255, 255, 255), (0, 0, 0, 0)
280 light_colour = self.light_colour()
282 radius_mask = self._cached_surface('radius_mask', surface)
283 radius_mask.set_clip(dest_rect)
284 ray_mask = self._cached_surface('ray_mask', surface)
285 ray_mask.set_clip(dest_rect)
288 for pygame_poly in self.ray_manager.pygame_polys(surface):
289 pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
290 pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
291 dt.lap("ray mask rendered")
293 radius_mask.fill(black)
294 centre = self.ray_manager.pygame_position(surface)
296 radius_mask, light_colour, centre, int(max_radius), 0)
298 radius_mask, black, centre, int(min_radius), 0)
299 dt.lap("radius mask rendered")
301 ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
302 dt.lap("blitted radius mask to ray mask")
304 surface.blit(ray_mask, dest_rect, dest_rect)
305 dt.lap("blitted surface")
308 def fitting_image(self):
309 if self._fitting_image is None:
310 self._fitting_image = loader.load_image(
311 "48", self.FITTING_IMG,
312 transform=ColourWedges(colours=self.colour_cycle))
313 return self._fitting_image
315 def invalidate_fitting_image(self):
316 self._fitting_image = None
318 def render_fitting(self, surface):
319 rx, ry = self.ray_manager.pygame_position(surface)
320 surface.blit(self.fitting_image(), (rx - self.FITTING_RADIUS, ry - self.FITTING_RADIUS), None, 0)
323 def _power_usage(min_radius, max_radius, spread, intensity):
324 area = math.pi * (max_radius ** 2 - min_radius ** 2) # radius
325 area = area * (spread / (2 * math.pi)) # spread
326 return 5 * area * intensity / 6400 # 80x80 unit area
328 def power_usage(self):
331 rm = self.ray_manager
332 power_usage = self._power_usage(rm.min_radius, rm.max_radius, rm.spread, self.intensity)
335 def base_damage(self):
336 return 10 * self.intensity
344 if self.colour_pos >= len(self.colour_cycle):
345 self.colour = self.colour_cycle[0]
349 self.colour = self.colour_cycle[self.colour_pos]
356 class Lamp(BaseLight):
358 FITTING_IMG = "lamp.png"
363 class PulsatingLamp(BaseLight):
365 FITTING_IMG = "pulsatinglamp.png"
366 DEFAULT_PULSE_RANGE = (20, 100)
367 DEFAULT_PULSE_VELOCITY = 2
368 DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
369 DEFAULT_INTENSITY_VELOCITY = 0.1
371 NAME = "pulsating lamp"
373 def __init__(self, **kw):
374 self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
375 self.pulse_velocity = kw.pop(
376 "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
377 self.intensity_range = kw.pop(
378 "intensity_range", self.DEFAULT_INTENSITY_RANGE)
379 self.intensity_velocity = kw.pop(
380 "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
381 super(PulsatingLamp, self).__init__(
382 bounding_radius=self.pulse_range[1], **kw)
385 result = super(PulsatingLamp, self).serialize()
386 result["pulse_velocity"] = self.pulse_velocity
387 result["intensity_range"] = self.intensity_range
388 result["intensity_velocity"] = self.intensity_velocity
391 def _update_range(self, value, velocity, value_range):
393 if value < value_range[0]:
394 value = value_range[0]
396 elif value > value_range[1]:
397 value = value_range[1]
399 return value, velocity
402 self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
403 self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
404 self.intensity, self.intensity_velocity = self._update_range(
405 self.intensity, self.intensity_velocity, self.intensity_range)
408 def find_cost(cls, config):
409 cost = super(PulsatingLamp, cls).find_cost(config)
410 cost += config.get("pulse_velocity", cls.DEFAULT_PULSE_VELOCITY)
411 pr = config.get("pulse_range", cls.DEFAULT_PULSE_RANGE)
412 cost += (pr[1] - pr[0]) / 10
413 cost += 5 * config.get("intensity_velocity", cls.DEFAULT_INTENSITY_VELOCITY)
414 ir = config.get("intensity_range", cls.DEFAULT_INTENSITY_RANGE)
415 cost += 5 * (ir[1] - ir[0])
419 def get_info(cls, config):
420 spread = math.radians(config.get("spread", 360))
421 rl = config.get("radius_limits", (0, 50.0))
422 pr = config.get("pulse_range", cls.DEFAULT_PULSE_RANGE)
423 pv = config.get("pulse_velocity", cls.DEFAULT_PULSE_VELOCITY)
424 ir = config.get("intensity_range", cls.DEFAULT_INTENSITY_RANGE)
425 iv = config.get("intensity_velocity", cls.DEFAULT_INTENSITY_VELOCITY)
426 min_power = (cls._power_usage(rl[0], pr[0], spread, ir[0])
427 / (FPS * NIGHT_HOURS_PER_TICK))
428 max_power = (cls._power_usage(rl[0], pr[1], spread, ir[1])
429 / (FPS * NIGHT_HOURS_PER_TICK))
431 "power usage: %d/h - %d/h" % (min_power, max_power),
433 "intensity: %g - %g, velocity %g" % (ir[0], ir[1], iv),
434 "pulse: %d - %d, velocity %g" % (pr[0], pr[1], pv),
438 class SpotLight(BaseLight):
440 FITTING_IMG = "spotlight.png"
444 def __init__(self, **kw):
445 self.angular_velocity = kw.pop("angular_velocity", None)
446 super(SpotLight, self).__init__(**kw)
449 result = super(SpotLight, self).serialize()
450 result["angular_velocity"] = self.angular_velocity
453 def fitting_image(self):
454 fitting_image = super(SpotLight, self).fitting_image()
455 rot_fitting_image = pygame.transform.rotozoom(
456 fitting_image, self.ray_manager.direction - 90, 1)
458 rot_rect = fitting_image.get_rect().copy()
459 rot_rect.center = rot_fitting_image.get_rect().center
460 rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
462 return rot_fitting_image
465 if self.angular_velocity:
466 self.ray_manager.direction -= self.angular_velocity
467 self.ray_manager.update_shapes()
470 def find_cost(cls, config):
471 cost = super(SpotLight, cls).find_cost(config)
472 cost += config.get("angular_velocity", 0)
473 cost += config["spread"] / 10
474 rl = config["radius_limits"]
475 cost += (rl[1] - rl[0]) / 10
479 def get_info(cls, config):
480 info = super(SpotLight, cls).get_info(config)
481 rl = config["radius_limits"]
483 "spread: %d" % config["spread"],
484 "length: %d" % (rl[1] - rl[0]),
485 "angular velocity: %g" % config.get("angular_velocity", 0),