src/jobs/mod.rs 65.8 K · 1899 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, MAX_TAME, Tame},
11 building::{Blueprints, BuildKind},
12 climate::{COLD_TEMP, WARM_TEMP, Warmth, outdoor_temperature, sowing_season, tile_temperature},
13 colonist::{Colonist, Path, repath},
14 designations::Designations,
15 economy::{ColonyGoals, in_colony},
16 family::{Child, Family, Homes},
17 food::{EAT_TICKS, Hunger, STARVING, find_food, portion, wants_food},
18 items::{
19 CARRY_CAPACITY, Carrying, Item, ItemAssets, ItemKind, ItemQuery, STACK_LIMIT, drop_items,
20 room_for, stock, take_items,
21 },
22 light::{
23 LIGHT_LOOKAHEAD_TICKS, LIT_BRIGHTNESS, LightMap, brightness, dark_soon, light_from,
24 line_of_sight,
25 },
26 mood::{Ate, Sick},
27 needs::{EXHAUSTED_REST, Rest, SleepContext, done_sleeping, wants_sleep},
28 pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_of, nearest_tile},
29 rng::SimRng,
30 sim::{SimSystems, SimTick, hour_of_day},
31 structures::{Fuel, Structure, StructureAssets, StructureKind, spawn_structure},
32 world::{Plant, Terrain, TileChanged, TilePos, WorldMap},
33 worldgen::WorldGenerated,
34 zones::{
35 StoragePriority, Zones, can_zone, find_stockpile_site, new_stockpile_tiles, plan_expansion,
36 },
37 };
38
39 pub struct JobsPlugin;
40
41 impl Plugin for JobsPlugin {
42 fn build(&self, app: &mut App) {
43 app.insert_resource(SimRng::new(0x5EED))
44 .init_resource::<Reservations>()
45 .add_message::<Order>()
46 .add_message::<TileChanged>()
47 .add_systems(
48 Update,
49 (
50 clear_reservations.run_if(on_message::<WorldGenerated>),
51 handle_orders,
52 ),
53 )
54 .add_systems(FixedUpdate, choose_jobs.in_set(SimSystems::Decide))
55 .add_systems(FixedUpdate, run_jobs.in_set(SimSystems::Act));
56 }
57 }
58
59 pub const EXPAND_WORK: u32 = 240;
60 pub const REFUEL_BELOW_SHARE: u32 = 3;
61 pub const CAMPFIRE_MIN_FUEL: u32 = 3 * crate::sim::TICKS_PER_HOUR as u32;
62 pub const HOME_RADIUS: f32 = 10.0;
63 pub const BED_STOCKPILE_CLEARANCE: i32 = 3;
64 const LIT_WORK_RATE: u32 = 2;
65 const DARK_WORK_RATE: u32 = 1;
66 pub const EXPANSION_TILES: usize = 8;
67 pub const MIN_EMPTY_STOCKPILE_TILES: usize = 3;
68 const SEARCH_TILES: usize = 15000;
69 const FORAGE_SEARCH_TILES: usize = 5000;
70 const WANDER_RADIUS: i32 = 8;
71 const IDLE_SECS: Range<f32> = 1.0..4.0;
72 const IDLE_AFTER_ORDER_SECS: f32 = 10.0;
73 const WORK_PAUSE_SECS: Range<f32> = 0.2..0.8;
74 const NEIGHBORS: [IVec2; 8] = [
75 IVec2::new(1, 0),
76 IVec2::new(-1, 0),
77 IVec2::new(0, 1),
78 IVec2::new(0, -1),
79 IVec2::new(1, 1),
80 IVec2::new(1, -1),
81 IVec2::new(-1, 1),
82 IVec2::new(-1, -1),
83 ];
84
85 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
86 pub enum WorkType {
87 Food,
88 Build,
89 Gather,
90 Haul,
91 Tame,
92 }
93
94 impl WorkType {
95 pub const ALL: [WorkType; 5] = [
96 WorkType::Food,
97 WorkType::Build,
98 WorkType::Gather,
99 WorkType::Haul,
100 WorkType::Tame,
101 ];
102
103 pub fn label(self) -> &'static str {
104 match self {
105 WorkType::Food => "Food",
106 WorkType::Build => "Build",
107 WorkType::Gather => "Gather",
108 WorkType::Haul => "Haul",
109 WorkType::Tame => "Tame",
110 }
111 }
112 }
113
114 #[derive(Component, Default, Debug, Clone, PartialEq, Eq)]
115 pub struct WorkPriorities {
116 disabled: Vec<WorkType>,
117 }
118
119 impl WorkPriorities {
120 pub fn allows(&self, work: WorkType) -> bool {
121 !self.disabled.contains(&work)
122 }
123
124 pub fn toggle(&mut self, work: WorkType) {
125 if self.allows(work) {
126 self.disabled.push(work);
127 } else {
128 self.disabled.retain(|w| *w != work);
129 }
130 }
131 }
132
133 #[derive(Component, Default, Debug, Clone, PartialEq)]
134 pub struct CurrentJob(pub Option<Job>);
135
136 #[derive(Debug, Clone, Copy, PartialEq)]
137 pub struct Job {
138 pub task: Task,
139 pub ordered: bool,
140 }
141
142 #[derive(Debug, Clone, Copy, PartialEq)]
143 pub enum Task {
144 MoveTo(UVec2),
145 Work {
146 site: UVec2,
147 kind: WorkKind,
148 progress: u32,
149 },
150 Haul {
151 pickup: Option<UVec2>,
152 to: UVec2,
153 },
154 ExpandStockpile {
155 site: UVec2,
156 progress: u32,
157 },
158 Build {
159 site: UVec2,
160 kind: BuildKind,
161 pickup: Option<UVec2>,
162 progress: u32,
163 },
164 Sleep {
165 spot: UVec2,
166 },
167 Eat {
168 pickup: Option<UVec2>,
169 progress: u32,
170 },
171 Hunt {
172 animal: Entity,
173 kind: AnimalKind,
174 progress: u32,
175 },
176 Cook {
177 pickup: Option<UVec2>,
178 station: UVec2,
179 progress: u32,
180 },
181 Butcher {
182 site: UVec2,
183 progress: u32,
184 },
185 Tame {
186 animal: Entity,
187 kind: AnimalKind,
188 progress: u32,
189 },
190 }
191
192 pub fn work_rate(light: &LightMap, tile: UVec2) -> u32 {
193 if light.is_lit(tile) {
194 LIT_WORK_RATE
195 } else {
196 DARK_WORK_RATE
197 }
198 }
199
200 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
201 pub enum WorkKind {
202 Chop,
203 Mine,
204 Harvest,
205 Sow,
206 }
207
208 impl WorkKind {
209 pub fn work(self) -> u32 {
210 match self {
211 WorkKind::Chop => 480,
212 WorkKind::Mine => 720,
213 WorkKind::Harvest => 240,
214 WorkKind::Sow => 160,
215 }
216 }
217
218 fn complete(self, map: &mut WorldMap, site: UVec2) {
219 match self {
220 WorkKind::Chop => map.set_plant(site, None),
221 WorkKind::Mine => map.set(site, Terrain::Gravel),
222 WorkKind::Harvest => {
223 if map.plant(site.as_ivec2()) == Some(Plant::Crop) {
224 map.set_plant(site, None);
225 }
226 map.set_growth(site, 0.0);
227 }
228 WorkKind::Sow => {
229 map.set_plant(site, Some(Plant::Crop));
230 map.set_growth(site, 0.0);
231 }
232 }
233 }
234 }
235
236 pub struct SiteWork {
237 pub kind: WorkKind,
238 pub item: ItemKind,
239 pub count: u32,
240 }
241
242 pub fn site_work(map: &WorldMap, site: UVec2) -> Option<SiteWork> {
243 let p = site.as_ivec2();
244 let harvest = |item, count| SiteWork {
245 kind: WorkKind::Harvest,
246 item,
247 count,
248 };
249 match map.plant(p) {
250 Some(Plant::Tree) => {
251 return Some(SiteWork {
252 kind: WorkKind::Chop,
253 item: ItemKind::Wood,
254 count: 10,
255 });
256 }
257 Some(Plant::BerryBush) if map.ripe_plant(p).is_some() => {
258 return Some(harvest(ItemKind::Berries, 8));
259 }
260 Some(Plant::Crop) if map.ripe_plant(p).is_some() => {
261 return Some(harvest(ItemKind::Vegetables, 10));
262 }
263 _ => {}
264 }
265 let (item, count) = match map.get(p)? {
266 Terrain::Stone => (ItemKind::Stone, 10),
267 Terrain::IronOre => (ItemKind::Iron, 10),
268 Terrain::GoldOre => (ItemKind::Gold, 5),
269 _ => return None,
270 };
271 Some(SiteWork {
272 kind: WorkKind::Mine,
273 item,
274 count,
275 })
276 }
277
278 #[derive(Component, Debug)]
279 pub struct IdleTimer(Timer);
280
281 impl Default for IdleTimer {
282 fn default() -> Self {
283 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
284 }
285 }
286
287 impl IdleTimer {
288 fn restart(&mut self, secs: f32) {
289 self.0.set_duration(Duration::from_secs_f32(secs));
290 self.0.reset();
291 }
292 }
293
294 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295 pub enum Target {
296 Site(UVec2),
297 Pickup(UVec2),
298 Storage(UVec2),
299 StockpileExpansion,
300 SleepSpot(UVec2),
301 Animal(Entity),
302 Station(UVec2),
303 }
304
305 #[derive(Resource, Default, Debug)]
306 pub struct Reservations(HashMap<Target, Entity>);
307
308 impl Reservations {
309 pub fn reserve(&mut self, target: Target, by: Entity) {
310 self.0.insert(target, by);
311 }
312
313 pub fn holder(&self, target: Target) -> Option<Entity> {
314 self.0.get(&target).copied()
315 }
316
317 pub fn is_free(&self, target: Target) -> bool {
318 self.holder(target).is_none()
319 }
320
321 pub fn release(&mut self, target: Target) {
322 self.0.remove(&target);
323 }
324
325 pub fn release_all(&mut self, by: Entity) {
326 self.0.retain(|_, holder| *holder != by);
327 }
328 }
329
330 #[derive(Message, Debug, Clone, Copy)]
331 pub struct Order {
332 pub colonist: Entity,
333 pub tile: UVec2,
334 }
335
336 fn clear_reservations(mut reservations: ResMut<Reservations>) {
337 reservations.0.clear();
338 }
339
340 fn handle_orders(
341 mut orders: MessageReader<Order>,
342 map: Res<WorldMap>,
343 zones: Res<Zones>,
344 items: Query<(&Item, &TilePos)>,
345 animals: Query<(Entity, &TilePos, &Animal), Without<Colonist>>,
346 mut reservations: ResMut<Reservations>,
347 mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob), With<Colonist>>,
348 ) {
349 for order in orders.read() {
350 let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else {
351 continue;
352 };
353 let loose_item = items
354 .iter()
355 .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0));
356 let animal = animals.iter().find(|(_, pos, _)| pos.0 == order.tile);
357 let task = if let Some((animal, _, a)) = animal {
358 Some(Task::Hunt {
359 animal,
360 kind: a.kind,
361 progress: 0,
362 })
363 } else if let Some(work) = site_work(&map, order.tile) {
364 Some(Task::Work {
365 site: order.tile,
366 kind: work.kind,
367 progress: 0,
368 })
369 } else if let Some((item, _)) = loose_item {
370 find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| {
371 Task::Haul {
372 pickup: Some(order.tile),
373 to,
374 }
375 })
376 } else {
377 None
378 };
379 if let Some(task) = task {
380 reservations.release_all(order.colonist);
381 reserve_task(&mut reservations, task, order.colonist);
382 path.0.truncate(1);
383 job.0 = Some(Job {
384 task,
385 ordered: true,
386 });
387 } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) {
388 reservations.release_all(order.colonist);
389 path.0 = new_path;
390 job.0 = Some(Job {
391 task: Task::MoveTo(order.tile),
392 ordered: true,
393 });
394 }
395 }
396 }
397
398 fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) {
399 match task {
400 Task::MoveTo(_) => {}
401 Task::Work { site, .. } => reservations.reserve(Target::Site(site), by),
402 Task::Haul { pickup, to } => {
403 if let Some(pickup) = pickup {
404 reservations.reserve(Target::Pickup(pickup), by);
405 }
406 reservations.reserve(Target::Storage(to), by);
407 }
408 Task::ExpandStockpile { .. } => reservations.reserve(Target::StockpileExpansion, by),
409 Task::Sleep { spot } => reservations.reserve(Target::SleepSpot(spot), by),
410 Task::Eat { pickup, .. } => {
411 if let Some(pickup) = pickup {
412 reservations.reserve(Target::Pickup(pickup), by);
413 }
414 }
415 Task::Hunt { animal, .. } | Task::Tame { animal, .. } => {
416 reservations.reserve(Target::Animal(animal), by)
417 }
418 Task::Butcher { site, .. } => reservations.reserve(Target::Pickup(site), by),
419 Task::Cook {
420 pickup, station, ..
421 } => {
422 reservations.reserve(Target::Station(station), by);
423 if let Some(pickup) = pickup {
424 reservations.reserve(Target::Pickup(pickup), by);
425 }
426 }
427 Task::Build { site, pickup, .. } => {
428 reservations.reserve(Target::Site(site), by);
429 if let Some(pickup) = pickup {
430 reservations.reserve(Target::Pickup(pickup), by);
431 }
432 }
433 }
434 }
435
436 pub fn find_work(
437 map: &WorldMap,
438 reservations: &Reservations,
439 from: UVec2,
440 wanted: impl Fn(UVec2, ItemKind) -> bool,
441 ) -> Option<Task> {
442 find_work_within(map, reservations, from, SEARCH_TILES, wanted)
443 }
444
445 pub fn find_work_within(
446 map: &WorldMap,
447 reservations: &Reservations,
448 from: UVec2,
449 max_tiles: usize,
450 wanted: impl Fn(UVec2, ItemKind) -> bool,
451 ) -> Option<Task> {
452 let mut found = None;
453 nearest_tile(map, from, max_tiles, |stand| {
454 found = NEIGHBORS.iter().find_map(|&d| {
455 let site = stand.as_ivec2() + d;
456 if site.x < 0 || site.y < 0 {
457 return None;
458 }
459 let site = site.as_uvec2();
460 let work = site_work(map, site)?;
461 (wanted(site, work.item) && reservations.is_free(Target::Site(site))).then_some(
462 Task::Work {
463 site,
464 kind: work.kind,
465 progress: 0,
466 },
467 )
468 });
469 found.is_some()
470 })?;
471 found
472 }
473
474 fn stacks_by_tile<'a>(
475 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)>,
476 ) -> HashMap<UVec2, (ItemKind, u32)> {
477 let mut stacks: HashMap<UVec2, (ItemKind, u32)> = HashMap::new();
478 for (item, pos) in items {
479 stacks.entry(pos.0).or_insert((item.kind, 0)).1 += item.count;
480 }
481 stacks
482 }
483
484 fn storage_candidates<'z>(
485 zones: &'z Zones,
486 reservations: &'z Reservations,
487 stacks: &'z HashMap<UVec2, (ItemKind, u32)>,
488 kind: ItemKind,
489 ) -> impl Iterator<Item = UVec2> + 'z {
490 zones.stockpile_tiles().filter(move |&t| {
491 zones.accepts(t, kind)
492 && reservations.is_free(Target::Storage(t))
493 && match stacks.get(&t) {
494 None => true,
495 Some(&(other, count)) => other == kind && count < STACK_LIMIT,
496 }
497 })
498 }
499
500 pub fn find_storage<'a>(
501 map: &WorldMap,
502 zones: &Zones,
503 reservations: &Reservations,
504 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)> + Clone,
505 from: UVec2,
506 kind: ItemKind,
507 ) -> Option<UVec2> {
508 let stacks = stacks_by_tile(items);
509 StoragePriority::DESCENDING
510 .into_iter()
511 .find_map(|priority| {
512 let candidates: HashSet<UVec2> = storage_candidates(zones, reservations, &stacks, kind)
513 .filter(|&t| zones.rule(t).priority == priority)
514 .collect();
515 nearest_of(map, from, SEARCH_TILES, &candidates)
516 })
517 }
518
519 pub fn find_haul(
520 map: &WorldMap,
521 zones: &Zones,
522 reservations: &Reservations,
523 items: &[(Item, TilePos)],
524 from: UVec2,
525 ) -> Option<Task> {
526 let stacks = stacks_by_tile(items.iter().map(|(i, p)| (i, p)));
527 let mut best: HashMap<ItemKind, StoragePriority> = HashMap::new();
528 let misplaced = |item: &Item, tile: UVec2, best: &mut HashMap<ItemKind, StoragePriority>| {
529 if !zones.accepts(tile, item.kind) {
530 return true;
531 }
532 let top = *best.entry(item.kind).or_insert_with(|| {
533 storage_candidates(zones, reservations, &stacks, item.kind)
534 .map(|t| zones.rule(t).priority)
535 .max()
536 .unwrap_or(StoragePriority::Low)
537 });
538 zones.rule(tile).priority < top
539 };
540 let loose: HashSet<UVec2> = items
541 .iter()
542 .filter(|(item, pos)| {
543 reservations.is_free(Target::Pickup(pos.0)) && misplaced(item, pos.0, &mut best)
544 })
545 .map(|(_, pos)| pos.0)
546 .collect();
547 if loose.is_empty() {
548 return None;
549 }
550 let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?;
551 let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?;
552 let refs = items.iter().map(|(i, p)| (i, p));
553 let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?;
554 Some(Task::Haul {
555 pickup: Some(pickup),
556 to,
557 })
558 }
559
560 pub fn sowable(map: &WorldMap, zones: &Zones, site: UVec2) -> bool {
561 zones.is_farm(site) && map.plant(site.as_ivec2()).is_none()
562 }
563
564 pub fn find_sowing(
565 map: &WorldMap,
566 zones: &Zones,
567 reservations: &Reservations,
568 from: UVec2,
569 ) -> Option<Task> {
570 let open: HashSet<UVec2> = zones
571 .farm_tiles()
572 .filter(|&p| sowable(map, zones, p) && reservations.is_free(Target::Site(p)))
573 .collect();
574 let site = nearest_of(map, from, SEARCH_TILES, &open)?;
575 Some(Task::Work {
576 site,
577 kind: WorkKind::Sow,
578 progress: 0,
579 })
580 }
581
582 pub const HUNT_RADIUS: f32 = 60.0;
583 pub const HUNT_RANGE: f32 = 6.0;
584
585 pub type Wildlife = (Entity, UVec2, AnimalKind, bool);
586
587 fn nearest_reachable(
588 map: &WorldMap,
589 reservations: &Reservations,
590 animals: &[Wildlife],
591 from: UVec2,
592 pick: impl Fn(&Wildlife) -> bool,
593 ) -> Option<Wildlife> {
594 let mut candidates: Vec<&Wildlife> = animals
595 .iter()
596 .filter(|a| {
597 pick(a)
598 && reservations.is_free(Target::Animal(a.0))
599 && a.1.as_vec2().distance(from.as_vec2()) <= HUNT_RADIUS
600 })
601 .collect();
602 candidates.sort_by(|a, b| {
603 a.1.as_vec2()
604 .distance_squared(from.as_vec2())
605 .total_cmp(&b.1.as_vec2().distance_squared(from.as_vec2()))
606 });
607 candidates
608 .into_iter()
609 .find(|a| find_path_adjacent(map, from, a.1).is_some())
610 .copied()
611 }
612
613 pub fn find_hunt(
614 map: &WorldMap,
615 reservations: &Reservations,
616 animals: &[Wildlife],
617 from: UVec2,
618 ) -> Option<Task> {
619 let herd = |kind: AnimalKind| animals.iter().filter(|a| a.3 && a.2 == kind).count();
620 let spare_tame = |a: &Wildlife| a.3 && herd(a.2) > 2;
621 let (animal, _, kind, _) = nearest_reachable(map, reservations, animals, from, spare_tame)
622 .or_else(|| nearest_reachable(map, reservations, animals, from, |a| !a.3))?;
623 Some(Task::Hunt {
624 animal,
625 kind,
626 progress: 0,
627 })
628 }
629
630 pub fn find_taming(
631 map: &WorldMap,
632 reservations: &Reservations,
633 animals: &[Wildlife],
634 from: UVec2,
635 ) -> Option<Task> {
636 if animals.iter().filter(|a| a.3).count() >= MAX_TAME {
637 return None;
638 }
639 let (animal, _, kind, _) = nearest_reachable(map, reservations, animals, from, |a| !a.3)?;
640 Some(Task::Tame {
641 animal,
642 kind,
643 progress: 0,
644 })
645 }
646
647 pub fn stockpile_too_full(zones: &Zones, items: &[(Item, TilePos)]) -> bool {
648 let occupied: HashSet<UVec2> = items.iter().map(|(_, pos)| pos.0).collect();
649 zones.has_stockpile() && zones.empty_stockpile_tiles(&occupied) < MIN_EMPTY_STOCKPILE_TILES
650 }
651
652 pub fn find_expansion(
653 map: &WorldMap,
654 zones: &Zones,
655 reservations: &Reservations,
656 items: &[(Item, TilePos)],
657 blueprints: &Blueprints,
658 ) -> Option<Task> {
659 if !reservations.is_free(Target::StockpileExpansion) {
660 return None;
661 }
662 let site = if zones.has_stockpile() {
663 if !stockpile_too_full(zones, items) {
664 return None;
665 }
666 *plan_expansion(map, zones, &blueprints.tiles(), EXPANSION_TILES).first()?
667 } else {
668 find_stockpile_site(map, central_item_tile(items)?)?
669 };
670 Some(Task::ExpandStockpile { site, progress: 0 })
671 }
672
673 fn central_item_tile(items: &[(Item, TilePos)]) -> Option<UVec2> {
674 let tiles: Vec<Vec2> = items.iter().map(|(_, pos)| pos.0.as_vec2()).collect();
675 let centroid = tiles.iter().sum::<Vec2>() / tiles.len().max(1) as f32;
676 items.iter().map(|(_, pos)| pos.0).min_by(|a, b| {
677 a.as_vec2()
678 .distance_squared(centroid)
679 .total_cmp(&b.as_vec2().distance_squared(centroid))
680 })
681 }
682
683 pub struct BuildContext<'a> {
684 pub map: &'a WorldMap,
685 pub zones: &'a Zones,
686 pub reservations: &'a Reservations,
687 pub items: &'a [(Item, TilePos)],
688 pub structures: &'a [(UVec2, StructureKind, u32)],
689 pub planned: &'a [(UVec2, StructureKind)],
690 pub blueprints: &'a Blueprints,
691 pub occupied: &'a HashSet<UVec2>,
692 }
693
694 impl BuildContext<'_> {
695 fn buildable(&self, tile: UVec2) -> bool {
696 can_zone(self.map, tile.as_ivec2())
697 && !self.zones.is_stockpile(tile)
698 && !self.zones.is_farm(tile)
699 && self.map.plant(tile.as_ivec2()).is_none()
700 && !self.occupied.contains(&tile)
701 && self.blueprints.get(tile).is_none()
702 && self.reservations.is_free(Target::Site(tile))
703 }
704
705 fn lights(&self) -> impl Iterator<Item = (UVec2, StructureKind)> + Clone + '_ {
706 self.structures
707 .iter()
708 .map(|&(pos, kind, _)| (pos, kind))
709 .chain(self.planned.iter().copied())
710 }
711
712 fn campfire_needed(&self, home: UVec2) -> bool {
713 let burning = self.structures.iter().any(|&(pos, kind, fuel)| {
714 kind == StructureKind::Campfire
715 && fuel >= CAMPFIRE_MIN_FUEL
716 && pos.as_vec2().distance(home.as_vec2()) <= HOME_RADIUS
717 });
718 let planned = self
719 .planned
720 .iter()
721 .any(|(_, kind)| *kind == StructureKind::Campfire);
722 !burning && !planned
723 }
724
725 fn darkest_stockpile_tile(&self, home: UVec2) -> Option<UVec2> {
726 self.zones
727 .stockpile_tiles()
728 .filter(|&t| brightness(light_from(t, self.lights())) < LIT_BRIGHTNESS)
729 .min_by(|a, b| {
730 a.as_vec2()
731 .distance_squared(home.as_vec2())
732 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
733 .then((a.y, a.x).cmp(&(b.y, b.x)))
734 })
735 }
736
737 fn site_near(&self, target: UVec2, max_distance: f32) -> Option<UVec2> {
738 self.site_near_where(target, max_distance, |_| true)
739 }
740
741 fn site_near_where(
742 &self,
743 target: UVec2,
744 max_distance: f32,
745 extra: impl Fn(UVec2) -> bool,
746 ) -> Option<UVec2> {
747 nearest_tile(self.map, target, SEARCH_TILES, |p| {
748 self.buildable(p) && extra(p)
749 })
750 .filter(|site| site.as_vec2().distance(target.as_vec2()) <= max_distance)
751 }
752
753 fn clear_of_stockpile(&self, tile: UVec2) -> bool {
754 self.zones
755 .stockpile_tiles()
756 .chain(self.zones.farm_tiles())
757 .all(|s| {
758 (s.as_ivec2() - tile.as_ivec2()).abs().max_element() >= BED_STOCKPILE_CLEARANCE
759 })
760 }
761
762 fn count(&self, kind: StructureKind) -> usize {
763 let built = self.structures.iter().filter(|s| s.1 == kind).count();
764 built + self.planned.iter().filter(|p| p.1 == kind).count()
765 }
766
767 fn bed_anchor(&self, home: UVec2) -> UVec2 {
768 let positions = |kind: StructureKind| {
769 let built = self.structures.iter().map(|s| (s.0, s.1));
770 built
771 .chain(self.planned.iter().copied())
772 .filter(move |s| s.1 == kind)
773 .map(|s| s.0)
774 };
775 let nearest = |kind: StructureKind| {
776 positions(kind).min_by(|a, b| {
777 a.as_vec2()
778 .distance_squared(home.as_vec2())
779 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
780 })
781 };
782 nearest(StructureKind::Bed)
783 .or_else(|| nearest(StructureKind::Campfire))
784 .unwrap_or(home)
785 }
786
787 fn material_source(&self, from: UVec2, (kind, amount): (ItemKind, u32)) -> Option<UVec2> {
788 let stacks: Vec<(u32, UVec2)> = self
789 .items
790 .iter()
791 .filter(|(item, pos)| {
792 item.kind == kind && self.reservations.is_free(Target::Pickup(pos.0))
793 })
794 .map(|(item, pos)| (item.count, pos.0))
795 .collect();
796 if stacks.iter().map(|(count, _)| count).sum::<u32>() < amount {
797 return None;
798 }
799 let tiles: HashSet<UVec2> = stacks.into_iter().map(|(_, tile)| tile).collect();
800 nearest_of(self.map, from, SEARCH_TILES, &tiles)
801 }
802
803 fn build_task(&self, from: UVec2, site: UVec2, kind: BuildKind) -> Option<Task> {
804 let pickup = match kind.cost() {
805 (_, 0) => None,
806 cost => Some(self.material_source(from, cost)?),
807 };
808 Some(Task::Build {
809 site,
810 kind,
811 pickup,
812 progress: 0,
813 })
814 }
815 }
816
817 pub const COOK_INPUT: u32 = 6;
818 pub const COOK_WORK: u32 = 300;
819 pub const COOK_MIN_FUEL: u32 = crate::sim::TICKS_PER_HOUR as u32;
820
821 pub fn find_campfire(ctx: &BuildContext, from: UVec2) -> Option<Task> {
822 let home = ctx.zones.home(from);
823 if !ctx.campfire_needed(home) {
824 return None;
825 }
826 let site = ctx.site_near(home, HOME_RADIUS)?;
827 ctx.build_task(from, site, BuildKind::Structure(StructureKind::Campfire))
828 }
829
830 pub fn food_to_fetch(reservations: &Reservations, food_tiles: &HashSet<UVec2>) -> bool {
831 food_tiles
832 .iter()
833 .any(|&p| reservations.is_free(Target::Pickup(p)))
834 }
835
836 pub fn raw_food_source(ctx: &BuildContext, from: UVec2) -> Option<UVec2> {
837 let sources: HashSet<UVec2> = ctx
838 .items
839 .iter()
840 .filter(|(item, pos)| {
841 item.kind.is_raw_food()
842 && item.count >= COOK_INPUT
843 && ctx.reservations.is_free(Target::Pickup(pos.0))
844 })
845 .map(|(_, pos)| pos.0)
846 .collect();
847 nearest_of(ctx.map, from, SEARCH_TILES, &sources)
848 }
849
850 pub const BUTCHER_WORK: u32 = 240;
851
852 pub fn find_butchering(
853 map: &WorldMap,
854 reservations: &Reservations,
855 items: &[(Item, TilePos)],
856 from: UVec2,
857 ) -> Option<Task> {
858 let carcasses: HashSet<UVec2> = items
859 .iter()
860 .filter(|(item, pos)| {
861 item.kind == ItemKind::Carcass && reservations.is_free(Target::Pickup(pos.0))
862 })
863 .map(|(_, pos)| pos.0)
864 .collect();
865 let site = nearest_of(map, from, SEARCH_TILES, &carcasses)?;
866 Some(Task::Butcher { site, progress: 0 })
867 }
868
869 pub fn find_cooking(ctx: &BuildContext, from: UVec2) -> Option<Task> {
870 let station = ctx
871 .structures
872 .iter()
873 .filter(|&&(pos, kind, fuel)| {
874 kind == StructureKind::Campfire
875 && fuel >= COOK_MIN_FUEL
876 && ctx.reservations.is_free(Target::Station(pos))
877 })
878 .map(|&(pos, ..)| pos)
879 .min_by(|a, b| {
880 a.as_vec2()
881 .distance_squared(from.as_vec2())
882 .total_cmp(&b.as_vec2().distance_squared(from.as_vec2()))
883 })?;
884 let pickup = raw_food_source(ctx, from)?;
885 Some(Task::Cook {
886 pickup: Some(pickup),
887 station,
888 progress: 0,
889 })
890 }
891
892 pub fn find_lighting(ctx: &BuildContext, from: UVec2, dark: bool) -> Option<Task> {
893 let home = ctx.zones.home(from);
894 let (kind, site) = if ctx.campfire_needed(home) {
895 (StructureKind::Campfire, ctx.site_near(home, HOME_RADIUS)?)
896 } else if !dark {
897 return None;
898 } else {
899 let dark = ctx.darkest_stockpile_tile(home)?;
900 let reach = StructureKind::Torch.radius() * 0.6;
901 (StructureKind::Torch, ctx.site_near(dark, reach)?)
902 };
903 ctx.build_task(from, site, BuildKind::Structure(kind))
904 }
905
906 pub fn chilly_soon(tick: SimTick) -> bool {
907 let later = SimTick(tick.0 + LIGHT_LOOKAHEAD_TICKS);
908 outdoor_temperature(tick) < COLD_TEMP || outdoor_temperature(later) < COLD_TEMP
909 }
910
911 pub fn find_warm_spot(
912 map: &WorldMap,
913 structures: &[(UVec2, StructureKind, u32)],
914 outdoor: f32,
915 from: UVec2,
916 ) -> Option<UVec2> {
917 let fires: Vec<(UVec2, StructureKind)> = structures
918 .iter()
919 .filter(|(_, kind, _)| kind.heat() > 0.0)
920 .map(|&(pos, kind, _)| (pos, kind))
921 .collect();
922 let taken: HashSet<UVec2> = structures.iter().map(|(pos, ..)| *pos).collect();
923 let warm: HashSet<UVec2> = fires
924 .iter()
925 .flat_map(|&(pos, kind)| {
926 let r = kind.radius().ceil() as i32;
927 (-r..=r).flat_map(move |dy| (-r..=r).map(move |dx| pos.as_ivec2() + IVec2::new(dx, dy)))
928 })
929 .filter(|&p| map.in_bounds(p) && map.move_cost(p).is_some())
930 .map(|p| p.as_uvec2())
931 .filter(|p| !taken.contains(p))
932 .filter(|&p| tile_temperature(map, outdoor, p, fires.iter().copied()) >= WARM_TEMP)
933 .collect();
934 nearest_of(map, from, SEARCH_TILES, &warm)
935 }
936
937 pub fn find_refuel(ctx: &BuildContext, from: UVec2) -> Option<Task> {
938 let home = ctx.zones.home(from);
939 let (site, kind, _) = ctx
940 .structures
941 .iter()
942 .filter(|&&(pos, kind, fuel)| {
943 kind.fuel_ticks()
944 .is_some_and(|full| fuel < full / REFUEL_BELOW_SHARE)
945 && pos.as_vec2().distance(home.as_vec2()) <= HOME_RADIUS * 2.0
946 && ctx.reservations.is_free(Target::Site(pos))
947 })
948 .min_by_key(|(.., fuel)| *fuel)?;
949 ctx.build_task(from, *site, BuildKind::Refuel(*kind))
950 }
951
952 pub fn find_bed_site(ctx: &BuildContext, colonists: usize, from: UVec2) -> Option<Task> {
953 if ctx.count(StructureKind::Bed) >= colonists {
954 return None;
955 }
956 let anchor = ctx.bed_anchor(ctx.zones.home(from));
957 let site = ctx.site_near_where(anchor, HOME_RADIUS * 1.5, |p| ctx.clear_of_stockpile(p))?;
958 ctx.build_task(from, site, BuildKind::Structure(StructureKind::Bed))
959 }
960
961 pub fn find_blueprint_work(ctx: &BuildContext, from: UVec2) -> Option<Task> {
962 if ctx.blueprints.0.is_empty() {
963 return None;
964 }
965 let mut found = None;
966 nearest_tile(ctx.map, from, SEARCH_TILES, |p| {
967 found = std::iter::once(IVec2::ZERO)
968 .chain(NEIGHBORS)
969 .filter_map(|d| {
970 let site = p.as_ivec2() + d;
971 (site.min_element() >= 0).then(|| site.as_uvec2())
972 })
973 .filter(|&site| site == p || ctx.map.move_cost(site.as_ivec2()).is_none())
974 .find_map(|site| {
975 let kind = ctx.blueprints.get(site)?;
976 if !ctx.reservations.is_free(Target::Site(site)) {
977 return None;
978 }
979 ctx.build_task(from, site, kind)
980 });
981 found.is_some()
982 })?;
983 found
984 }
985
986 fn on_the_way(map: &WorldMap, jobs: impl Iterator<Item = Option<Job>>) -> HashMap<ItemKind, u32> {
987 let mut totals = HashMap::new();
988 for job in jobs.flatten() {
989 if let Task::Work { site, .. } = job.task
990 && let Some(work) = site_work(map, site)
991 {
992 *totals.entry(work.item).or_insert(0) += work.count;
993 }
994 }
995 totals
996 }
997
998 #[allow(clippy::too_many_arguments)]
999 fn choose_jobs(
1000 mut commands: Commands,
1001 time: Res<Time>,
1002 map: Res<WorldMap>,
1003 zones: Res<Zones>,
1004 goals: Res<ColonyGoals>,
1005 item_assets: Res<ItemAssets>,
1006 tick: Res<SimTick>,
1007 blueprints: Res<Blueprints>,
1008 mut rng: ResMut<SimRng>,
1009 mut reservations: ResMut<Reservations>,
1010 mut items: ItemQuery,
1011 structures: Query<(&TilePos, &Structure, Option<&Fuel>), Without<Colonist>>,
1012 animals: Query<(Entity, &TilePos, &Animal, Has<Tame>), Without<Colonist>>,
1013 mut colonists: Query<
1014 (
1015 Entity,
1016 &TilePos,
1017 &mut Path,
1018 &mut CurrentJob,
1019 &mut IdleTimer,
1020 &mut Carrying,
1021 &Rest,
1022 &Hunger,
1023 Option<&Family>,
1024 Has<Child>,
1025 &WorkPriorities,
1026 &Warmth,
1027 ),
1028 With<Colonist>,
1029 >,
1030 plans: (Res<Homes>, Res<Designations>),
1031 ) {
1032 let (homes, designations) = plans;
1033 let mut anyone_ready = false;
1034 for (_, _, path, job, mut idle, _, rest, hunger, ..) in &mut colonists {
1035 let idle_now = job.0.is_none() && path.0.is_empty();
1036 if idle_now {
1037 idle.0.tick(time.delta());
1038 }
1039 anyone_ready |=
1040 (idle_now && idle.0.is_finished()) || rest.0 < EXHAUSTED_REST || hunger.0 < STARVING;
1041 }
1042 if !anyone_ready {
1043 return;
1044 }
1045 let wildlife: Vec<Wildlife> = animals
1046 .iter()
1047 .map(|(e, pos, a, tame)| (e, pos.0, a.kind, tame))
1048 .collect();
1049 let adults = colonists.iter().filter(|c| !c.9).count();
1050 let structures_list: Vec<(UVec2, StructureKind, u32)> = structures
1051 .iter()
1052 .map(|(pos, s, fuel)| (pos.0, s.kind, fuel.map_or(u32::MAX, |f| f.0)))
1053 .collect();
1054 let mut planned: Vec<(UVec2, StructureKind)> = colonists
1055 .iter()
1056 .filter_map(|c| match c.3.0?.task {
1057 Task::Build {
1058 site,
1059 kind: BuildKind::Structure(kind),
1060 ..
1061 } => Some((site, kind)),
1062 _ => None,
1063 })
1064 .collect();
1065 let dark = dark_soon(*tick);
1066 let chilly = chilly_soon(*tick);
1067 let outdoor = outdoor_temperature(*tick);
1068 let sowing = sowing_season(*tick);
1069 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
1070 let home = zones.home(map.size / 2);
1071 let stocks: HashMap<ItemKind, u32> = ItemKind::ALL
1072 .iter()
1073 .map(|&kind| {
1074 let all = items
1075 .iter()
1076 .filter(|(_, _, pos)| in_colony(home, pos.0))
1077 .map(|(_, item, _)| item)
1078 .chain(carried.iter());
1079 (kind, stock(all, kind))
1080 })
1081 .collect();
1082 let mut pending = on_the_way(&map, colonists.iter().map(|c| c.3.0));
1083 for job in colonists.iter().filter_map(|c| c.3.0) {
1084 match job.task {
1085 Task::Hunt { kind, .. } => *pending.entry(ItemKind::Meat).or_insert(0) += kind.meat(),
1086 Task::Cook { .. } => *pending.entry(ItemKind::Meal).or_insert(0) += 1,
1087 _ => {}
1088 }
1089 }
1090 let food_tiles: HashSet<UVec2> = items
1091 .iter()
1092 .filter(|(_, item, _)| item.kind.is_food())
1093 .map(|(_, _, pos)| pos.0)
1094 .collect();
1095 let hour = hour_of_day(*tick);
1096 for (
1097 entity,
1098 tile,
1099 mut path,
1100 mut job,
1101 mut idle,
1102 mut carrying,
1103 rest,
1104 hunger,
1105 family,
1106 child,
1107 priorities,
1108 warmth,
1109 ) in &mut colonists
1110 {
1111 let exhausted = rest.0 < EXHAUSTED_REST;
1112 let starving = hunger.0 < STARVING && food_to_fetch(&reservations, &food_tiles);
1113 let urgent = exhausted || starving;
1114 if urgent
1115 && job.0.is_some_and(|j| {
1116 !j.ordered && !matches!(j.task, Task::Sleep { .. } | Task::Eat { .. })
1117 })
1118 {
1119 reservations.release_all(entity);
1120 job.0 = None;
1121 path.0.truncate(1);
1122 }
1123 let rested = idle.0.is_finished();
1124 if job.0.is_some() || !path.0.is_empty() || !(rested || urgent) {
1125 continue;
1126 }
1127 let snapshot: Vec<(Item, TilePos)> =
1128 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
1129 let refs = snapshot.iter().map(|(i, p)| (i, p));
1130 let wanted = |kind: ItemKind| goals.wanted(kind, &stocks, &pending);
1131 let sleep = SleepContext {
1132 map: &map,
1133 zones: &zones,
1134 reservations: &reservations,
1135 items: &snapshot,
1136 structures: &structures_list,
1137 blueprints: &blueprints,
1138 homes: &homes,
1139 family: family.copied(),
1140 child,
1141 };
1142 let food = wants_food(hunger.0)
1143 .then(|| find_food(&map, &reservations, &snapshot, tile.0))
1144 .flatten();
1145 let task = if exhausted {
1146 Some(Task::Sleep {
1147 spot: sleep.spot(tile.0),
1148 })
1149 } else if let Some(pickup) = food {
1150 if let Some(load) = carrying.0.take() {
1151 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
1152 }
1153 Some(Task::Eat {
1154 pickup: Some(pickup),
1155 progress: 0,
1156 })
1157 } else if wants_sleep(rest.0, hour) {
1158 Some(Task::Sleep {
1159 spot: sleep.spot(tile.0),
1160 })
1161 } else if let Some(spot) = warmth
1162 .cold()
1163 .then(|| find_warm_spot(&map, &structures_list, outdoor, tile.0))
1164 .flatten()
1165 .filter(|&spot| spot != tile.0)
1166 {
1167 find_path(&map, tile.0, spot).map(|route| {
1168 path.0 = route.into();
1169 Task::MoveTo(spot)
1170 })
1171 } else if child {
1172 None
1173 } else if let Some(load) = carrying.0 {
1174 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
1175 if storage.is_none() {
1176 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
1177 carrying.0 = None;
1178 }
1179 storage.map(|to| Task::Haul { pickup: None, to })
1180 } else {
1181 let occupied: HashSet<UVec2> = structures_list
1182 .iter()
1183 .map(|(pos, ..)| *pos)
1184 .chain(planned.iter().map(|(pos, _)| *pos))
1185 .chain(snapshot.iter().map(|(_, pos)| pos.0))
1186 .collect();
1187 let build = BuildContext {
1188 map: &map,
1189 zones: &zones,
1190 reservations: &reservations,
1191 items: &snapshot,
1192 structures: &structures_list,
1193 planned: &planned,
1194 blueprints: &blueprints,
1195 occupied: &occupied,
1196 };
1197 let cooking = || {
1198 (wanted(ItemKind::Meal) && raw_food_source(&build, tile.0).is_some())
1199 .then(|| find_cooking(&build, tile.0).or_else(|| find_campfire(&build, tile.0)))
1200 .flatten()
1201 };
1202 let designated = || {
1203 (!designations.0.is_empty())
1204 .then(|| {
1205 find_work(&map, &reservations, tile.0, |site, _| {
1206 designations.0.contains(&site)
1207 })
1208 })
1209 .flatten()
1210 };
1211 let candidates: [(WorkType, &dyn Fn() -> Option<Task>); 15] = [
1212 (WorkType::Haul, &|| {
1213 find_expansion(&map, &zones, &reservations, &snapshot, &blueprints)
1214 }),
1215 (WorkType::Build, &|| find_refuel(&build, tile.0)),
1216 (WorkType::Build, &|| {
1217 (dark || chilly)
1218 .then(|| find_lighting(&build, tile.0, dark))
1219 .flatten()
1220 }),
1221 (WorkType::Food, &cooking),
1222 (WorkType::Food, &|| {
1223 find_butchering(&map, &reservations, &snapshot, tile.0)
1224 }),
1225 (WorkType::Food, &|| {
1226 ItemKind::ALL
1227 .iter()
1228 .any(|&k| k.is_food() && wanted(k))
1229 .then(|| {
1230 let food = |_, k: ItemKind| k.is_food() && wanted(k);
1231 find_work_within(&map, &reservations, tile.0, FORAGE_SEARCH_TILES, food)
1232 })
1233 .flatten()
1234 }),
1235 (WorkType::Gather, &designated),
1236 (WorkType::Food, &|| {
1237 (sowing && wanted(ItemKind::Vegetables))
1238 .then(|| find_sowing(&map, &zones, &reservations, tile.0))
1239 .flatten()
1240 }),
1241 (WorkType::Build, &|| find_bed_site(&build, adults, tile.0)),
1242 (WorkType::Build, &|| find_blueprint_work(&build, tile.0)),
1243 (WorkType::Gather, &|| {
1244 ItemKind::ALL
1245 .iter()
1246 .any(|&k| wanted(k))
1247 .then(|| find_work(&map, &reservations, tile.0, |_, k| wanted(k)))
1248 .flatten()
1249 }),
1250 (WorkType::Food, &|| {
1251 wanted(ItemKind::Meat)
1252 .then(|| find_hunt(&map, &reservations, &wildlife, tile.0))
1253 .flatten()
1254 }),
1255 (WorkType::Food, &|| {
1256 sowing
1257 .then(|| find_sowing(&map, &zones, &reservations, tile.0))
1258 .flatten()
1259 }),
1260 (WorkType::Tame, &|| {
1261 (!wanted(ItemKind::Meat))
1262 .then(|| find_taming(&map, &reservations, &wildlife, tile.0))
1263 .flatten()
1264 }),
1265 (WorkType::Haul, &|| {
1266 find_haul(&map, &zones, &reservations, &snapshot, tile.0)
1267 }),
1268 ];
1269 candidates
1270 .iter()
1271 .filter(|(work, _)| priorities.allows(*work))
1272 .find_map(|(_, find)| find())
1273 };
1274 if let Some(task) = task {
1275 if let Task::Work { site, .. } = task
1276 && let Some(work) = site_work(&map, site)
1277 {
1278 *pending.entry(work.item).or_insert(0) += work.count;
1279 }
1280 match task {
1281 Task::Hunt { kind, .. } => {
1282 *pending.entry(ItemKind::Meat).or_insert(0) += kind.meat()
1283 }
1284 Task::Cook { .. } => *pending.entry(ItemKind::Meal).or_insert(0) += 1,
1285 _ => {}
1286 }
1287 if let Task::Build {
1288 site,
1289 kind: BuildKind::Structure(kind),
1290 ..
1291 } = task
1292 {
1293 planned.push((site, kind));
1294 }
1295 reserve_task(&mut reservations, task, entity);
1296 job.0 = Some(Job {
1297 task,
1298 ordered: false,
1299 });
1300 continue;
1301 }
1302 let goal = tile.0.as_ivec2()
1303 + IVec2::new(
1304 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
1305 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
1306 );
1307 if map.in_bounds(goal)
1308 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
1309 {
1310 path.0 = wander_path.into();
1311 idle.restart(rng.range_f32(IDLE_SECS));
1312 }
1313 }
1314 }
1315
1316 enum Step {
1317 Continue,
1318 Done,
1319 }
1320
1321 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
1322 match find_path(map, from, to) {
1323 Some(p) if !p.is_empty() => {
1324 path.0 = p.into();
1325 Step::Continue
1326 }
1327 _ => Step::Done,
1328 }
1329 }
1330
1331 #[allow(clippy::too_many_arguments)]
1332 fn run_jobs(
1333 mut commands: Commands,
1334 mut map: ResMut<WorldMap>,
1335 mut zones: ResMut<Zones>,
1336 mut reservations: ResMut<Reservations>,
1337 mut rng: ResMut<SimRng>,
1338 item_assets: Res<ItemAssets>,
1339 structure_assets: Res<StructureAssets>,
1340 light: Res<LightMap>,
1341 tick: Res<SimTick>,
1342 mut blueprints: ResMut<Blueprints>,
1343 mut goals: ResMut<ColonyGoals>,
1344 mut items: ItemQuery,
1345 mut structures: Query<(Entity, &TilePos, &Structure, Option<&mut Fuel>), Without<Colonist>>,
1346 animals: Query<(&TilePos, &Path), (With<Animal>, Without<Colonist>)>,
1347 messages: (MessageWriter<TileChanged>, MessageWriter<Ate>),
1348 mut colonists: Query<
1349 (
1350 Entity,
1351 &TilePos,
1352 &mut Path,
1353 &mut CurrentJob,
1354 &mut IdleTimer,
1355 &mut Carrying,
1356 &Rest,
1357 &mut Hunger,
1358 Has<Sick>,
1359 ),
1360 With<Colonist>,
1361 >,
1362 ) {
1363 let (mut changed, mut ate) = messages;
1364 let hour = hour_of_day(*tick);
1365 let occupied: Vec<UVec2> = colonists
1366 .iter()
1367 .flat_map(|c| [Some(c.1.0), c.2.0.front().copied()])
1368 .chain(
1369 animals
1370 .iter()
1371 .flat_map(|(t, p)| [Some(t.0), p.0.front().copied()]),
1372 )
1373 .flatten()
1374 .collect();
1375 for (entity, tile, mut path, mut current, mut idle, mut carrying, rest, mut hunger, sick) in
1376 &mut colonists
1377 {
1378 let Some(mut job) = current.0 else {
1379 continue;
1380 };
1381 let rate = match work_rate(&light, tile.0) {
1382 rate if sick => rate.div_ceil(2),
1383 rate => rate,
1384 };
1385 if !path.0.is_empty() {
1386 continue;
1387 }
1388 let step = match &mut job.task {
1389 Task::MoveTo(_) => Step::Done,
1390 Task::Cook {
1391 pickup,
1392 station,
1393 progress,
1394 } => {
1395 let station = *station;
1396 let fire = structures
1397 .iter()
1398 .any(|(_, pos, s, _)| pos.0 == station && s.kind == StructureKind::Campfire);
1399 let ours = reservations.holder(Target::Station(station)) == Some(entity);
1400 if !fire || !ours {
1401 Step::Done
1402 } else if let Some(from) = *pickup {
1403 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1404 Step::Done
1405 } else if tile.0 != from {
1406 walk_to(&map, tile.0, from, &mut path)
1407 } else {
1408 let load = take_items(&mut commands, &mut items, from, COOK_INPUT)
1409 .filter(|load| load.kind.is_raw_food() && load.count > 0);
1410 carrying.0 = load;
1411 reservations.release(Target::Pickup(from));
1412 match load {
1413 Some(load) if load.count >= COOK_INPUT => {
1414 *pickup = None;
1415 Step::Continue
1416 }
1417 _ => Step::Done,
1418 }
1419 }
1420 } else if !carrying
1421 .0
1422 .is_some_and(|load| load.kind.is_raw_food() && load.count >= COOK_INPUT)
1423 {
1424 Step::Done
1425 } else if !is_adjacent(tile.0.as_ivec2(), station.as_ivec2()) {
1426 match find_path_adjacent(&map, tile.0, station) {
1427 Some(p) if !p.is_empty() => {
1428 path.0 = p.into();
1429 Step::Continue
1430 }
1431 _ => Step::Done,
1432 }
1433 } else {
1434 *progress += rate;
1435 if *progress < COOK_WORK {
1436 Step::Continue
1437 } else {
1438 if let Some(load) = carrying.0 {
1439 goals.record_use(load.kind, COOK_INPUT);
1440 }
1441 carrying.0 = carrying.0.and_then(|load| {
1442 (load.count > COOK_INPUT).then_some(Item {
1443 count: load.count - COOK_INPUT,
1444 ..load
1445 })
1446 });
1447 drop_items(
1448 &mut commands,
1449 &mut items,
1450 &item_assets,
1451 tile.0,
1452 Item::new(ItemKind::Meal, 1),
1453 );
1454 Step::Done
1455 }
1456 }
1457 }
1458 Task::Hunt {
1459 animal,
1460 kind,
1461 progress,
1462 } => match animals.get(*animal) {
1463 Ok((prey, _)) if reservations.holder(Target::Animal(*animal)) == Some(entity) => {
1464 let prey = prey.0;
1465 let in_range = tile.0.as_vec2().distance(prey.as_vec2()) <= HUNT_RANGE
1466 && line_of_sight(&map, tile.0, prey);
1467 let stale = path.0.back().is_none_or(|end| {
1468 end.as_vec2().distance(prey.as_vec2()) > HUNT_RANGE / 2.0
1469 });
1470 if !in_range && !stale {
1471 Step::Continue
1472 } else if !in_range {
1473 match find_path_adjacent(&map, tile.0, prey) {
1474 Some(p) if !p.is_empty() => {
1475 path.0 = p.into();
1476 Step::Continue
1477 }
1478 _ => Step::Done,
1479 }
1480 } else {
1481 path.0.truncate(1);
1482 *progress += rate;
1483 if *progress < kind.hunt_work() {
1484 Step::Continue
1485 } else {
1486 commands.entity(*animal).despawn();
1487 drop_items(
1488 &mut commands,
1489 &mut items,
1490 &item_assets,
1491 prey,
1492 Item::new(ItemKind::Carcass, kind.meat()),
1493 );
1494 Step::Done
1495 }
1496 }
1497 }
1498 _ => Step::Done,
1499 },
1500 Task::Tame {
1501 animal,
1502 kind,
1503 progress,
1504 } => match animals.get(*animal) {
1505 Ok((prey, _)) if reservations.holder(Target::Animal(*animal)) == Some(entity) => {
1506 let prey = prey.0;
1507 if prey != tile.0 && !is_adjacent(tile.0.as_ivec2(), prey.as_ivec2()) {
1508 if path.0.is_empty() {
1509 match find_path_adjacent(&map, tile.0, prey) {
1510 Some(p) if !p.is_empty() => {
1511 path.0 = p.into();
1512 Step::Continue
1513 }
1514 _ => Step::Done,
1515 }
1516 } else {
1517 Step::Continue
1518 }
1519 } else {
1520 *progress += rate;
1521 if *progress < kind.tame_work() {
1522 Step::Continue
1523 } else {
1524 commands.entity(*animal).insert(Tame);
1525 Step::Done
1526 }
1527 }
1528 }
1529 _ => Step::Done,
1530 },
1531 Task::Butcher { site, progress } => {
1532 let site = *site;
1533 if reservations.holder(Target::Pickup(site)) != Some(entity) {
1534 Step::Done
1535 } else if tile.0 != site {
1536 walk_to(&map, tile.0, site, &mut path)
1537 } else {
1538 *progress += rate;
1539 if *progress < BUTCHER_WORK {
1540 Step::Continue
1541 } else {
1542 let is_carcass = items
1543 .iter()
1544 .any(|(_, item, pos)| pos.0 == site && item.kind == ItemKind::Carcass);
1545 if is_carcass
1546 && let Some(carcass) =
1547 take_items(&mut commands, &mut items, site, u32::MAX)
1548 {
1549 let meat = Item {
1550 kind: ItemKind::Meat,
1551 ..carcass
1552 };
1553 drop_items(&mut commands, &mut items, &item_assets, site, meat);
1554 }
1555 Step::Done
1556 }
1557 }
1558 }
1559 Task::Eat { pickup, progress } => {
1560 if let Some(from) = *pickup {
1561 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1562 Step::Done
1563 } else if tile.0 != from {
1564 walk_to(&map, tile.0, from, &mut path)
1565 } else {
1566 let kind = items
1567 .iter()
1568 .find(|(_, item, pos)| pos.0 == from && item.kind.is_food())
1569 .map(|(_, item, _)| item.kind);
1570 let meal = kind.and_then(|kind| {
1571 take_items(&mut commands, &mut items, from, portion(kind, hunger.0))
1572 });
1573 reservations.release(Target::Pickup(from));
1574 match meal.filter(|m| m.kind.is_food()) {
1575 Some(meal) => {
1576 carrying.0 = Some(meal);
1577 *pickup = None;
1578 Step::Continue
1579 }
1580 None => Step::Done,
1581 }
1582 }
1583 } else if let Some(meal) = carrying.0.filter(|m| m.kind.is_food()) {
1584 *progress += 1;
1585 if *progress < EAT_TICKS {
1586 Step::Continue
1587 } else {
1588 hunger.0 = (hunger.0 + meal.count as f32 * meal.kind.nutrition()).min(1.0);
1589 goals.record_use(meal.kind, meal.count);
1590 ate.write(Ate {
1591 colonist: entity,
1592 kind: meal.kind,
1593 });
1594 carrying.0 = None;
1595 Step::Done
1596 }
1597 } else {
1598 Step::Done
1599 }
1600 }
1601 Task::Sleep { spot } => {
1602 if reservations.holder(Target::SleepSpot(*spot)) != Some(entity) {
1603 Step::Done
1604 } else if tile.0 != *spot {
1605 let step = walk_to(&map, tile.0, *spot, &mut path);
1606 if matches!(step, Step::Done) {
1607 reservations.release(Target::SleepSpot(*spot));
1608 *spot = tile.0;
1609 reservations.reserve(Target::SleepSpot(*spot), entity);
1610 }
1611 Step::Continue
1612 } else if done_sleeping(rest.0, hour) {
1613 Step::Done
1614 } else {
1615 Step::Continue
1616 }
1617 }
1618 Task::Work {
1619 site,
1620 kind,
1621 progress,
1622 } => {
1623 let (site, kind) = (*site, *kind);
1624 let work = site_work(&map, site).filter(|w| w.kind == kind);
1625 let valid =
1626 work.is_some() || (kind == WorkKind::Sow && sowable(&map, &zones, site));
1627 let ours = reservations.holder(Target::Site(site)) == Some(entity);
1628 if !valid || !ours {
1629 Step::Done
1630 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
1631 match find_path_adjacent(&map, tile.0, site) {
1632 Some(p) if !p.is_empty() => {
1633 path.0 = p.into();
1634 Step::Continue
1635 }
1636 _ => Step::Done,
1637 }
1638 } else {
1639 *progress += rate;
1640 if *progress < kind.work() {
1641 Step::Continue
1642 } else {
1643 kind.complete(&mut map, site);
1644 changed.write(TileChanged(site));
1645 if let Some(work) = work {
1646 drop_items(
1647 &mut commands,
1648 &mut items,
1649 &item_assets,
1650 site,
1651 Item::new(work.item, work.count),
1652 );
1653 }
1654 Step::Done
1655 }
1656 }
1657 }
1658 Task::ExpandStockpile { site, progress } => {
1659 if tile.0 != *site {
1660 walk_to(&map, tile.0, *site, &mut path)
1661 } else {
1662 *progress += rate;
1663 if *progress >= EXPAND_WORK {
1664 if zones.has_stockpile() {
1665 let excluded = blueprints.tiles();
1666 let tiles = plan_expansion(&map, &zones, &excluded, EXPANSION_TILES);
1667 zones.add_tiles(&map, tiles);
1668 } else {
1669 zones.add_tiles(&map, new_stockpile_tiles(*site));
1670 }
1671 Step::Done
1672 } else {
1673 Step::Continue
1674 }
1675 }
1676 }
1677 Task::Build {
1678 site,
1679 kind,
1680 pickup,
1681 progress,
1682 } => {
1683 let (site, kind) = (*site, *kind);
1684 let ours = reservations.holder(Target::Site(site)) == Some(entity);
1685 let planned = match kind {
1686 BuildKind::Structure(
1687 StructureKind::Campfire | StructureKind::Torch | StructureKind::Bed,
1688 )
1689 | BuildKind::Refuel(_) => true,
1690 _ => blueprints.get(site) == Some(kind),
1691 };
1692 let structure_there = structures.iter().any(|(_, pos, ..)| pos.0 == site);
1693 let blocked = map.plant(site.as_ivec2()).is_some()
1694 || match kind {
1695 BuildKind::Roof => false,
1696 BuildKind::Refuel(fire) => !structures
1697 .iter()
1698 .any(|(_, pos, s, _)| pos.0 == site && s.kind == fire),
1699 BuildKind::Deconstruct => !structure_there,
1700 _ => structure_there,
1701 };
1702 let (material, cost) = kind.cost();
1703 if !ours || blocked || !planned {
1704 Step::Done
1705 } else if let Some(from) = *pickup {
1706 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1707 Step::Done
1708 } else if tile.0 != from {
1709 walk_to(&map, tile.0, from, &mut path)
1710 } else if carrying.0.is_some_and(|load| load.kind != material) {
1711 Step::Done
1712 } else {
1713 let have = carrying.0.map_or(0, |load| load.count);
1714 let taken = take_items(&mut commands, &mut items, from, cost - have)
1715 .filter(|load| load.kind == material)
1716 .map_or(0, |load| load.count);
1717 reservations.release(Target::Pickup(from));
1718 let total = have + taken;
1719 carrying.0 = (total > 0).then_some(Item::new(material, total));
1720 let next = nearest_tile(&map, tile.0, SEARCH_TILES, |p| {
1721 reservations.is_free(Target::Pickup(p))
1722 && items.iter().any(|(_, item, pos)| {
1723 pos.0 == p && item.kind == material && item.count > 0
1724 })
1725 });
1726 match next {
1727 _ if total >= cost => {
1728 *pickup = None;
1729 Step::Continue
1730 }
1731 Some(next) => {
1732 reservations.reserve(Target::Pickup(next), entity);
1733 *pickup = Some(next);
1734 Step::Continue
1735 }
1736 None => Step::Done,
1737 }
1738 }
1739 } else if cost > 0
1740 && !carrying
1741 .0
1742 .is_some_and(|load| load.kind == material && load.count >= cost)
1743 {
1744 Step::Done
1745 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
1746 match find_path_adjacent(&map, tile.0, site) {
1747 Some(p) if !p.is_empty() => {
1748 path.0 = p.into();
1749 Step::Continue
1750 }
1751 _ => Step::Done,
1752 }
1753 } else {
1754 *progress = (*progress + rate).min(kind.work());
1755 let someone_in_the_way = kind.blocks_tile() && occupied.contains(&site);
1756 if *progress < kind.work() || someone_in_the_way {
1757 Step::Continue
1758 } else {
1759 goals.record_use(material, cost);
1760 carrying.0 = carrying.0.and_then(|load| {
1761 (load.count > cost).then_some(Item {
1762 count: load.count - cost,
1763 ..load
1764 })
1765 });
1766 match kind {
1767 BuildKind::Structure(structure) => {
1768 spawn_structure(&mut commands, &structure_assets, site, structure);
1769 if kind.blocks_tile() {
1770 map.set_wall(site, true);
1771 changed.write(TileChanged(site));
1772 }
1773 }
1774 BuildKind::Roof => {
1775 map.set_roof(site, true);
1776 changed.write(TileChanged(site));
1777 }
1778 BuildKind::Pave => {
1779 map.set(site, Terrain::Paved);
1780 changed.write(TileChanged(site));
1781 }
1782 BuildKind::Deconstruct => {
1783 for (entity, pos, structure, _) in &structures {
1784 if pos.0 != site {
1785 continue;
1786 }
1787 commands.entity(entity).despawn();
1788 let (refund, amount) = structure.kind.cost();
1789 if amount / 2 > 0 {
1790 drop_items(
1791 &mut commands,
1792 &mut items,
1793 &item_assets,
1794 site,
1795 Item::new(refund, amount / 2),
1796 );
1797 }
1798 }
1799 if map.is_wall(site.as_ivec2()) {
1800 map.set_wall(site, false);
1801 changed.write(TileChanged(site));
1802 }
1803 }
1804 BuildKind::Refuel(fire) => {
1805 for (_, pos, _, fuel) in &mut structures {
1806 if pos.0 == site
1807 && let Some(mut fuel) = fuel
1808 {
1809 fuel.0 = fire.fuel_ticks().unwrap_or(fuel.0);
1810 }
1811 }
1812 }
1813 }
1814 blueprints.0.remove(&site);
1815 Step::Done
1816 }
1817 }
1818 }
1819 Task::Haul { pickup, to } => {
1820 let to = *to;
1821 let destination_valid = zones.is_stockpile(to)
1822 && reservations.holder(Target::Storage(to)) == Some(entity);
1823 if !destination_valid {
1824 Step::Done
1825 } else if let Some(from) = *pickup {
1826 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1827 Step::Done
1828 } else if tile.0 != from {
1829 walk_to(&map, tile.0, from, &mut path)
1830 } else {
1831 let kind = items
1832 .iter()
1833 .find(|(_, _, pos)| pos.0 == from)
1834 .map(|(_, item, _)| item.kind);
1835 let room = kind.map_or(0, |kind| {
1836 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
1837 });
1838 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
1839 .filter(|load| load.count > 0)
1840 {
1841 Some(load) => {
1842 carrying.0 = Some(load);
1843 reservations.release(Target::Pickup(from));
1844 *pickup = None;
1845 Step::Continue
1846 }
1847 None => Step::Done,
1848 }
1849 }
1850 } else if let Some(load) = carrying.0 {
1851 if tile.0 != to {
1852 walk_to(&map, tile.0, to, &mut path)
1853 } else {
1854 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
1855 let dropped = load.count.min(room);
1856 if dropped > 0 {
1857 drop_items(
1858 &mut commands,
1859 &mut items,
1860 &item_assets,
1861 to,
1862 load.with_count(dropped),
1863 );
1864 }
1865 carrying.0 = (load.count > dropped).then_some(Item {
1866 count: load.count - dropped,
1867 ..load
1868 });
1869 Step::Done
1870 }
1871 } else {
1872 Step::Done
1873 }
1874 }
1875 };
1876 match step {
1877 Step::Continue => current.0 = Some(job),
1878 Step::Done => {
1879 reservations.release_all(entity);
1880 current.0 = None;
1881 let ordered_move = matches!(
1882 job,
1883 Job {
1884 task: Task::MoveTo(_),
1885 ordered: true
1886 }
1887 );
1888 idle.restart(if ordered_move {
1889 IDLE_AFTER_ORDER_SECS
1890 } else {
1891 rng.range_f32(WORK_PAUSE_SECS)
1892 });
1893 }
1894 }
1895 }
1896 }
1897
1898 #[cfg(test)]
1899 mod tests;