src/jobs/mod.rs 77.5 K · 2239 lines · raw · history

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