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