use bevy::prelude::*; use crate::{ climate::snow_cover, sim::{SimSystems, SimTick, TICKS_PER_HOUR, hour_of_day}, structures::{Structure, StructureKind}, world::{TilePos, WorldMap}, }; pub struct LightPlugin; impl Plugin for LightPlugin { fn build(&self, app: &mut App) { app.init_resource::() .add_systems(FixedUpdate, update_light_map.in_set(SimSystems::Decide)); } } pub const LIT_BRIGHTNESS: f32 = 0.5; pub const LIGHT_LOOKAHEAD_TICKS: u64 = TICKS_PER_HOUR * 3 / 2; const AMBIENT_STEPS: f32 = 16.0; const DAY_COLOR: Vec3 = Vec3::ONE; const NIGHT_COLOR: Vec3 = Vec3::new(0.2, 0.24, 0.4); pub const ROOF_DAYLIGHT: f32 = 0.3; const SNOW_STEPS: f32 = 8.0; pub fn daylight(hour: f32) -> f32 { match hour { h if h < 5.0 => 0.0, h if h < 7.0 => (h - 5.0) / 2.0, h if h < 18.0 => 1.0, h if h < 20.0 => 1.0 - (h - 18.0) / 2.0, _ => 0.0, } } pub fn ambient_color(daylight: f32) -> Vec3 { NIGHT_COLOR.lerp(DAY_COLOR, daylight) } pub fn brightness(color: Vec3) -> f32 { (color.x + color.y + color.z) / 3.0 } pub fn dark_soon(tick: SimTick) -> bool { let later = SimTick(tick.0 + LIGHT_LOOKAHEAD_TICKS); daylight(hour_of_day(tick)) < LIT_BRIGHTNESS || daylight(hour_of_day(later)) < LIT_BRIGHTNESS } pub fn light_at(kind: StructureKind, source: UVec2, tile: UVec2) -> Vec3 { let Some((radius, color)) = kind.light() else { return Vec3::ZERO; }; let d = source.as_vec2().distance(tile.as_vec2()) / radius; if d >= 1.0 { return Vec3::ZERO; } color * (1.0 - d * d).powi(2) } pub fn line_of_sight(map: &WorldMap, from: UVec2, to: UVec2) -> bool { let (a, b) = (from.as_vec2(), to.as_vec2()); let steps = (b - a).abs().max_element().ceil() as i32; (1..steps).all(|i| { let p = a.lerp(b, i as f32 / steps as f32).round().as_ivec2(); !map.is_wall(p) }) } pub fn light_from(tile: UVec2, sources: impl IntoIterator) -> Vec3 { sources .into_iter() .map(|(pos, kind)| light_at(kind, pos, tile)) .sum() } #[derive(Resource, Default, Debug, Clone, PartialEq)] pub struct LightMap { size: UVec2, ambient_step: u32, ambient: Vec3, indoor_ambient: Vec3, sources: Vec, roofed: Vec, snow_step: u32, } impl LightMap { pub fn color(&self, tile: UVec2) -> Vec3 { if self.sources.is_empty() || tile.x >= self.size.x || tile.y >= self.size.y { return Vec3::ONE; } let index = (tile.y * self.size.x + tile.x) as usize; let ambient = if self.roofed[index] { self.indoor_ambient } else { self.ambient }; (ambient + self.sources[index]).min(Vec3::ONE) } pub fn snow(&self) -> f32 { self.snow_step as f32 / SNOW_STEPS } pub fn with_snow(mut self, cover: f32) -> Self { self.snow_step = (cover * SNOW_STEPS).round() as u32; self } pub fn is_lit(&self, tile: UVec2) -> bool { brightness(self.color(tile)) >= LIT_BRIGHTNESS } pub fn compute( map: &WorldMap, daylight: f32, sources: impl IntoIterator, ) -> Self { let size = map.size; let ambient_step = (daylight * AMBIENT_STEPS).round() as u32; let mut light = vec![Vec3::ZERO; size.element_product() as usize]; for (pos, kind) in sources { let Some((radius, _)) = kind.light() else { continue; }; let r = radius.ceil() as i32; for dy in -r..=r { for dx in -r..=r { let tile = pos.as_ivec2() + IVec2::new(dx, dy); if tile.x < 0 || tile.y < 0 || tile.x >= size.x as i32 || tile.y >= size.y as i32 { continue; } let tile = tile.as_uvec2(); if line_of_sight(map, pos, tile) { light[(tile.y * size.x + tile.x) as usize] += light_at(kind, pos, tile); } } } } let day = ambient_step as f32 / AMBIENT_STEPS; Self { size, ambient_step, ambient: ambient_color(day), indoor_ambient: ambient_color(day * ROOF_DAYLIGHT), sources: light, roofed: map .positions() .map(|p| map.is_roofed(p.as_ivec2())) .collect(), snow_step: 0, } } } fn update_light_map( tick: Res, map: Res, structures: Query<(&TilePos, &Structure)>, added: Query<(), Added>, mut removed: RemovedComponents, mut light: ResMut, mut shape: Local, ) { let day = daylight(hour_of_day(*tick)); let step = (day * AMBIENT_STEPS).round() as u32; let reshaped = map.shape_version() != *shape; *shape = map.shape_version(); let sources_changed = !added.is_empty() || removed.read().count() > 0 || reshaped; let snow = LightMap::default().with_snow(snow_cover(*tick)).snow_step; if !sources_changed && step == light.ambient_step && snow == light.snow_step && light.size == map.size { return; } let fresh = LightMap::compute(&map, day, structures.iter().map(|(pos, s)| (pos.0, s.kind))) .with_snow(snow_cover(*tick)); if fresh != *light { *light = fresh; } } #[cfg(test)] mod tests { use super::*; use crate::{sim::TICKS_PER_HOUR, world::Terrain}; #[test] fn days_are_bright_and_nights_dark_with_gradual_dusk_and_dawn() { assert_eq!(daylight(12.0), 1.0); assert_eq!(daylight(23.0), 0.0); assert_eq!(daylight(2.0), 0.0); assert_eq!(daylight(19.0), 0.5); assert_eq!(daylight(6.0), 0.5); } // Building a fire takes time, so colonists start before it actually gets dark. #[test] fn darkness_is_anticipated_before_dusk() { let at = |hour: u64| SimTick((hour + 24 - 6) % 24 * TICKS_PER_HOUR); assert!(!dark_soon(at(12))); assert!(dark_soon(at(18))); assert!(dark_soon(at(23))); assert!(!dark_soon(at(8))); } #[test] fn fires_light_their_surroundings_with_falloff() { let fire = UVec2::new(10, 10); let near = light_at(StructureKind::Campfire, fire, UVec2::new(11, 10)); let far = light_at(StructureKind::Campfire, fire, UVec2::new(15, 10)); assert!(brightness(near) > brightness(far)); assert_eq!( light_at(StructureKind::Campfire, fire, UVec2::new(17, 10)), Vec3::ZERO ); } #[test] fn light_map_combines_ambient_and_fires() { let fire = (UVec2::new(5, 5), StructureKind::Campfire); let map = WorldMap::filled(UVec2::splat(20), Terrain::Grass); let night = LightMap::compute(&map, 0.0, [fire]); assert!(night.is_lit(UVec2::new(5, 6))); assert!(!night.is_lit(UVec2::new(18, 18))); let day = LightMap::compute(&map, 1.0, []); assert!(day.is_lit(UVec2::new(18, 18))); } #[test] fn walls_cast_shadows_and_roofs_keep_daylight_out() { let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass); for y in 0..20 { map.set_wall(UVec2::new(8, y), true); } map.set_roof(UVec2::new(15, 15), true); let fire = (UVec2::new(6, 10), StructureKind::Campfire); let night = LightMap::compute(&map, 0.0, [fire]); assert!(night.is_lit(UVec2::new(7, 10))); assert!(!night.is_lit(UVec2::new(9, 10))); let day = LightMap::compute(&map, 1.0, []); assert!(day.is_lit(UVec2::new(14, 15))); assert!(!day.is_lit(UVec2::new(15, 15))); } #[test] fn an_empty_light_map_counts_as_daylight() { assert!(LightMap::default().is_lit(UVec2::new(3, 3))); } #[test] fn beds_give_no_light() { let bed = UVec2::new(4, 4); assert_eq!(light_at(StructureKind::Bed, bed, bed), Vec3::ZERO); } // Lighting depends only on walls and roofs. Recomputing it (a full-map pass) on every tile // change made flooring a home, one tile at a time by 20 colonists, halve Max speed. #[test] fn only_walls_and_roofs_change_the_lighting_shape() { let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass); let start = map.shape_version(); map.set(UVec2::ONE, Terrain::WoodFloor); map.set_wall(UVec2::ZERO, false); assert_eq!(map.shape_version(), start); map.set_wall(UVec2::ZERO, true); map.set_roof(UVec2::ONE, true); assert_eq!(map.shape_version(), start + 2); } }