360 lines
11 KiB
Python
360 lines
11 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import math
|
|
import random
|
|
from typing import Final
|
|
|
|
import pygame
|
|
|
|
from data.constants import (
|
|
ANIM_TEXT_MS,
|
|
CAMERA_EASE_PER_S,
|
|
Color,
|
|
EXPLORED_ALPHA,
|
|
EXPLORED_TINT,
|
|
LIGHT_ALPHA_AT_EDGE,
|
|
LIGHT_ALPHA_PER_TILE,
|
|
MAX_PARTICLES,
|
|
SHAKE_DECAY_PER_S,
|
|
)
|
|
|
|
SHAKE_MAX_OFFSET: Final = 7.0
|
|
|
|
# kind -> (colors, gravity px/s^2, speed px/s, life s, size px)
|
|
PARTICLE_KINDS: Final[dict[str, tuple[tuple[Color, ...], float, float, float, int]]] = {
|
|
"hit": ((255, 235, 180, 255), 260.0, 55.0, 0.35, 2),
|
|
"crit": ((255, 215, 90, 255), 130.0, 75.0, 0.5, 2),
|
|
"blood": ((200, 55, 45, 255), 420.0, 60.0, 0.45, 2),
|
|
"slime": ((110, 210, 120, 255), 380.0, 50.0, 0.5, 2),
|
|
"ash": ((150, 150, 160, 255), 40.0, 30.0, 0.7, 2),
|
|
"stars": ((255, 225, 120, 255), -60.0, 45.0, 0.9, 2),
|
|
"sparkle": ((255, 250, 210, 255), -30.0, 35.0, 0.6, 1),
|
|
"heal": ((140, 235, 150, 255), -90.0, 30.0, 0.8, 2),
|
|
"stairs": ((245, 210, 70, 255), -45.0, 22.0, 0.8, 1),
|
|
}
|
|
|
|
|
|
class Camera:
|
|
"""Eased viewport follow; clamps to the map and centers small floors."""
|
|
|
|
def __init__(self, viewport: tuple[int, int]) -> None:
|
|
self.viewport_width, self.viewport_height = viewport
|
|
self.x = 0.0
|
|
self.y = 0.0
|
|
|
|
def clamp_bounds(self, map_width: int, map_height: int, tile: int) -> None:
|
|
self._map_width = map_width * tile
|
|
self._map_height = map_height * tile
|
|
|
|
def snap(self, target_x: float, target_y: float) -> None:
|
|
self.x, self.y = self._clamp(self._centered(target_x, target_y))
|
|
|
|
def update(self, target_x: float, target_y: float, dt: float) -> None:
|
|
goal_x, goal_y = self._clamp(self._centered(target_x, target_y))
|
|
ease = min(1.0, dt * CAMERA_EASE_PER_S)
|
|
self.x += (goal_x - self.x) * ease
|
|
self.y += (goal_y - self.y) * ease
|
|
|
|
def _centered(self, target_x: float, target_y: float) -> tuple[float, float]:
|
|
return (
|
|
target_x - self.viewport_width / 2,
|
|
target_y - self.viewport_height / 2,
|
|
)
|
|
|
|
def _clamp(self, position: tuple[float, float]) -> tuple[float, float]:
|
|
x, y = position
|
|
if self._map_width <= self.viewport_width:
|
|
x = (self._map_width - self.viewport_width) / 2
|
|
else:
|
|
x = min(max(x, 0.0), self._map_width - self.viewport_width)
|
|
if self._map_height <= self.viewport_height:
|
|
y = (self._map_height - self.viewport_height) / 2
|
|
else:
|
|
y = min(max(y, 0.0), self._map_height - self.viewport_height)
|
|
return x, y
|
|
|
|
@property
|
|
def offset(self) -> tuple[int, int]:
|
|
return int(self.x), int(self.y)
|
|
|
|
_map_width: int = 0
|
|
_map_height: int = 0
|
|
|
|
|
|
class ScreenShake:
|
|
"""Decaying trauma; offset magnitude grows with the square of trauma."""
|
|
|
|
def __init__(self) -> None:
|
|
self.trauma = 0.0
|
|
|
|
def add(self, amount: float) -> None:
|
|
self.trauma = min(1.0, self.trauma + amount)
|
|
|
|
def update(self, dt: float) -> None:
|
|
self.trauma = max(0.0, self.trauma - SHAKE_DECAY_PER_S * dt)
|
|
|
|
def offset(self) -> tuple[int, int]:
|
|
if self.trauma <= 0.0:
|
|
return 0, 0
|
|
magnitude = SHAKE_MAX_OFFSET * self.trauma * self.trauma
|
|
return (
|
|
int(random.uniform(-magnitude, magnitude)),
|
|
int(random.uniform(-magnitude, magnitude)),
|
|
)
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class Particle:
|
|
x: float
|
|
y: float
|
|
vx: float
|
|
vy: float
|
|
age: float
|
|
life: float
|
|
size: int
|
|
color: Color
|
|
gravity: float
|
|
|
|
|
|
class Particles:
|
|
"""Pooled world-space pixel bursts, capped so frames stay cheap."""
|
|
|
|
def __init__(self, cap: int = MAX_PARTICLES) -> None:
|
|
self.cap = cap
|
|
self.items: list[Particle] = []
|
|
|
|
def burst(self, x: float, y: float, kind: str, count: int = 6) -> None:
|
|
colors, gravity, speed, life, size = PARTICLE_KINDS[kind]
|
|
for _ in range(count):
|
|
if len(self.items) >= self.cap:
|
|
self.items.pop(0)
|
|
angle = random.uniform(0.0, math.tau)
|
|
velocity = random.uniform(0.4, 1.0) * speed
|
|
self.items.append(
|
|
Particle(
|
|
x=x,
|
|
y=y,
|
|
vx=math.cos(angle) * velocity,
|
|
vy=math.sin(angle) * velocity,
|
|
age=0.0,
|
|
life=life * random.uniform(0.7, 1.3),
|
|
size=size,
|
|
color=random.choice(colors),
|
|
gravity=gravity,
|
|
)
|
|
)
|
|
|
|
def update(self, dt: float) -> None:
|
|
alive: list[Particle] = []
|
|
for particle in self.items:
|
|
particle.age += dt
|
|
if particle.age >= particle.life:
|
|
continue
|
|
particle.vy += particle.gravity * dt
|
|
particle.x += particle.vx * dt
|
|
particle.y += particle.vy * dt
|
|
alive.append(particle)
|
|
self.items = alive
|
|
|
|
def draw(self, surface: pygame.Surface, offset_x: int, offset_y: int) -> None:
|
|
for particle in self.items:
|
|
remaining = 1.0 - particle.age / particle.life
|
|
size = max(1, int(particle.size * remaining + 0.5))
|
|
x = int(particle.x) - offset_x
|
|
y = int(particle.y) - offset_y
|
|
if -size <= x <= surface.get_width() and -size <= y <= surface.get_height():
|
|
pygame.draw.rect(
|
|
surface, particle.color, (x, y, size, size)
|
|
)
|
|
|
|
def clear(self) -> None:
|
|
self.items.clear()
|
|
|
|
def __len__(self) -> int:
|
|
return len(self.items)
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class FloatingText:
|
|
text: str
|
|
color: Color
|
|
x: float
|
|
y: float
|
|
age: float
|
|
|
|
|
|
class FloatingTexts:
|
|
"""Rising, fading combat numbers driven by the message log."""
|
|
|
|
def __init__(self) -> None:
|
|
self.items: list[FloatingText] = []
|
|
|
|
def add(self, text: str, color: Color, x: float, y: float) -> None:
|
|
self.items.append(FloatingText(text, color, x, y, 0.0))
|
|
del self.items[:-16]
|
|
|
|
def update(self, dt: float) -> None:
|
|
for item in self.items:
|
|
item.age += dt
|
|
item.y -= 18.0 * dt
|
|
self.items = [item for item in self.items if item.age < ANIM_TEXT_MS / 1000]
|
|
|
|
def draw(
|
|
self,
|
|
surface: pygame.Surface,
|
|
font: pygame.font.Font,
|
|
offset_x: int,
|
|
offset_y: int,
|
|
) -> None:
|
|
for item in self.items:
|
|
alpha = max(0, min(255, int(255 * (1.0 - item.age / (ANIM_TEXT_MS / 1000)))))
|
|
label = font.render(item.text, False, item.color)
|
|
label.set_alpha(alpha)
|
|
surface.blit(label, (int(item.x) - offset_x, int(item.y) - offset_y))
|
|
|
|
def clear(self) -> None:
|
|
self.items.clear()
|
|
|
|
|
|
_vignettes: dict[tuple[int, int], pygame.Surface] = {}
|
|
_light_tiles: dict[tuple[int, Color, int, int], pygame.Surface] = {}
|
|
|
|
|
|
def vignette(size: tuple[int, int]) -> pygame.Surface:
|
|
"""Soft radial darkening at the screen edges (built once per size)."""
|
|
cached = _vignettes.get(size)
|
|
if cached is not None:
|
|
return cached
|
|
width, height = size
|
|
surface = pygame.Surface(size, pygame.SRCALPHA)
|
|
center_x, center_y = width / 2, height / 2
|
|
max_distance = math.hypot(center_x, center_y)
|
|
inner = max_distance * 0.55
|
|
steps = 48
|
|
for index in range(steps):
|
|
ratio = index / steps
|
|
radius = max_distance * (1.0 - ratio)
|
|
alpha = int(110 * (ratio * ratio))
|
|
if alpha <= 0:
|
|
continue
|
|
color = (0, 0, 0, alpha)
|
|
pygame.draw.circle(
|
|
surface,
|
|
color,
|
|
(int(center_x), int(center_y)),
|
|
int(radius),
|
|
width=max(1, int((max_distance - radius) / (max_distance / steps)) + 2),
|
|
)
|
|
_vignettes[size] = surface
|
|
return surface
|
|
|
|
|
|
def light_tile(
|
|
alpha: int,
|
|
tile_size: int,
|
|
color: Color = (0, 0, 0),
|
|
) -> pygame.Surface:
|
|
"""A cached alpha-darkening square for one torch-light level."""
|
|
alpha = max(0, min(255, alpha // 8 * 8))
|
|
key = (tile_size, color, alpha)
|
|
cached = _light_tiles.get(key)
|
|
if cached is not None:
|
|
return cached
|
|
surface = pygame.Surface((tile_size, tile_size), pygame.SRCALPHA)
|
|
surface.fill((*color, alpha))
|
|
_light_tiles[key] = surface
|
|
return surface
|
|
|
|
|
|
def visible_light_alpha(distance: float, flicker: float = 0.0) -> int:
|
|
"""Torch falloff for a tile the player currently sees."""
|
|
base = min(LIGHT_ALPHA_AT_EDGE, distance * LIGHT_ALPHA_PER_TILE)
|
|
return max(0, min(255, int(base + flicker)))
|
|
|
|
|
|
def explored_light_alpha() -> int:
|
|
return EXPLORED_ALPHA
|
|
|
|
|
|
def explored_tint() -> Color:
|
|
return EXPLORED_TINT
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Run from the repo root: python -m render.effects
|
|
import os
|
|
|
|
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
|
|
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
|
|
pygame.init()
|
|
screen = pygame.display.set_mode((320, 240))
|
|
|
|
camera = Camera((160, 120))
|
|
camera.clamp_bounds(64, 40, 16)
|
|
camera.snap(320, 320)
|
|
offset = camera.offset
|
|
assert 0 <= offset[0] <= 64 * 16 - 160 and 0 <= offset[1] <= 40 * 16 - 120
|
|
camera.update(1000, 700, 0.5)
|
|
moved = camera.offset
|
|
assert moved != offset or camera.offset == offset # eases, never jumps
|
|
camera.update(1000, 700, 10.0)
|
|
settled = camera.offset
|
|
# the eased goal is the CLAMPED center-on-player position, not the raw one
|
|
assert settled == (64 * 16 - 160, 40 * 16 - 120) == (864, 520)
|
|
|
|
small = Camera((400, 300))
|
|
small.clamp_bounds(20, 15, 16) # boss arena: smaller than the viewport
|
|
small.snap(160, 120)
|
|
assert small.offset == (-40, -30) # centered
|
|
|
|
shake = ScreenShake()
|
|
assert shake.offset() == (0, 0)
|
|
shake.add(1.0)
|
|
shake.update(0.1)
|
|
magnitude = SHAKE_MAX_OFFSET * shake.trauma * shake.trauma
|
|
offsets = {shake.offset() for _ in range(20)}
|
|
assert all(
|
|
abs(dx) <= magnitude + 1 and abs(dy) <= magnitude + 1 for dx, dy in offsets
|
|
), "shake must stay within the trauma-squared magnitude"
|
|
assert len(offsets) > 1, "shake must jitter while traumatized"
|
|
shake.update(10.0)
|
|
assert shake.offset() == (0, 0)
|
|
|
|
particles = Particles(cap=10)
|
|
for kind in PARTICLE_KINDS:
|
|
particles.burst(10, 10, kind, count=4)
|
|
assert len(particles) == 10 # capped, not grown
|
|
particles.update(0.001)
|
|
particles.update(10.0)
|
|
assert len(particles) == 0
|
|
|
|
texts = FloatingTexts()
|
|
texts.add("-8", (255, 90, 90), 10, 10)
|
|
texts.update(0.0)
|
|
assert len(texts.items) == 1
|
|
before_y = texts.items[0].y
|
|
texts.update(0.5)
|
|
assert texts.items[0].y < before_y
|
|
texts.update(2.0)
|
|
assert not texts.items
|
|
|
|
screen.fill((0, 0, 0))
|
|
particles.burst(100, 100, "hit", 5)
|
|
particles.draw(screen, 0, 0)
|
|
texts.add("MISS!", (200, 200, 210), 90, 90)
|
|
texts.draw(screen, pygame.font.SysFont(None, 16), 0, 0)
|
|
screen.blit(vignette((320, 240)), (0, 0))
|
|
dark = screen.get_at((3, 3))
|
|
center = screen.get_at((160, 120))
|
|
assert dark[0] < 40 # edges darkened
|
|
assert center[0] >= dark[0]
|
|
|
|
tile = light_tile(visible_light_alpha(4.0), 16)
|
|
assert tile.get_at((8, 8))[3] == visible_light_alpha(4.0)
|
|
assert light_tile(201, 16).get_at((0, 0))[3] == 200 # bucketed to 8s
|
|
remembered = light_tile(explored_light_alpha(), 16, explored_tint())
|
|
assert tuple(remembered.get_at((0, 0)))[:3] == explored_tint()
|
|
|
|
print("render.effects self-check: PASS")
|