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