src/jobs/mod.rs 58.8 K · 1667 lines · raw · history

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