use std::{ collections::{HashMap, HashSet}, ops::Range, time::Duration, }; use bevy::prelude::*; use crate::{ colonist::{Colonist, Path, repath}, items::{ CARRY_CAPACITY, Carrying, Item, ItemAssets, ItemKind, ItemQuery, drop_items, room_for, stock, take_items, }, pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_tile}, rng::SimRng, sim::SimSystems, world::{Plant, TileChanged, TilePos, WorldMap}, worldgen::WorldGenerated, zones::Zones, }; pub struct JobsPlugin; impl Plugin for JobsPlugin { fn build(&self, app: &mut App) { app.insert_resource(SimRng::new(0x5EED)) .init_resource::() .init_resource::() .add_message::() .add_message::() .add_systems( Update, ( clear_reservations.run_if(on_message::), handle_orders, ), ) .add_systems(FixedUpdate, choose_jobs.in_set(SimSystems::Decide)) .add_systems(FixedUpdate, run_jobs.in_set(SimSystems::Act)); } } pub const CHOP_TICKS: u32 = 240; pub const WOOD_PER_TREE: u32 = 10; const SEARCH_TILES: usize = 6000; const WANDER_RADIUS: i32 = 8; const IDLE_SECS: Range = 1.0..4.0; const IDLE_AFTER_ORDER_SECS: f32 = 10.0; const WORK_PAUSE_SECS: Range = 0.2..0.8; #[derive(Component, Default, Debug, Clone, PartialEq)] pub struct CurrentJob(pub Option); #[derive(Debug, Clone, Copy, PartialEq)] pub struct Job { pub task: Task, pub ordered: bool, } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Task { MoveTo(UVec2), Chop { tree: UVec2, progress: u32 }, Haul { pickup: Option, to: UVec2 }, } #[derive(Component, Debug)] pub struct IdleTimer(Timer); impl Default for IdleTimer { fn default() -> Self { Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once)) } } impl IdleTimer { fn restart(&mut self, secs: f32) { self.0.set_duration(Duration::from_secs_f32(secs)); self.0.reset(); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Target { Tree(UVec2), Pickup(UVec2), Storage(UVec2), } #[derive(Resource, Default, Debug)] pub struct Reservations(HashMap); impl Reservations { pub fn reserve(&mut self, target: Target, by: Entity) { self.0.insert(target, by); } pub fn holder(&self, target: Target) -> Option { self.0.get(&target).copied() } pub fn is_free(&self, target: Target) -> bool { self.holder(target).is_none() } pub fn release(&mut self, target: Target) { self.0.remove(&target); } pub fn release_all(&mut self, by: Entity) { self.0.retain(|_, holder| *holder != by); } } #[derive(Resource, Debug)] pub struct ColonyGoals { pub wood: u32, } impl Default for ColonyGoals { fn default() -> Self { Self { wood: 50 } } } #[derive(Message, Debug, Clone, Copy)] pub struct Order { pub colonist: Entity, pub tile: UVec2, } fn clear_reservations(mut reservations: ResMut) { reservations.0.clear(); } fn handle_orders( mut orders: MessageReader, map: Res, zones: Res, items: Query<(&Item, &TilePos)>, mut reservations: ResMut, mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob)>, ) { for order in orders.read() { let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else { continue; }; let loose_item = items .iter() .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0)); let task = if map.plant(order.tile.as_ivec2()) == Some(Plant::Tree) { Some(Task::Chop { tree: order.tile, progress: 0, }) } else if let Some((item, _)) = loose_item { find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| { Task::Haul { pickup: Some(order.tile), to, } }) } else { None }; if let Some(task) = task { reservations.release_all(order.colonist); reserve_task(&mut reservations, task, order.colonist); path.0.truncate(1); job.0 = Some(Job { task, ordered: true, }); } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) { reservations.release_all(order.colonist); path.0 = new_path; job.0 = Some(Job { task: Task::MoveTo(order.tile), ordered: true, }); } } } fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) { match task { Task::MoveTo(_) => {} Task::Chop { tree, .. } => reservations.reserve(Target::Tree(tree), by), Task::Haul { pickup, to } => { if let Some(pickup) = pickup { reservations.reserve(Target::Pickup(pickup), by); } reservations.reserve(Target::Storage(to), by); } } } pub fn wood_wanted(goals: &ColonyGoals, in_stock: u32, trees_being_chopped: u32) -> bool { in_stock + trees_being_chopped * WOOD_PER_TREE < goals.wood } pub fn find_tree(map: &WorldMap, reservations: &Reservations, from: UVec2) -> Option { let tree = nearest_tile(map, from, SEARCH_TILES, |p| { map.plant(p.as_ivec2()) == Some(Plant::Tree) && reservations.is_free(Target::Tree(p)) })?; find_path_adjacent(map, from, tree)?; Some(tree) } pub fn find_storage<'a>( map: &WorldMap, zones: &Zones, reservations: &Reservations, items: impl IntoIterator + Clone, from: UVec2, kind: ItemKind, ) -> Option { nearest_tile(map, from, SEARCH_TILES, |p| { zones.is_stockpile(p) && reservations.is_free(Target::Storage(p)) && room_for(items.clone().into_iter(), p, kind) > 0 }) } pub fn find_haul( map: &WorldMap, zones: &Zones, reservations: &Reservations, items: &[(Item, TilePos)], from: UVec2, ) -> Option { let loose: HashSet = items .iter() .map(|(_, pos)| pos.0) .filter(|&p| !zones.is_stockpile(p) && reservations.is_free(Target::Pickup(p))) .collect(); if loose.is_empty() { return None; } let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?; let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?; let refs = items.iter().map(|(i, p)| (i, p)); let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?; Some(Task::Haul { pickup: Some(pickup), to, }) } #[allow(clippy::too_many_arguments)] fn choose_jobs( mut commands: Commands, time: Res