use std::collections::{HashMap, HashSet}; use bevy::prelude::*; use crate::{ building::{Blueprints, BuildKind, enclosed_room}, colonist::{Colonist, ColonistAssets, NAMES, spawn_colonist}, economy::in_colony, items::{Item, ItemAssets}, pathfinding::nearest_tile, population::{ColonyLog, MAX_COLONISTS, food_in_store}, rng::SimRng, sim::{SimSystems, SimTick, TICKS_PER_HOUR}, structures::{Structure, StructureKind}, world::{TilePos, WorldMap}, worldgen::WorldGenerated, zones::{Zones, can_zone}, }; pub struct FamilyPlugin; impl Plugin for FamilyPlugin { fn build(&self, app: &mut App) { app.init_resource::() .init_resource::() .add_systems(Update, clear_families.run_if(on_message::)) .add_systems( FixedUpdate, ( plan_homes.in_set(SimSystems::Decide), (bond, births, grow_up).chain().in_set(SimSystems::Act), ), ); } } pub const HOME_INTERIOR: UVec2 = UVec2::new(4, 3); pub const HOME_MIN_DISTANCE: i32 = 6; pub const BOND_RANGE: i32 = 4; pub const BOND_HOURS: u32 = 16; pub const BOND_CHANCE: f32 = 0.2; pub const MAX_CHILDREN: usize = 2; pub const BIRTH_CHANCE: f32 = 0.35; pub const CHILDHOOD_TICKS: u64 = 4 * 24 * TICKS_PER_HOUR; pub const CHILD_SCALE: f32 = 0.6; const BIRTH_HOUR_TICK: u64 = 20 * TICKS_PER_HOUR; const DAY_TICKS: u64 = 24 * TICKS_PER_HOUR; const HOME_PLAN_INTERVAL_TICKS: u64 = 300; const HOME_SEARCH_TILES: usize = 6000; const HOME_CLEARANCE: i32 = 1; #[derive(Component, Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Family(pub u32); #[derive(Component, Clone, Copy, Debug, PartialEq, Eq)] pub struct Partner(pub Entity); #[derive(Component, Clone, Copy, Debug, PartialEq, Eq)] pub struct Child { pub born: u64, } impl Child { pub fn days_left(&self, tick: SimTick) -> u64 { (self.born + CHILDHOOD_TICKS) .saturating_sub(tick.0) .div_ceil(DAY_TICKS) } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Home { pub lo: UVec2, pub hi: UVec2, } impl Home { pub fn at(lo: UVec2) -> Self { Self { lo, hi: lo + HOME_INTERIOR + UVec2::ONE, } } pub fn contains(&self, tile: UVec2) -> bool { tile.cmpge(self.lo).all() && tile.cmple(self.hi).all() } pub fn interior(&self) -> impl Iterator + use<> { let (lo, hi) = (self.lo + UVec2::ONE, self.hi - UVec2::ONE); (lo.y..=hi.y).flat_map(move |y| (lo.x..=hi.x).map(move |x| UVec2::new(x, y))) } pub fn ring(&self) -> impl Iterator + use<> { let (lo, hi) = (self.lo, self.hi); (lo.y..=hi.y) .flat_map(move |y| (lo.x..=hi.x).map(move |x| UVec2::new(x, y))) .filter(move |t| t.x == lo.x || t.x == hi.x || t.y == lo.y || t.y == hi.y) } pub fn bed_tiles(&self) -> [UVec2; 2] { let corner = UVec2::new(self.lo.x + 1, self.hi.y - 1); [corner, corner + UVec2::X] } pub fn blueprints(&self, toward: UVec2) -> HashMap { let corner = |t: &UVec2| { (t.x == self.lo.x || t.x == self.hi.x) && (t.y == self.lo.y || t.y == self.hi.y) }; let door = self .ring() .filter(|t| !corner(t)) .min_by(|a, b| { a.as_vec2() .distance_squared(toward.as_vec2()) .total_cmp(&b.as_vec2().distance_squared(toward.as_vec2())) .then((a.y, a.x).cmp(&(b.y, b.x))) }) .unwrap_or(self.lo); let mut plan: HashMap = self .ring() .map(|t| (t, BuildKind::Structure(StructureKind::Wall))) .collect(); plan.insert(door, BuildKind::Structure(StructureKind::Door)); for bed in self.bed_tiles() { plan.insert(bed, BuildKind::Structure(StructureKind::Bed)); } plan } } #[derive(Resource, Default, Debug)] pub struct Homes { pub by_family: HashMap, next_family: u32, } impl Homes { pub fn new_family(&mut self) -> Family { self.next_family += 1; Family(self.next_family) } pub fn owner(&self, tile: UVec2) -> Option { self.by_family .iter() .find(|(_, home)| home.contains(tile)) .map(|(family, _)| *family) } pub fn of(&self, family: Option) -> Option<&Home> { self.by_family.get(&family?.0) } } #[derive(Resource, Default, Debug)] pub struct Affinity(pub HashMap<(Entity, Entity), u32>); fn clear_families(mut homes: ResMut, mut affinity: ResMut) { homes.by_family.clear(); affinity.0.clear(); } #[derive(Clone, Copy)] pub struct Single { pub entity: Entity, pub tile: UVec2, pub family: Option, } pub fn bond_hour( affinity: &mut Affinity, singles: &[Single], rng: &mut SimRng, ) -> Vec<(Entity, Entity)> { let mut bonded: Vec<(Entity, Entity)> = Vec::new(); let taken = |bonded: &[(Entity, Entity)], e: Entity| bonded.iter().any(|&(a, b)| a == e || b == e); for (i, a) in singles.iter().enumerate() { for b in &singles[i + 1..] { let near = (a.tile.as_ivec2() - b.tile.as_ivec2()).abs().max_element() <= BOND_RANGE; let kin = a.family.is_some() && a.family == b.family; if !near || kin { continue; } let key = (a.entity.min(b.entity), a.entity.max(b.entity)); let hours = affinity.0.entry(key).or_insert(0); *hours += 1; if *hours >= BOND_HOURS && !taken(&bonded, a.entity) && !taken(&bonded, b.entity) && rng.range_f32(0.0..1.0) < BOND_CHANCE { bonded.push(key); } } } for pair in &bonded { affinity .0 .retain(|&(a, b), _| ![a, b].iter().any(|e| *e == pair.0 || *e == pair.1)); } bonded } #[allow(clippy::type_complexity)] fn bond( mut commands: Commands, tick: Res, mut rng: ResMut, mut homes: ResMut, mut affinity: ResMut, mut log: ResMut, colonists: Query<( Entity, &Colonist, &TilePos, Option<&Family>, Option<&Partner>, Has, )>, ) { if !tick.0.is_multiple_of(TICKS_PER_HOUR) { return; } for (entity, _, _, _, partner, _) in &colonists { if let Some(partner) = partner && !colonists.contains(partner.0) { commands.entity(entity).remove::(); } } let singles: Vec = colonists .iter() .filter(|(.., partner, child)| partner.is_none() && !child) .map(|(entity, _, tile, family, ..)| Single { entity, tile: tile.0, family: family.copied(), }) .collect(); for (a, b) in bond_hour(&mut affinity, &singles, &mut rng) { let family = homes.new_family(); commands.entity(a).insert((Partner(b), family)); commands.entity(b).insert((Partner(a), family)); let name = |e: Entity| { colonists .get(e) .map(|c| c.1.name.clone()) .unwrap_or_default() }; log.push( *tick, format!("{} and {} became partners", name(a), name(b)), ); } } pub struct HomeContext<'a> { pub map: &'a WorldMap, pub zones: &'a Zones, pub blueprints: &'a Blueprints, pub homes: &'a Homes, pub occupied: &'a HashSet, } impl HomeContext<'_> { fn claimed(&self, tile: UVec2) -> bool { self.zones.is_stockpile(tile) || self.zones.is_farm(tile) || self.blueprints.get(tile).is_some() || self.homes.owner(tile).is_some() } fn open(&self, tile: IVec2) -> bool { self.map.in_bounds(tile) && can_zone(self.map, tile) && self.map.plant(tile).is_none() && !self.map.is_wall(tile) && !self.occupied.contains(&tile.as_uvec2()) && !self.claimed(tile.as_uvec2()) } fn fits(&self, home: Home) -> bool { let (lo, hi) = (home.lo.as_ivec2(), home.hi.as_ivec2()); let (outer_lo, outer_hi) = (lo - HOME_CLEARANCE, hi + HOME_CLEARANCE); (outer_lo.y..=outer_hi.y).all(|y| { (outer_lo.x..=outer_hi.x).all(|x| { let tile = IVec2::new(x, y); let core = tile.cmpge(lo).all() && tile.cmple(hi).all(); if core { self.open(tile) } else { !self.map.in_bounds(tile) || !self.claimed(tile.as_uvec2()) } }) }) } pub fn plan(&self, colony_home: UVec2) -> Option { let center = (HOME_INTERIOR / 2 + UVec2::ONE).as_ivec2(); let mut found = None; nearest_tile(self.map, colony_home, HOME_SEARCH_TILES, |p| { let lo = p.as_ivec2() - center; if lo.min_element() < 0 { return false; } let home = Home::at(lo.as_uvec2()); let middle = (home.lo + home.hi).as_ivec2() / 2; if (middle - colony_home.as_ivec2()).abs().max_element() < HOME_MIN_DISTANCE { return false; } found = self.fits(home).then_some(home); found.is_some() })?; found } } pub fn roofs_needed(map: &WorldMap, doors: &HashSet, home: &Home) -> Vec { let interior: Vec = home.interior().collect(); let Some(room) = enclosed_room(map, doors, interior[0]) else { return Vec::new(); }; if room.len() != interior.len() { return Vec::new(); } interior .into_iter() .filter(|t| !map.is_roofed(t.as_ivec2())) .collect() } #[allow(clippy::too_many_arguments)] fn plan_homes( tick: Res, map: Res, zones: Res, mut homes: ResMut, mut blueprints: ResMut, structures: Query<(&TilePos, &Structure), Without>, items: Query<&TilePos, With>, families: Query<(&Family, Has), With>, ) { if !tick.0.is_multiple_of(HOME_PLAN_INTERVAL_TICKS) { return; } let living: HashSet = families.iter().map(|(f, _)| f.0).collect(); homes.by_family.retain(|family, _| living.contains(family)); let doors: HashSet = structures .iter() .filter(|(_, s)| s.kind == StructureKind::Door) .map(|(pos, _)| pos.0) .collect(); for home in homes.by_family.values() { if blueprints.0.keys().any(|t| home.contains(*t)) { continue; } for tile in roofs_needed(&map, &doors, home) { blueprints.0.insert(tile, BuildKind::Roof); } } let Some(family) = families .iter() .filter(|(f, partnered)| *partnered && !homes.by_family.contains_key(&f.0)) .map(|(f, _)| f.0) .min() else { return; }; let occupied: HashSet = structures .iter() .map(|(pos, _)| pos.0) .chain(items.iter().map(|pos| pos.0)) .collect(); let colony_home = zones.home(map.size / 2); let ctx = HomeContext { map: &map, zones: &zones, blueprints: &blueprints, homes: &homes, occupied: &occupied, }; if let Some(home) = ctx.plan(colony_home) { blueprints.0.extend(home.blueprints(colony_home)); homes.by_family.insert(family, home); } } #[allow(clippy::too_many_arguments, clippy::type_complexity)] fn births( mut commands: Commands, tick: Res, map: Res, zones: Res, homes: Res, assets: Res, item_assets: Res, mut materials: ResMut>, mut rng: ResMut, mut log: ResMut, items: Query<(&Item, &TilePos)>, structures: Query<(&TilePos, &Structure), Without>, colonists: Query<(&Colonist, Option<&Family>, Has, Has)>, ) { if tick.0 % DAY_TICKS != BIRTH_HOUR_TICK { return; } let count = colonists.iter().count(); let colony_home = zones.home(map.size / 2); let food = food_in_store( items .iter() .filter(|(_, pos)| in_colony(colony_home, pos.0)) .map(|(item, _)| item), ); let mut born = 0; let mut families: Vec<(&u32, &Home)> = homes.by_family.iter().collect(); families.sort_by_key(|(family, _)| **family); for (&family, home) in families { let members = || { colonists .iter() .filter(move |c| c.1 == Some(&Family(family))) }; let parents: Vec<&str> = members() .filter(|c| c.2) .map(|c| c.0.name.as_str()) .collect(); let children = members().filter(|c| c.3).count(); let beds = structures .iter() .filter(|(pos, s)| s.kind == StructureKind::Bed && home.contains(pos.0)) .count(); let built = home.interior().all(|t| map.is_roofed(t.as_ivec2())); let room = count + born < MAX_COLONISTS && food >= (count + born) as f32; if parents.len() < 2 || children >= MAX_CHILDREN || beds < 2 || !built || !room { continue; } if rng.range_f32(0.0..1.0) >= BIRTH_CHANCE { continue; } let taken: Vec<&str> = colonists.iter().map(|c| c.0.name.as_str()).collect(); let index = (0..NAMES.len()) .find(|&i| !taken.contains(&NAMES[i])) .unwrap_or(count); let tile = home .interior() .find(|t| !home.bed_tiles().contains(t)) .unwrap_or(home.lo); let child = spawn_colonist( &mut commands, &assets, &item_assets, &mut materials, index, tile, ); commands.entity(child).insert(( Child { born: tick.0 }, Family(family), Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)) .with_scale(Vec3::splat(CHILD_SCALE)), )); born += 1; log.push( *tick, format!( "{} and {} had a child, {}", parents[0], parents[1], NAMES[index % NAMES.len()] ), ); } } fn grow_up( mut commands: Commands, tick: Res, mut log: ResMut, mut children: Query<(Entity, &Colonist, &Child, &mut Transform)>, ) { if !tick.0.is_multiple_of(TICKS_PER_HOUR) { return; } for (entity, colonist, child, mut transform) in &mut children { if tick.0 < child.born + CHILDHOOD_TICKS { continue; } transform.scale = Vec3::ONE; commands.entity(entity).remove::(); log.push(*tick, format!("{} has grown up", colonist.name)); } } #[cfg(test)] mod tests { use super::*; use crate::world::Terrain; fn singles(app_world: &mut World, tiles: &[UVec2]) -> Vec { tiles .iter() .map(|&tile| Single { entity: app_world.spawn_empty().id(), tile, family: None, }) .collect() } fn bond_for(hours: u32, singles: &[Single]) -> Vec<(Entity, Entity)> { let mut affinity = Affinity::default(); let mut rng = SimRng::new(3); let mut bonded: Vec<(Entity, Entity)> = Vec::new(); for _ in 0..hours { let free: Vec = singles .iter() .filter(|s| !bonded.iter().any(|&(a, b)| a == s.entity || b == s.entity)) .copied() .collect(); bonded.extend(bond_hour(&mut affinity, &free, &mut rng)); } bonded } #[test] fn colonists_who_spend_time_together_become_partners() { let mut world = World::new(); let near = singles(&mut world, &[UVec2::new(5, 5), UVec2::new(6, 7)]); assert!(bond_for(BOND_HOURS - 1, &near).is_empty()); assert_eq!(bond_for(BOND_HOURS * 4, &near).len(), 1); let apart = singles(&mut world, &[UVec2::new(5, 5), UVec2::new(15, 5)]); assert!(bond_for(BOND_HOURS * 4, &apart).is_empty()); } #[test] fn everyone_has_at_most_one_partner_and_family_never_pairs() { let mut world = World::new(); let mut trio = singles(&mut world, &[UVec2::ONE, UVec2::ONE, UVec2::ONE]); let bonded = bond_for(BOND_HOURS * 10, &trio); assert_eq!(bonded.len(), 1); for single in &mut trio { single.family = Some(Family(1)); } assert!(bond_for(BOND_HOURS * 10, &trio).is_empty()); } fn plan_on(map: &WorldMap, zones: &Zones, occupied: &HashSet) -> Home { HomeContext { map, zones, blueprints: &Blueprints::default(), homes: &Homes::default(), occupied, } .plan(UVec2::new(20, 20)) .unwrap() } #[test] fn homes_go_on_open_ground_away_from_the_colony_center() { let mut map = WorldMap::filled(UVec2::splat(40), Terrain::Grass); for x in 0..40 { map.set_plant(UVec2::new(x, 14), Some(crate::world::Plant::Tree)); } let mut zones = Zones::default(); zones.add_tiles(&map, [UVec2::new(20, 20), UVec2::new(21, 20)]); let occupied = HashSet::from([UVec2::new(20, 26)]); let home = plan_on(&map, &zones, &occupied); let center = (home.lo + home.hi).as_ivec2() / 2; assert!((center - IVec2::new(20, 20)).abs().max_element() >= HOME_MIN_DISTANCE); for y in home.lo.y - 1..=home.hi.y + 1 { for x in home.lo.x - 1..=home.hi.x + 1 { let tile = UVec2::new(x, y); assert!(!zones.is_stockpile(tile)); if home.contains(tile) { assert!(map.plant(tile.as_ivec2()).is_none()); assert!(!occupied.contains(&tile)); } } } } #[test] fn a_home_is_a_walled_room_with_a_door_and_two_beds() { let home = Home::at(UVec2::new(10, 10)); let plan = home.blueprints(UVec2::new(12, 0)); let count = |kind: StructureKind| { plan.values() .filter(|k| **k == BuildKind::Structure(kind)) .count() }; let ring = 2 * (HOME_INTERIOR.x + 2) + 2 * HOME_INTERIOR.y; assert_eq!( count(StructureKind::Wall) + count(StructureKind::Door), ring as usize ); assert_eq!(count(StructureKind::Door), 1); assert_eq!(count(StructureKind::Bed), 2); let door = plan .iter() .find(|(_, k)| **k == BuildKind::Structure(StructureKind::Door)) .unwrap() .0; assert_eq!(door.y, home.lo.y); for bed in home.bed_tiles() { assert!(home.interior().any(|t| t == bed)); } } #[test] fn finished_homes_get_a_roof() { let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass); let home = Home::at(UVec2::new(5, 5)); let door = UVec2::new(7, 5); for tile in home.ring().filter(|t| *t != door) { map.set_wall(tile, true); } assert!(roofs_needed(&map, &HashSet::new(), &home).is_empty()); let roofs = roofs_needed(&map, &HashSet::from([door]), &home); assert_eq!(roofs.len(), (HOME_INTERIOR.x * HOME_INTERIOR.y) as usize); } }