src/jobs/mod.rs 49.4 K · 1430 lines · raw · history

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