src/jobs/mod.rs 41.9 K · 1241 lines · raw · history

1 use std::{
2 collections::{HashMap, HashSet},
3 ops::Range,
4 time::Duration,
5 };
6
7 use bevy::prelude::*;
8
9 use crate::{
10 animals::{Animal, AnimalKind},
11 building::{Blueprints, BuildKind},
12 colonist::{Colonist, Path, repath},
13 food::{EAT_TICKS, Hunger, STARVING, find_food, portion, wants_food},
14 items::{
15 CARRY_CAPACITY, Carrying, Item, ItemAssets, ItemKind, ItemQuery, drop_items, room_for,
16 stock, take_items,
17 },
18 light::{LIT_BRIGHTNESS, LightMap, brightness, dark_soon, light_from},
19 needs::{EXHAUSTED_REST, Rest, SleepContext, done_sleeping, wants_sleep},
20 pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_tile},
21 rng::SimRng,
22 sim::{SimSystems, SimTick, hour_of_day},
23 structures::{Fuel, Structure, StructureAssets, StructureKind, spawn_structure},
24 world::{Plant, Terrain, TileChanged, TilePos, WorldMap},
25 worldgen::WorldGenerated,
26 zones::{Zones, can_zone, find_stockpile_site, new_stockpile_tiles, plan_expansion},
27 };
28
29 pub struct JobsPlugin;
30
31 impl Plugin for JobsPlugin {
32 fn build(&self, app: &mut App) {
33 app.insert_resource(SimRng::new(0x5EED))
34 .init_resource::<Reservations>()
35 .init_resource::<ColonyGoals>()
36 .add_message::<Order>()
37 .add_message::<TileChanged>()
38 .add_systems(
39 Update,
40 (
41 clear_reservations.run_if(on_message::<WorldGenerated>),
42 handle_orders,
43 ),
44 )
45 .add_systems(FixedUpdate, choose_jobs.in_set(SimSystems::Decide))
46 .add_systems(FixedUpdate, run_jobs.in_set(SimSystems::Act));
47 }
48 }
49
50 pub const EXPAND_WORK: u32 = 240;
51 pub const CAMPFIRE_MIN_FUEL: u32 = 3 * crate::sim::TICKS_PER_HOUR as u32;
52 pub const HOME_RADIUS: f32 = 10.0;
53 pub const BED_STOCKPILE_CLEARANCE: i32 = 3;
54 const LIT_WORK_RATE: u32 = 2;
55 const DARK_WORK_RATE: u32 = 1;
56 pub const EXPANSION_TILES: usize = 8;
57 pub const MIN_EMPTY_STOCKPILE_TILES: usize = 3;
58 const SEARCH_TILES: usize = 15000;
59 const WANDER_RADIUS: i32 = 8;
60 const IDLE_SECS: Range<f32> = 1.0..4.0;
61 const IDLE_AFTER_ORDER_SECS: f32 = 10.0;
62 const WORK_PAUSE_SECS: Range<f32> = 0.2..0.8;
63 const NEIGHBORS: [IVec2; 8] = [
64 IVec2::new(1, 0),
65 IVec2::new(-1, 0),
66 IVec2::new(0, 1),
67 IVec2::new(0, -1),
68 IVec2::new(1, 1),
69 IVec2::new(1, -1),
70 IVec2::new(-1, 1),
71 IVec2::new(-1, -1),
72 ];
73
74 #[derive(Component, Default, Debug, Clone, PartialEq)]
75 pub struct CurrentJob(pub Option<Job>);
76
77 #[derive(Debug, Clone, Copy, PartialEq)]
78 pub struct Job {
79 pub task: Task,
80 pub ordered: bool,
81 }
82
83 #[derive(Debug, Clone, Copy, PartialEq)]
84 pub enum Task {
85 MoveTo(UVec2),
86 Work {
87 site: UVec2,
88 kind: WorkKind,
89 progress: u32,
90 },
91 Haul {
92 pickup: Option<UVec2>,
93 to: UVec2,
94 },
95 ExpandStockpile {
96 site: UVec2,
97 progress: u32,
98 },
99 Build {
100 site: UVec2,
101 kind: BuildKind,
102 pickup: Option<UVec2>,
103 progress: u32,
104 },
105 Sleep {
106 spot: UVec2,
107 },
108 Eat {
109 pickup: Option<UVec2>,
110 progress: u32,
111 },
112 Hunt {
113 animal: Entity,
114 kind: AnimalKind,
115 progress: u32,
116 },
117 }
118
119 pub fn work_rate(light: &LightMap, tile: UVec2) -> u32 {
120 if light.is_lit(tile) {
121 LIT_WORK_RATE
122 } else {
123 DARK_WORK_RATE
124 }
125 }
126
127 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
128 pub enum WorkKind {
129 Chop,
130 Mine,
131 Harvest,
132 }
133
134 impl WorkKind {
135 pub fn work(self) -> u32 {
136 match self {
137 WorkKind::Chop => 480,
138 WorkKind::Mine => 720,
139 WorkKind::Harvest => 240,
140 }
141 }
142
143 fn complete(self, map: &mut WorldMap, site: UVec2) {
144 match self {
145 WorkKind::Chop => map.set_plant(site, None),
146 WorkKind::Mine => map.set(site, Terrain::Gravel),
147 WorkKind::Harvest => {
148 if map.plant(site.as_ivec2()) == Some(Plant::Crop) {
149 map.set_plant(site, None);
150 }
151 map.set_growth(site, 0.0);
152 }
153 }
154 }
155 }
156
157 pub struct SiteWork {
158 pub kind: WorkKind,
159 pub item: ItemKind,
160 pub count: u32,
161 }
162
163 pub fn site_work(map: &WorldMap, site: UVec2) -> Option<SiteWork> {
164 let p = site.as_ivec2();
165 let harvest = |item, count| SiteWork {
166 kind: WorkKind::Harvest,
167 item,
168 count,
169 };
170 match map.plant(p) {
171 Some(Plant::Tree) => {
172 return Some(SiteWork {
173 kind: WorkKind::Chop,
174 item: ItemKind::Wood,
175 count: 10,
176 });
177 }
178 Some(Plant::BerryBush) if map.ripe_plant(p).is_some() => {
179 return Some(harvest(ItemKind::Berries, 8));
180 }
181 Some(Plant::Crop) if map.ripe_plant(p).is_some() => {
182 return Some(harvest(ItemKind::Vegetables, 10));
183 }
184 _ => {}
185 }
186 let (item, count) = match map.get(p)? {
187 Terrain::Stone => (ItemKind::Stone, 10),
188 Terrain::IronOre => (ItemKind::Iron, 10),
189 Terrain::GoldOre => (ItemKind::Gold, 5),
190 _ => return None,
191 };
192 Some(SiteWork {
193 kind: WorkKind::Mine,
194 item,
195 count,
196 })
197 }
198
199 #[derive(Component, Debug)]
200 pub struct IdleTimer(Timer);
201
202 impl Default for IdleTimer {
203 fn default() -> Self {
204 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
205 }
206 }
207
208 impl IdleTimer {
209 fn restart(&mut self, secs: f32) {
210 self.0.set_duration(Duration::from_secs_f32(secs));
211 self.0.reset();
212 }
213 }
214
215 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
216 pub enum Target {
217 Site(UVec2),
218 Pickup(UVec2),
219 Storage(UVec2),
220 StockpileExpansion,
221 SleepSpot(UVec2),
222 Animal(Entity),
223 }
224
225 #[derive(Resource, Default, Debug)]
226 pub struct Reservations(HashMap<Target, Entity>);
227
228 impl Reservations {
229 pub fn reserve(&mut self, target: Target, by: Entity) {
230 self.0.insert(target, by);
231 }
232
233 pub fn holder(&self, target: Target) -> Option<Entity> {
234 self.0.get(&target).copied()
235 }
236
237 pub fn is_free(&self, target: Target) -> bool {
238 self.holder(target).is_none()
239 }
240
241 pub fn release(&mut self, target: Target) {
242 self.0.remove(&target);
243 }
244
245 pub fn release_all(&mut self, by: Entity) {
246 self.0.retain(|_, holder| *holder != by);
247 }
248 }
249
250 #[derive(Resource, Debug, Clone)]
251 pub struct ColonyGoals(pub HashMap<ItemKind, u32>);
252
253 impl Default for ColonyGoals {
254 fn default() -> Self {
255 Self(HashMap::from([
256 (ItemKind::Wood, 50),
257 (ItemKind::Stone, 40),
258 (ItemKind::Iron, 20),
259 (ItemKind::Gold, 10),
260 (ItemKind::Berries, 30),
261 (ItemKind::Meat, 30),
262 (ItemKind::Vegetables, 30),
263 (ItemKind::Meal, 10),
264 ]))
265 }
266 }
267
268 impl ColonyGoals {
269 pub fn goal(&self, kind: ItemKind) -> u32 {
270 self.0.get(&kind).copied().unwrap_or(0)
271 }
272
273 pub fn wanted(&self, kind: ItemKind, in_stock: u32, on_the_way: u32) -> bool {
274 in_stock + on_the_way < self.goal(kind)
275 }
276 }
277
278 #[derive(Message, Debug, Clone, Copy)]
279 pub struct Order {
280 pub colonist: Entity,
281 pub tile: UVec2,
282 }
283
284 fn clear_reservations(mut reservations: ResMut<Reservations>) {
285 reservations.0.clear();
286 }
287
288 fn handle_orders(
289 mut orders: MessageReader<Order>,
290 map: Res<WorldMap>,
291 zones: Res<Zones>,
292 items: Query<(&Item, &TilePos)>,
293 animals: Query<(Entity, &TilePos, &Animal), Without<Colonist>>,
294 mut reservations: ResMut<Reservations>,
295 mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob), With<Colonist>>,
296 ) {
297 for order in orders.read() {
298 let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else {
299 continue;
300 };
301 let loose_item = items
302 .iter()
303 .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0));
304 let animal = animals.iter().find(|(_, pos, _)| pos.0 == order.tile);
305 let task = if let Some((animal, _, a)) = animal {
306 Some(Task::Hunt {
307 animal,
308 kind: a.kind,
309 progress: 0,
310 })
311 } else if let Some(work) = site_work(&map, order.tile) {
312 Some(Task::Work {
313 site: order.tile,
314 kind: work.kind,
315 progress: 0,
316 })
317 } else if let Some((item, _)) = loose_item {
318 find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| {
319 Task::Haul {
320 pickup: Some(order.tile),
321 to,
322 }
323 })
324 } else {
325 None
326 };
327 if let Some(task) = task {
328 reservations.release_all(order.colonist);
329 reserve_task(&mut reservations, task, order.colonist);
330 path.0.truncate(1);
331 job.0 = Some(Job {
332 task,
333 ordered: true,
334 });
335 } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) {
336 reservations.release_all(order.colonist);
337 path.0 = new_path;
338 job.0 = Some(Job {
339 task: Task::MoveTo(order.tile),
340 ordered: true,
341 });
342 }
343 }
344 }
345
346 fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) {
347 match task {
348 Task::MoveTo(_) => {}
349 Task::Work { site, .. } => reservations.reserve(Target::Site(site), by),
350 Task::Haul { pickup, to } => {
351 if let Some(pickup) = pickup {
352 reservations.reserve(Target::Pickup(pickup), by);
353 }
354 reservations.reserve(Target::Storage(to), by);
355 }
356 Task::ExpandStockpile { .. } => reservations.reserve(Target::StockpileExpansion, by),
357 Task::Sleep { spot } => reservations.reserve(Target::SleepSpot(spot), by),
358 Task::Eat { pickup, .. } => {
359 if let Some(pickup) = pickup {
360 reservations.reserve(Target::Pickup(pickup), by);
361 }
362 }
363 Task::Hunt { animal, .. } => reservations.reserve(Target::Animal(animal), by),
364 Task::Build { site, pickup, .. } => {
365 reservations.reserve(Target::Site(site), by);
366 if let Some(pickup) = pickup {
367 reservations.reserve(Target::Pickup(pickup), by);
368 }
369 }
370 }
371 }
372
373 pub fn find_work(
374 map: &WorldMap,
375 reservations: &Reservations,
376 from: UVec2,
377 wanted: impl Fn(ItemKind) -> bool,
378 ) -> Option<Task> {
379 let mut found = None;
380 nearest_tile(map, from, SEARCH_TILES, |stand| {
381 found = NEIGHBORS.iter().find_map(|&d| {
382 let site = stand.as_ivec2() + d;
383 if site.x < 0 || site.y < 0 {
384 return None;
385 }
386 let site = site.as_uvec2();
387 let work = site_work(map, site)?;
388 (wanted(work.item) && reservations.is_free(Target::Site(site))).then_some(Task::Work {
389 site,
390 kind: work.kind,
391 progress: 0,
392 })
393 });
394 found.is_some()
395 })?;
396 found
397 }
398
399 pub fn find_storage<'a>(
400 map: &WorldMap,
401 zones: &Zones,
402 reservations: &Reservations,
403 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)> + Clone,
404 from: UVec2,
405 kind: ItemKind,
406 ) -> Option<UVec2> {
407 nearest_tile(map, from, SEARCH_TILES, |p| {
408 zones.is_stockpile(p)
409 && reservations.is_free(Target::Storage(p))
410 && room_for(items.clone().into_iter(), p, kind) > 0
411 })
412 }
413
414 pub fn find_haul(
415 map: &WorldMap,
416 zones: &Zones,
417 reservations: &Reservations,
418 items: &[(Item, TilePos)],
419 from: UVec2,
420 ) -> Option<Task> {
421 let loose: HashSet<UVec2> = items
422 .iter()
423 .map(|(_, pos)| pos.0)
424 .filter(|&p| !zones.is_stockpile(p) && reservations.is_free(Target::Pickup(p)))
425 .collect();
426 if loose.is_empty() {
427 return None;
428 }
429 let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?;
430 let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?;
431 let refs = items.iter().map(|(i, p)| (i, p));
432 let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?;
433 Some(Task::Haul {
434 pickup: Some(pickup),
435 to,
436 })
437 }
438
439 pub const HUNT_RADIUS: f32 = 60.0;
440
441 pub fn find_hunt(
442 map: &WorldMap,
443 reservations: &Reservations,
444 animals: &[(Entity, UVec2, AnimalKind)],
445 from: UVec2,
446 ) -> Option<Task> {
447 let mut prey: Vec<_> = animals
448 .iter()
449 .filter(|(e, pos, _)| {
450 reservations.is_free(Target::Animal(*e))
451 && pos.as_vec2().distance(from.as_vec2()) <= HUNT_RADIUS
452 })
453 .collect();
454 prey.sort_by(|a, b| {
455 a.1.as_vec2()
456 .distance_squared(from.as_vec2())
457 .total_cmp(&b.1.as_vec2().distance_squared(from.as_vec2()))
458 });
459 prey.into_iter()
460 .find(|(_, pos, _)| find_path_adjacent(map, from, *pos).is_some())
461 .map(|&(animal, _, kind)| Task::Hunt {
462 animal,
463 kind,
464 progress: 0,
465 })
466 }
467
468 pub fn stockpile_too_full(zones: &Zones, items: &[(Item, TilePos)]) -> bool {
469 let occupied: HashSet<UVec2> = items.iter().map(|(_, pos)| pos.0).collect();
470 zones.has_stockpile() && zones.empty_stockpile_tiles(&occupied) < MIN_EMPTY_STOCKPILE_TILES
471 }
472
473 pub fn find_expansion(
474 map: &WorldMap,
475 zones: &Zones,
476 reservations: &Reservations,
477 items: &[(Item, TilePos)],
478 blueprints: &Blueprints,
479 ) -> Option<Task> {
480 if !reservations.is_free(Target::StockpileExpansion) {
481 return None;
482 }
483 let site = if zones.has_stockpile() {
484 if !stockpile_too_full(zones, items) {
485 return None;
486 }
487 *plan_expansion(map, zones, &blueprints.tiles(), EXPANSION_TILES).first()?
488 } else {
489 find_stockpile_site(map, central_item_tile(items)?)?
490 };
491 Some(Task::ExpandStockpile { site, progress: 0 })
492 }
493
494 fn central_item_tile(items: &[(Item, TilePos)]) -> Option<UVec2> {
495 let tiles: Vec<Vec2> = items.iter().map(|(_, pos)| pos.0.as_vec2()).collect();
496 let centroid = tiles.iter().sum::<Vec2>() / tiles.len().max(1) as f32;
497 items.iter().map(|(_, pos)| pos.0).min_by(|a, b| {
498 a.as_vec2()
499 .distance_squared(centroid)
500 .total_cmp(&b.as_vec2().distance_squared(centroid))
501 })
502 }
503
504 pub struct BuildContext<'a> {
505 pub map: &'a WorldMap,
506 pub zones: &'a Zones,
507 pub reservations: &'a Reservations,
508 pub items: &'a [(Item, TilePos)],
509 pub structures: &'a [(UVec2, StructureKind, u32)],
510 pub planned: &'a [(UVec2, StructureKind)],
511 pub blueprints: &'a Blueprints,
512 }
513
514 impl BuildContext<'_> {
515 fn buildable(&self, tile: UVec2) -> bool {
516 can_zone(self.map, tile.as_ivec2())
517 && !self.zones.is_stockpile(tile)
518 && self.map.plant(tile.as_ivec2()).is_none()
519 && !self.structures.iter().any(|(pos, ..)| *pos == tile)
520 && !self.planned.iter().any(|(pos, _)| *pos == tile)
521 && self.blueprints.get(tile).is_none()
522 && !self.items.iter().any(|(_, pos)| pos.0 == tile)
523 && self.reservations.is_free(Target::Site(tile))
524 }
525
526 fn lights(&self) -> impl Iterator<Item = (UVec2, StructureKind)> + Clone + '_ {
527 self.structures
528 .iter()
529 .map(|&(pos, kind, _)| (pos, kind))
530 .chain(self.planned.iter().copied())
531 }
532
533 fn campfire_needed(&self, home: UVec2) -> bool {
534 let burning = self.structures.iter().any(|&(pos, kind, fuel)| {
535 kind == StructureKind::Campfire
536 && fuel >= CAMPFIRE_MIN_FUEL
537 && pos.as_vec2().distance(home.as_vec2()) <= HOME_RADIUS
538 });
539 let planned = self
540 .planned
541 .iter()
542 .any(|(_, kind)| *kind == StructureKind::Campfire);
543 !burning && !planned
544 }
545
546 fn darkest_stockpile_tile(&self, home: UVec2) -> Option<UVec2> {
547 self.zones
548 .stockpile_tiles()
549 .filter(|&t| brightness(light_from(t, self.lights())) < LIT_BRIGHTNESS)
550 .min_by(|a, b| {
551 a.as_vec2()
552 .distance_squared(home.as_vec2())
553 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
554 .then((a.y, a.x).cmp(&(b.y, b.x)))
555 })
556 }
557
558 fn site_near(&self, target: UVec2, max_distance: f32) -> Option<UVec2> {
559 self.site_near_where(target, max_distance, |_| true)
560 }
561
562 fn site_near_where(
563 &self,
564 target: UVec2,
565 max_distance: f32,
566 extra: impl Fn(UVec2) -> bool,
567 ) -> Option<UVec2> {
568 nearest_tile(self.map, target, SEARCH_TILES, |p| {
569 self.buildable(p) && extra(p)
570 })
571 .filter(|site| site.as_vec2().distance(target.as_vec2()) <= max_distance)
572 }
573
574 fn clear_of_stockpile(&self, tile: UVec2) -> bool {
575 self.zones.stockpile_tiles().all(|s| {
576 (s.as_ivec2() - tile.as_ivec2()).abs().max_element() >= BED_STOCKPILE_CLEARANCE
577 })
578 }
579
580 fn count(&self, kind: StructureKind) -> usize {
581 let built = self.structures.iter().filter(|s| s.1 == kind).count();
582 built + self.planned.iter().filter(|p| p.1 == kind).count()
583 }
584
585 fn bed_anchor(&self, home: UVec2) -> UVec2 {
586 let positions = |kind: StructureKind| {
587 let built = self.structures.iter().map(|s| (s.0, s.1));
588 built
589 .chain(self.planned.iter().copied())
590 .filter(move |s| s.1 == kind)
591 .map(|s| s.0)
592 };
593 let nearest = |kind: StructureKind| {
594 positions(kind).min_by(|a, b| {
595 a.as_vec2()
596 .distance_squared(home.as_vec2())
597 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
598 })
599 };
600 nearest(StructureKind::Bed)
601 .or_else(|| nearest(StructureKind::Campfire))
602 .unwrap_or(home)
603 }
604
605 fn material_source(&self, from: UVec2, (kind, amount): (ItemKind, u32)) -> Option<UVec2> {
606 nearest_tile(self.map, from, SEARCH_TILES, |p| {
607 self.reservations.is_free(Target::Pickup(p))
608 && self
609 .items
610 .iter()
611 .any(|(item, pos)| pos.0 == p && item.kind == kind && item.count >= amount)
612 })
613 }
614
615 fn build_task(&self, from: UVec2, site: UVec2, kind: BuildKind) -> Option<Task> {
616 let pickup = self.material_source(from, kind.cost())?;
617 Some(Task::Build {
618 site,
619 kind,
620 pickup: Some(pickup),
621 progress: 0,
622 })
623 }
624 }
625
626 pub fn find_lighting(ctx: &BuildContext, from: UVec2) -> Option<Task> {
627 let home = ctx.zones.home(from);
628 let (kind, site) = if ctx.campfire_needed(home) {
629 (StructureKind::Campfire, ctx.site_near(home, HOME_RADIUS)?)
630 } else {
631 let dark = ctx.darkest_stockpile_tile(home)?;
632 let reach = StructureKind::Torch.radius() * 0.6;
633 (StructureKind::Torch, ctx.site_near(dark, reach)?)
634 };
635 ctx.build_task(from, site, BuildKind::Structure(kind))
636 }
637
638 pub fn find_bed_site(ctx: &BuildContext, colonists: usize, from: UVec2) -> Option<Task> {
639 if ctx.count(StructureKind::Bed) >= colonists {
640 return None;
641 }
642 let anchor = ctx.bed_anchor(ctx.zones.home(from));
643 let site = ctx.site_near_where(anchor, HOME_RADIUS * 1.5, |p| ctx.clear_of_stockpile(p))?;
644 ctx.build_task(from, site, BuildKind::Structure(StructureKind::Bed))
645 }
646
647 pub fn find_blueprint_work(ctx: &BuildContext, from: UVec2) -> Option<Task> {
648 let mut found = None;
649 nearest_tile(ctx.map, from, SEARCH_TILES, |p| {
650 let Some(kind) = ctx.blueprints.get(p) else {
651 return false;
652 };
653 if !ctx.reservations.is_free(Target::Site(p)) {
654 return false;
655 }
656 found = ctx.build_task(from, p, kind);
657 found.is_some()
658 })?;
659 found
660 }
661
662 fn on_the_way(map: &WorldMap, jobs: impl Iterator<Item = Option<Job>>) -> HashMap<ItemKind, u32> {
663 let mut totals = HashMap::new();
664 for job in jobs.flatten() {
665 if let Task::Work { site, .. } = job.task
666 && let Some(work) = site_work(map, site)
667 {
668 *totals.entry(work.item).or_insert(0) += work.count;
669 }
670 }
671 totals
672 }
673
674 #[allow(clippy::too_many_arguments)]
675 fn choose_jobs(
676 mut commands: Commands,
677 time: Res<Time>,
678 map: Res<WorldMap>,
679 zones: Res<Zones>,
680 goals: Res<ColonyGoals>,
681 item_assets: Res<ItemAssets>,
682 tick: Res<SimTick>,
683 blueprints: Res<Blueprints>,
684 mut rng: ResMut<SimRng>,
685 mut reservations: ResMut<Reservations>,
686 mut items: ItemQuery,
687 structures: Query<(&TilePos, &Structure, Option<&Fuel>), Without<Colonist>>,
688 animals: Query<(Entity, &TilePos, &Animal), Without<Colonist>>,
689 mut colonists: Query<
690 (
691 Entity,
692 &TilePos,
693 &mut Path,
694 &mut CurrentJob,
695 &mut IdleTimer,
696 &mut Carrying,
697 &Rest,
698 &Hunger,
699 ),
700 With<Colonist>,
701 >,
702 ) {
703 let wildlife: Vec<(Entity, UVec2, AnimalKind)> = animals
704 .iter()
705 .map(|(e, pos, a)| (e, pos.0, a.kind))
706 .collect();
707 let colonist_count = colonists.iter().count();
708 let structures_list: Vec<(UVec2, StructureKind, u32)> = structures
709 .iter()
710 .map(|(pos, s, fuel)| (pos.0, s.kind, fuel.map_or(u32::MAX, |f| f.0)))
711 .collect();
712 let mut planned: Vec<(UVec2, StructureKind)> = colonists
713 .iter()
714 .filter_map(|c| match c.3.0?.task {
715 Task::Build {
716 site,
717 kind: BuildKind::Structure(kind),
718 ..
719 } => Some((site, kind)),
720 _ => None,
721 })
722 .collect();
723 let dark = dark_soon(*tick);
724 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
725 let stocks: HashMap<ItemKind, u32> = ItemKind::ALL
726 .iter()
727 .map(|&kind| {
728 let all = items.iter().map(|(_, item, _)| item).chain(carried.iter());
729 (kind, stock(all, kind))
730 })
731 .collect();
732 let mut pending = on_the_way(&map, colonists.iter().map(|c| c.3.0));
733 for job in colonists.iter().filter_map(|c| c.3.0) {
734 if let Task::Hunt { kind, .. } = job.task {
735 *pending.entry(ItemKind::Meat).or_insert(0) += kind.meat();
736 }
737 }
738 let hour = hour_of_day(*tick);
739 for (entity, tile, mut path, mut job, mut idle, mut carrying, rest, hunger) in &mut colonists {
740 let exhausted = rest.0 < EXHAUSTED_REST;
741 let starving = hunger.0 < STARVING;
742 let urgent = exhausted || starving;
743 if urgent
744 && job.0.is_some_and(|j| {
745 !j.ordered && !matches!(j.task, Task::Sleep { .. } | Task::Eat { .. })
746 })
747 {
748 reservations.release_all(entity);
749 job.0 = None;
750 path.0.truncate(1);
751 }
752 let rested = idle.0.tick(time.delta()).is_finished();
753 if job.0.is_some() || !path.0.is_empty() || !(rested || urgent) {
754 continue;
755 }
756 let snapshot: Vec<(Item, TilePos)> =
757 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
758 let refs = snapshot.iter().map(|(i, p)| (i, p));
759 let wanted = |kind: ItemKind| {
760 goals.wanted(
761 kind,
762 stocks[&kind],
763 pending.get(&kind).copied().unwrap_or(0),
764 )
765 };
766 let sleep = SleepContext {
767 map: &map,
768 zones: &zones,
769 reservations: &reservations,
770 items: &snapshot,
771 structures: &structures_list,
772 blueprints: &blueprints,
773 };
774 let food = wants_food(hunger.0)
775 .then(|| find_food(&map, &reservations, &snapshot, tile.0))
776 .flatten();
777 let task = if exhausted {
778 Some(Task::Sleep {
779 spot: sleep.spot(tile.0),
780 })
781 } else if let Some(pickup) = food {
782 if let Some(load) = carrying.0.take() {
783 drop_items(
784 &mut commands,
785 &mut items,
786 &item_assets,
787 tile.0,
788 load.kind,
789 load.count,
790 );
791 }
792 Some(Task::Eat {
793 pickup: Some(pickup),
794 progress: 0,
795 })
796 } else if wants_sleep(rest.0, hour) {
797 Some(Task::Sleep {
798 spot: sleep.spot(tile.0),
799 })
800 } else if let Some(load) = carrying.0 {
801 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
802 if storage.is_none() {
803 drop_items(
804 &mut commands,
805 &mut items,
806 &item_assets,
807 tile.0,
808 load.kind,
809 load.count,
810 );
811 carrying.0 = None;
812 }
813 storage.map(|to| Task::Haul { pickup: None, to })
814 } else {
815 let build = BuildContext {
816 map: &map,
817 zones: &zones,
818 reservations: &reservations,
819 items: &snapshot,
820 structures: &structures_list,
821 planned: &planned,
822 blueprints: &blueprints,
823 };
824 find_expansion(&map, &zones, &reservations, &snapshot, &blueprints)
825 .or_else(|| dark.then(|| find_lighting(&build, tile.0)).flatten())
826 .or_else(|| find_work(&map, &reservations, tile.0, wanted))
827 .or_else(|| {
828 wanted(ItemKind::Meat)
829 .then(|| find_hunt(&map, &reservations, &wildlife, tile.0))
830 .flatten()
831 })
832 .or_else(|| find_haul(&map, &zones, &reservations, &snapshot, tile.0))
833 .or_else(|| find_bed_site(&build, colonist_count, tile.0))
834 .or_else(|| find_blueprint_work(&build, tile.0))
835 };
836 if let Some(task) = task {
837 if let Task::Work { site, .. } = task
838 && let Some(work) = site_work(&map, site)
839 {
840 *pending.entry(work.item).or_insert(0) += work.count;
841 }
842 if let Task::Hunt { kind, .. } = task {
843 *pending.entry(ItemKind::Meat).or_insert(0) += kind.meat();
844 }
845 if let Task::Build {
846 site,
847 kind: BuildKind::Structure(kind),
848 ..
849 } = task
850 {
851 planned.push((site, kind));
852 }
853 reserve_task(&mut reservations, task, entity);
854 job.0 = Some(Job {
855 task,
856 ordered: false,
857 });
858 continue;
859 }
860 let goal = tile.0.as_ivec2()
861 + IVec2::new(
862 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
863 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
864 );
865 if map.in_bounds(goal)
866 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
867 {
868 path.0 = wander_path.into();
869 idle.restart(rng.range_f32(IDLE_SECS));
870 }
871 }
872 }
873
874 enum Step {
875 Continue,
876 Done,
877 }
878
879 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
880 match find_path(map, from, to) {
881 Some(p) if !p.is_empty() => {
882 path.0 = p.into();
883 Step::Continue
884 }
885 _ => Step::Done,
886 }
887 }
888
889 #[allow(clippy::too_many_arguments)]
890 fn run_jobs(
891 mut commands: Commands,
892 mut map: ResMut<WorldMap>,
893 mut zones: ResMut<Zones>,
894 mut reservations: ResMut<Reservations>,
895 mut rng: ResMut<SimRng>,
896 item_assets: Res<ItemAssets>,
897 structure_assets: Res<StructureAssets>,
898 light: Res<LightMap>,
899 tick: Res<SimTick>,
900 mut blueprints: ResMut<Blueprints>,
901 mut items: ItemQuery,
902 structures: Query<&TilePos, (With<Structure>, Without<Colonist>)>,
903 animals: Query<&TilePos, (With<Animal>, Without<Colonist>)>,
904 mut changed: MessageWriter<TileChanged>,
905 mut colonists: Query<
906 (
907 Entity,
908 &TilePos,
909 &mut Path,
910 &mut CurrentJob,
911 &mut IdleTimer,
912 &mut Carrying,
913 &Rest,
914 &mut Hunger,
915 ),
916 With<Colonist>,
917 >,
918 ) {
919 let hour = hour_of_day(*tick);
920 let occupied: Vec<UVec2> = colonists.iter().map(|c| c.1.0).collect();
921 for (entity, tile, mut path, mut current, mut idle, mut carrying, rest, mut hunger) in
922 &mut colonists
923 {
924 let Some(mut job) = current.0 else {
925 continue;
926 };
927 if !path.0.is_empty() {
928 continue;
929 }
930 let step = match &mut job.task {
931 Task::MoveTo(_) => Step::Done,
932 Task::Hunt {
933 animal,
934 kind,
935 progress,
936 } => match animals.get(*animal) {
937 Ok(prey) if reservations.holder(Target::Animal(*animal)) == Some(entity) => {
938 let prey = prey.0;
939 if prey != tile.0 && !is_adjacent(tile.0.as_ivec2(), prey.as_ivec2()) {
940 match find_path_adjacent(&map, tile.0, prey) {
941 Some(p) if !p.is_empty() => {
942 path.0 = p.into();
943 Step::Continue
944 }
945 _ => Step::Done,
946 }
947 } else {
948 *progress += work_rate(&light, tile.0);
949 if *progress < kind.hunt_work() {
950 Step::Continue
951 } else {
952 commands.entity(*animal).despawn();
953 drop_items(
954 &mut commands,
955 &mut items,
956 &item_assets,
957 prey,
958 ItemKind::Meat,
959 kind.meat(),
960 );
961 Step::Done
962 }
963 }
964 }
965 _ => Step::Done,
966 },
967 Task::Eat { pickup, progress } => {
968 if let Some(from) = *pickup {
969 if reservations.holder(Target::Pickup(from)) != Some(entity) {
970 Step::Done
971 } else if tile.0 != from {
972 walk_to(&map, tile.0, from, &mut path)
973 } else {
974 let kind = items
975 .iter()
976 .find(|(_, item, pos)| pos.0 == from && item.kind.is_food())
977 .map(|(_, item, _)| item.kind);
978 let meal = kind.and_then(|kind| {
979 take_items(&mut commands, &mut items, from, portion(kind, hunger.0))
980 });
981 reservations.release(Target::Pickup(from));
982 match meal.filter(|m| m.kind.is_food()) {
983 Some(meal) => {
984 carrying.0 = Some(meal);
985 *pickup = None;
986 Step::Continue
987 }
988 None => Step::Done,
989 }
990 }
991 } else if let Some(meal) = carrying.0.filter(|m| m.kind.is_food()) {
992 *progress += 1;
993 if *progress < EAT_TICKS {
994 Step::Continue
995 } else {
996 hunger.0 = (hunger.0 + meal.count as f32 * meal.kind.nutrition()).min(1.0);
997 carrying.0 = None;
998 Step::Done
999 }
1000 } else {
1001 Step::Done
1002 }
1003 }
1004 Task::Sleep { spot } => {
1005 if reservations.holder(Target::SleepSpot(*spot)) != Some(entity) {
1006 Step::Done
1007 } else if tile.0 != *spot {
1008 let step = walk_to(&map, tile.0, *spot, &mut path);
1009 if matches!(step, Step::Done) {
1010 reservations.release(Target::SleepSpot(*spot));
1011 *spot = tile.0;
1012 reservations.reserve(Target::SleepSpot(*spot), entity);
1013 }
1014 Step::Continue
1015 } else if done_sleeping(rest.0, hour) {
1016 Step::Done
1017 } else {
1018 Step::Continue
1019 }
1020 }
1021 Task::Work {
1022 site,
1023 kind,
1024 progress,
1025 } => {
1026 let (site, kind) = (*site, *kind);
1027 let work = site_work(&map, site).filter(|w| w.kind == kind);
1028 let ours = reservations.holder(Target::Site(site)) == Some(entity);
1029 match work {
1030 Some(work) if ours => {
1031 if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
1032 match find_path_adjacent(&map, tile.0, site) {
1033 Some(p) if !p.is_empty() => {
1034 path.0 = p.into();
1035 Step::Continue
1036 }
1037 _ => Step::Done,
1038 }
1039 } else {
1040 *progress += work_rate(&light, tile.0);
1041 if *progress < kind.work() {
1042 Step::Continue
1043 } else {
1044 kind.complete(&mut map, site);
1045 changed.write(TileChanged(site));
1046 drop_items(
1047 &mut commands,
1048 &mut items,
1049 &item_assets,
1050 site,
1051 work.item,
1052 work.count,
1053 );
1054 Step::Done
1055 }
1056 }
1057 }
1058 _ => Step::Done,
1059 }
1060 }
1061 Task::ExpandStockpile { site, progress } => {
1062 if tile.0 != *site {
1063 walk_to(&map, tile.0, *site, &mut path)
1064 } else {
1065 *progress += work_rate(&light, tile.0);
1066 if *progress >= EXPAND_WORK {
1067 if zones.has_stockpile() {
1068 let excluded = blueprints.tiles();
1069 let tiles = plan_expansion(&map, &zones, &excluded, EXPANSION_TILES);
1070 zones.add_tiles(&map, tiles);
1071 } else {
1072 zones.add_tiles(&map, new_stockpile_tiles(*site));
1073 }
1074 Step::Done
1075 } else {
1076 Step::Continue
1077 }
1078 }
1079 }
1080 Task::Build {
1081 site,
1082 kind,
1083 pickup,
1084 progress,
1085 } => {
1086 let (site, kind) = (*site, *kind);
1087 let ours = reservations.holder(Target::Site(site)) == Some(entity);
1088 let planned = match kind {
1089 BuildKind::Structure(
1090 StructureKind::Campfire | StructureKind::Torch | StructureKind::Bed,
1091 ) => true,
1092 _ => blueprints.get(site) == Some(kind),
1093 };
1094 let blocked = map.plant(site.as_ivec2()).is_some()
1095 || (kind != BuildKind::Roof && structures.iter().any(|pos| pos.0 == site));
1096 let (material, cost) = kind.cost();
1097 if !ours || blocked || !planned {
1098 Step::Done
1099 } else if let Some(from) = *pickup {
1100 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1101 Step::Done
1102 } else if tile.0 != from {
1103 walk_to(&map, tile.0, from, &mut path)
1104 } else {
1105 let load = take_items(&mut commands, &mut items, from, cost)
1106 .filter(|load| load.kind == material && load.count > 0);
1107 carrying.0 = load;
1108 match load {
1109 Some(load) if load.count >= cost => {
1110 reservations.release(Target::Pickup(from));
1111 *pickup = None;
1112 Step::Continue
1113 }
1114 _ => Step::Done,
1115 }
1116 }
1117 } else if !carrying
1118 .0
1119 .is_some_and(|load| load.kind == material && load.count >= cost)
1120 {
1121 Step::Done
1122 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
1123 match find_path_adjacent(&map, tile.0, site) {
1124 Some(p) if !p.is_empty() => {
1125 path.0 = p.into();
1126 Step::Continue
1127 }
1128 _ => Step::Done,
1129 }
1130 } else {
1131 *progress = (*progress + work_rate(&light, tile.0)).min(kind.work());
1132 let someone_in_the_way = kind.blocks_tile() && occupied.contains(&site);
1133 if *progress < kind.work() || someone_in_the_way {
1134 Step::Continue
1135 } else {
1136 carrying.0 = carrying.0.and_then(|load| {
1137 (load.count > cost).then_some(Item {
1138 count: load.count - cost,
1139 ..load
1140 })
1141 });
1142 match kind {
1143 BuildKind::Structure(structure) => {
1144 spawn_structure(&mut commands, &structure_assets, site, structure);
1145 if kind.blocks_tile() {
1146 map.set_wall(site, true);
1147 changed.write(TileChanged(site));
1148 }
1149 }
1150 BuildKind::Roof => {
1151 map.set_roof(site, true);
1152 changed.write(TileChanged(site));
1153 }
1154 }
1155 blueprints.0.remove(&site);
1156 Step::Done
1157 }
1158 }
1159 }
1160 Task::Haul { pickup, to } => {
1161 let to = *to;
1162 let destination_valid = zones.is_stockpile(to)
1163 && reservations.holder(Target::Storage(to)) == Some(entity);
1164 if !destination_valid {
1165 Step::Done
1166 } else if let Some(from) = *pickup {
1167 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1168 Step::Done
1169 } else if tile.0 != from {
1170 walk_to(&map, tile.0, from, &mut path)
1171 } else {
1172 let kind = items
1173 .iter()
1174 .find(|(_, _, pos)| pos.0 == from)
1175 .map(|(_, item, _)| item.kind);
1176 let room = kind.map_or(0, |kind| {
1177 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
1178 });
1179 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
1180 .filter(|load| load.count > 0)
1181 {
1182 Some(load) => {
1183 carrying.0 = Some(load);
1184 reservations.release(Target::Pickup(from));
1185 *pickup = None;
1186 Step::Continue
1187 }
1188 None => Step::Done,
1189 }
1190 }
1191 } else if let Some(load) = carrying.0 {
1192 if tile.0 != to {
1193 walk_to(&map, tile.0, to, &mut path)
1194 } else {
1195 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
1196 let dropped = load.count.min(room);
1197 if dropped > 0 {
1198 drop_items(
1199 &mut commands,
1200 &mut items,
1201 &item_assets,
1202 to,
1203 load.kind,
1204 dropped,
1205 );
1206 }
1207 carrying.0 = (load.count > dropped).then_some(Item {
1208 count: load.count - dropped,
1209 ..load
1210 });
1211 Step::Done
1212 }
1213 } else {
1214 Step::Done
1215 }
1216 }
1217 };
1218 match step {
1219 Step::Continue => current.0 = Some(job),
1220 Step::Done => {
1221 reservations.release_all(entity);
1222 current.0 = None;
1223 let ordered_move = matches!(
1224 job,
1225 Job {
1226 task: Task::MoveTo(_),
1227 ordered: true
1228 }
1229 );
1230 idle.restart(if ordered_move {
1231 IDLE_AFTER_ORDER_SECS
1232 } else {
1233 rng.range_f32(WORK_PAUSE_SECS)
1234 });
1235 }
1236 }
1237 }
1238 }
1239
1240 #[cfg(test)]
1241 mod tests;