src/jobs/mod.rs 49.3 K · 1428 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,
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_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 if sources.is_empty() {
686 return None;
687 }
688 nearest_tile(ctx.map, from, SEARCH_TILES, |p| sources.contains(&p))
689 }
690
691 pub fn find_cooking(ctx: &BuildContext, from: UVec2) -> Option<Task> {
692 let station = ctx
693 .structures
694 .iter()
695 .filter(|&&(pos, kind, fuel)| {
696 kind == StructureKind::Campfire
697 && fuel >= COOK_MIN_FUEL
698 && ctx.reservations.is_free(Target::Station(pos))
699 })
700 .map(|&(pos, ..)| pos)
701 .min_by(|a, b| {
702 a.as_vec2()
703 .distance_squared(from.as_vec2())
704 .total_cmp(&b.as_vec2().distance_squared(from.as_vec2()))
705 })?;
706 let pickup = raw_food_source(ctx, from)?;
707 Some(Task::Cook {
708 pickup: Some(pickup),
709 station,
710 progress: 0,
711 })
712 }
713
714 pub fn find_lighting(ctx: &BuildContext, from: UVec2) -> Option<Task> {
715 let home = ctx.zones.home(from);
716 let (kind, site) = if ctx.campfire_needed(home) {
717 (StructureKind::Campfire, ctx.site_near(home, HOME_RADIUS)?)
718 } else {
719 let dark = ctx.darkest_stockpile_tile(home)?;
720 let reach = StructureKind::Torch.radius() * 0.6;
721 (StructureKind::Torch, ctx.site_near(dark, reach)?)
722 };
723 ctx.build_task(from, site, BuildKind::Structure(kind))
724 }
725
726 pub fn find_bed_site(ctx: &BuildContext, colonists: usize, from: UVec2) -> Option<Task> {
727 if ctx.count(StructureKind::Bed) >= colonists {
728 return None;
729 }
730 let anchor = ctx.bed_anchor(ctx.zones.home(from));
731 let site = ctx.site_near_where(anchor, HOME_RADIUS * 1.5, |p| ctx.clear_of_stockpile(p))?;
732 ctx.build_task(from, site, BuildKind::Structure(StructureKind::Bed))
733 }
734
735 pub fn find_blueprint_work(ctx: &BuildContext, from: UVec2) -> Option<Task> {
736 let mut found = None;
737 nearest_tile(ctx.map, from, SEARCH_TILES, |p| {
738 let Some(kind) = ctx.blueprints.get(p) else {
739 return false;
740 };
741 if !ctx.reservations.is_free(Target::Site(p)) {
742 return false;
743 }
744 found = ctx.build_task(from, p, kind);
745 found.is_some()
746 })?;
747 found
748 }
749
750 fn on_the_way(map: &WorldMap, jobs: impl Iterator<Item = Option<Job>>) -> HashMap<ItemKind, u32> {
751 let mut totals = HashMap::new();
752 for job in jobs.flatten() {
753 if let Task::Work { site, .. } = job.task
754 && let Some(work) = site_work(map, site)
755 {
756 *totals.entry(work.item).or_insert(0) += work.count;
757 }
758 }
759 totals
760 }
761
762 #[allow(clippy::too_many_arguments)]
763 fn choose_jobs(
764 mut commands: Commands,
765 time: Res<Time>,
766 map: Res<WorldMap>,
767 zones: Res<Zones>,
768 goals: Res<ColonyGoals>,
769 item_assets: Res<ItemAssets>,
770 tick: Res<SimTick>,
771 blueprints: Res<Blueprints>,
772 mut rng: ResMut<SimRng>,
773 mut reservations: ResMut<Reservations>,
774 mut items: ItemQuery,
775 structures: Query<(&TilePos, &Structure, Option<&Fuel>), Without<Colonist>>,
776 animals: Query<(Entity, &TilePos, &Animal), Without<Colonist>>,
777 mut colonists: Query<
778 (
779 Entity,
780 &TilePos,
781 &mut Path,
782 &mut CurrentJob,
783 &mut IdleTimer,
784 &mut Carrying,
785 &Rest,
786 &Hunger,
787 ),
788 With<Colonist>,
789 >,
790 ) {
791 let wildlife: Vec<(Entity, UVec2, AnimalKind)> = animals
792 .iter()
793 .map(|(e, pos, a)| (e, pos.0, a.kind))
794 .collect();
795 let colonist_count = colonists.iter().count();
796 let structures_list: Vec<(UVec2, StructureKind, u32)> = structures
797 .iter()
798 .map(|(pos, s, fuel)| (pos.0, s.kind, fuel.map_or(u32::MAX, |f| f.0)))
799 .collect();
800 let mut planned: Vec<(UVec2, StructureKind)> = colonists
801 .iter()
802 .filter_map(|c| match c.3.0?.task {
803 Task::Build {
804 site,
805 kind: BuildKind::Structure(kind),
806 ..
807 } => Some((site, kind)),
808 _ => None,
809 })
810 .collect();
811 let dark = dark_soon(*tick);
812 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
813 let stocks: HashMap<ItemKind, u32> = ItemKind::ALL
814 .iter()
815 .map(|&kind| {
816 let all = items.iter().map(|(_, item, _)| item).chain(carried.iter());
817 (kind, stock(all, kind))
818 })
819 .collect();
820 let mut pending = on_the_way(&map, colonists.iter().map(|c| c.3.0));
821 for job in colonists.iter().filter_map(|c| c.3.0) {
822 match job.task {
823 Task::Hunt { kind, .. } => *pending.entry(ItemKind::Meat).or_insert(0) += kind.meat(),
824 Task::Cook { .. } => *pending.entry(ItemKind::Meal).or_insert(0) += 1,
825 _ => {}
826 }
827 }
828 let food_tiles: HashSet<UVec2> = items
829 .iter()
830 .filter(|(_, item, _)| item.kind.is_food())
831 .map(|(_, _, pos)| pos.0)
832 .collect();
833 let hour = hour_of_day(*tick);
834 for (entity, tile, mut path, mut job, mut idle, mut carrying, rest, hunger) in &mut colonists {
835 let exhausted = rest.0 < EXHAUSTED_REST;
836 let starving = hunger.0 < STARVING && food_to_fetch(&reservations, &food_tiles);
837 let urgent = exhausted || starving;
838 if urgent
839 && job.0.is_some_and(|j| {
840 !j.ordered && !matches!(j.task, Task::Sleep { .. } | Task::Eat { .. })
841 })
842 {
843 reservations.release_all(entity);
844 job.0 = None;
845 path.0.truncate(1);
846 }
847 let rested = idle.0.tick(time.delta()).is_finished();
848 if job.0.is_some() || !path.0.is_empty() || !(rested || urgent) {
849 continue;
850 }
851 let snapshot: Vec<(Item, TilePos)> =
852 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
853 let refs = snapshot.iter().map(|(i, p)| (i, p));
854 let wanted = |kind: ItemKind| goals.wanted(kind, &stocks, &pending);
855 let sleep = SleepContext {
856 map: &map,
857 zones: &zones,
858 reservations: &reservations,
859 items: &snapshot,
860 structures: &structures_list,
861 blueprints: &blueprints,
862 };
863 let food = wants_food(hunger.0)
864 .then(|| find_food(&map, &reservations, &snapshot, tile.0))
865 .flatten();
866 let task = if exhausted {
867 Some(Task::Sleep {
868 spot: sleep.spot(tile.0),
869 })
870 } else if let Some(pickup) = food {
871 if let Some(load) = carrying.0.take() {
872 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
873 }
874 Some(Task::Eat {
875 pickup: Some(pickup),
876 progress: 0,
877 })
878 } else if wants_sleep(rest.0, hour) {
879 Some(Task::Sleep {
880 spot: sleep.spot(tile.0),
881 })
882 } else if let Some(load) = carrying.0 {
883 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
884 if storage.is_none() {
885 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
886 carrying.0 = None;
887 }
888 storage.map(|to| Task::Haul { pickup: None, to })
889 } else {
890 let build = BuildContext {
891 map: &map,
892 zones: &zones,
893 reservations: &reservations,
894 items: &snapshot,
895 structures: &structures_list,
896 planned: &planned,
897 blueprints: &blueprints,
898 };
899 find_expansion(&map, &zones, &reservations, &snapshot, &blueprints)
900 .or_else(|| dark.then(|| find_lighting(&build, tile.0)).flatten())
901 .or_else(|| {
902 let cooking =
903 wanted(ItemKind::Meal) && raw_food_source(&build, tile.0).is_some();
904 cooking
905 .then(|| {
906 find_cooking(&build, tile.0).or_else(|| find_campfire(&build, tile.0))
907 })
908 .flatten()
909 })
910 .or_else(|| find_bed_site(&build, colonist_count, tile.0))
911 .or_else(|| find_blueprint_work(&build, tile.0))
912 .or_else(|| find_work(&map, &reservations, tile.0, wanted))
913 .or_else(|| {
914 wanted(ItemKind::Meat)
915 .then(|| find_hunt(&map, &reservations, &wildlife, tile.0))
916 .flatten()
917 })
918 .or_else(|| find_sowing(&map, &zones, &reservations, tile.0))
919 .or_else(|| find_haul(&map, &zones, &reservations, &snapshot, tile.0))
920 };
921 if let Some(task) = task {
922 if let Task::Work { site, .. } = task
923 && let Some(work) = site_work(&map, site)
924 {
925 *pending.entry(work.item).or_insert(0) += work.count;
926 }
927 match task {
928 Task::Hunt { kind, .. } => {
929 *pending.entry(ItemKind::Meat).or_insert(0) += kind.meat()
930 }
931 Task::Cook { .. } => *pending.entry(ItemKind::Meal).or_insert(0) += 1,
932 _ => {}
933 }
934 if let Task::Build {
935 site,
936 kind: BuildKind::Structure(kind),
937 ..
938 } = task
939 {
940 planned.push((site, kind));
941 }
942 reserve_task(&mut reservations, task, entity);
943 job.0 = Some(Job {
944 task,
945 ordered: false,
946 });
947 continue;
948 }
949 let goal = tile.0.as_ivec2()
950 + IVec2::new(
951 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
952 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
953 );
954 if map.in_bounds(goal)
955 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
956 {
957 path.0 = wander_path.into();
958 idle.restart(rng.range_f32(IDLE_SECS));
959 }
960 }
961 }
962
963 enum Step {
964 Continue,
965 Done,
966 }
967
968 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
969 match find_path(map, from, to) {
970 Some(p) if !p.is_empty() => {
971 path.0 = p.into();
972 Step::Continue
973 }
974 _ => Step::Done,
975 }
976 }
977
978 #[allow(clippy::too_many_arguments)]
979 fn run_jobs(
980 mut commands: Commands,
981 mut map: ResMut<WorldMap>,
982 mut zones: ResMut<Zones>,
983 mut reservations: ResMut<Reservations>,
984 mut rng: ResMut<SimRng>,
985 item_assets: Res<ItemAssets>,
986 structure_assets: Res<StructureAssets>,
987 light: Res<LightMap>,
988 tick: Res<SimTick>,
989 mut blueprints: ResMut<Blueprints>,
990 mut goals: ResMut<ColonyGoals>,
991 mut items: ItemQuery,
992 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
993 animals: Query<(&TilePos, &Path), (With<Animal>, Without<Colonist>)>,
994 mut changed: MessageWriter<TileChanged>,
995 mut colonists: Query<
996 (
997 Entity,
998 &TilePos,
999 &mut Path,
1000 &mut CurrentJob,
1001 &mut IdleTimer,
1002 &mut Carrying,
1003 &Rest,
1004 &mut Hunger,
1005 ),
1006 With<Colonist>,
1007 >,
1008 ) {
1009 let hour = hour_of_day(*tick);
1010 let occupied: Vec<UVec2> = colonists
1011 .iter()
1012 .flat_map(|c| [Some(c.1.0), c.2.0.front().copied()])
1013 .chain(
1014 animals
1015 .iter()
1016 .flat_map(|(t, p)| [Some(t.0), p.0.front().copied()]),
1017 )
1018 .flatten()
1019 .collect();
1020 for (entity, tile, mut path, mut current, mut idle, mut carrying, rest, mut hunger) in
1021 &mut colonists
1022 {
1023 let Some(mut job) = current.0 else {
1024 continue;
1025 };
1026 if !path.0.is_empty() {
1027 continue;
1028 }
1029 let step = match &mut job.task {
1030 Task::MoveTo(_) => Step::Done,
1031 Task::Cook {
1032 pickup,
1033 station,
1034 progress,
1035 } => {
1036 let station = *station;
1037 let fire = structures
1038 .iter()
1039 .any(|(pos, s)| pos.0 == station && s.kind == StructureKind::Campfire);
1040 let ours = reservations.holder(Target::Station(station)) == Some(entity);
1041 if !fire || !ours {
1042 Step::Done
1043 } else if let Some(from) = *pickup {
1044 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1045 Step::Done
1046 } else if tile.0 != from {
1047 walk_to(&map, tile.0, from, &mut path)
1048 } else {
1049 let load = take_items(&mut commands, &mut items, from, COOK_INPUT)
1050 .filter(|load| load.kind.is_raw_food() && load.count > 0);
1051 carrying.0 = load;
1052 reservations.release(Target::Pickup(from));
1053 match load {
1054 Some(load) if load.count >= COOK_INPUT => {
1055 *pickup = None;
1056 Step::Continue
1057 }
1058 _ => Step::Done,
1059 }
1060 }
1061 } else if !carrying
1062 .0
1063 .is_some_and(|load| load.kind.is_raw_food() && load.count >= COOK_INPUT)
1064 {
1065 Step::Done
1066 } else if !is_adjacent(tile.0.as_ivec2(), station.as_ivec2()) {
1067 match find_path_adjacent(&map, tile.0, station) {
1068 Some(p) if !p.is_empty() => {
1069 path.0 = p.into();
1070 Step::Continue
1071 }
1072 _ => Step::Done,
1073 }
1074 } else {
1075 *progress += work_rate(&light, tile.0);
1076 if *progress < COOK_WORK {
1077 Step::Continue
1078 } else {
1079 if let Some(load) = carrying.0 {
1080 goals.record_use(load.kind, COOK_INPUT);
1081 }
1082 carrying.0 = carrying.0.and_then(|load| {
1083 (load.count > COOK_INPUT).then_some(Item {
1084 count: load.count - COOK_INPUT,
1085 ..load
1086 })
1087 });
1088 drop_items(
1089 &mut commands,
1090 &mut items,
1091 &item_assets,
1092 tile.0,
1093 Item::new(ItemKind::Meal, 1),
1094 );
1095 Step::Done
1096 }
1097 }
1098 }
1099 Task::Hunt {
1100 animal,
1101 kind,
1102 progress,
1103 } => match animals.get(*animal) {
1104 Ok((prey, _)) if reservations.holder(Target::Animal(*animal)) == Some(entity) => {
1105 let prey = prey.0;
1106 if prey != tile.0 && !is_adjacent(tile.0.as_ivec2(), prey.as_ivec2()) {
1107 match find_path_adjacent(&map, tile.0, prey) {
1108 Some(p) if !p.is_empty() => {
1109 path.0 = p.into();
1110 Step::Continue
1111 }
1112 _ => Step::Done,
1113 }
1114 } else {
1115 *progress += work_rate(&light, tile.0);
1116 if *progress < kind.hunt_work() {
1117 Step::Continue
1118 } else {
1119 commands.entity(*animal).despawn();
1120 drop_items(
1121 &mut commands,
1122 &mut items,
1123 &item_assets,
1124 prey,
1125 Item::new(ItemKind::Meat, kind.meat()),
1126 );
1127 Step::Done
1128 }
1129 }
1130 }
1131 _ => Step::Done,
1132 },
1133 Task::Eat { pickup, progress } => {
1134 if let Some(from) = *pickup {
1135 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1136 Step::Done
1137 } else if tile.0 != from {
1138 walk_to(&map, tile.0, from, &mut path)
1139 } else {
1140 let kind = items
1141 .iter()
1142 .find(|(_, item, pos)| pos.0 == from && item.kind.is_food())
1143 .map(|(_, item, _)| item.kind);
1144 let meal = kind.and_then(|kind| {
1145 take_items(&mut commands, &mut items, from, portion(kind, hunger.0))
1146 });
1147 reservations.release(Target::Pickup(from));
1148 match meal.filter(|m| m.kind.is_food()) {
1149 Some(meal) => {
1150 carrying.0 = Some(meal);
1151 *pickup = None;
1152 Step::Continue
1153 }
1154 None => Step::Done,
1155 }
1156 }
1157 } else if let Some(meal) = carrying.0.filter(|m| m.kind.is_food()) {
1158 *progress += 1;
1159 if *progress < EAT_TICKS {
1160 Step::Continue
1161 } else {
1162 hunger.0 = (hunger.0 + meal.count as f32 * meal.kind.nutrition()).min(1.0);
1163 goals.record_use(meal.kind, meal.count);
1164 carrying.0 = None;
1165 Step::Done
1166 }
1167 } else {
1168 Step::Done
1169 }
1170 }
1171 Task::Sleep { spot } => {
1172 if reservations.holder(Target::SleepSpot(*spot)) != Some(entity) {
1173 Step::Done
1174 } else if tile.0 != *spot {
1175 let step = walk_to(&map, tile.0, *spot, &mut path);
1176 if matches!(step, Step::Done) {
1177 reservations.release(Target::SleepSpot(*spot));
1178 *spot = tile.0;
1179 reservations.reserve(Target::SleepSpot(*spot), entity);
1180 }
1181 Step::Continue
1182 } else if done_sleeping(rest.0, hour) {
1183 Step::Done
1184 } else {
1185 Step::Continue
1186 }
1187 }
1188 Task::Work {
1189 site,
1190 kind,
1191 progress,
1192 } => {
1193 let (site, kind) = (*site, *kind);
1194 let work = site_work(&map, site).filter(|w| w.kind == kind);
1195 let valid =
1196 work.is_some() || (kind == WorkKind::Sow && sowable(&map, &zones, site));
1197 let ours = reservations.holder(Target::Site(site)) == Some(entity);
1198 if !valid || !ours {
1199 Step::Done
1200 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
1201 match find_path_adjacent(&map, tile.0, site) {
1202 Some(p) if !p.is_empty() => {
1203 path.0 = p.into();
1204 Step::Continue
1205 }
1206 _ => Step::Done,
1207 }
1208 } else {
1209 *progress += work_rate(&light, tile.0);
1210 if *progress < kind.work() {
1211 Step::Continue
1212 } else {
1213 kind.complete(&mut map, site);
1214 changed.write(TileChanged(site));
1215 if let Some(work) = work {
1216 drop_items(
1217 &mut commands,
1218 &mut items,
1219 &item_assets,
1220 site,
1221 Item::new(work.item, work.count),
1222 );
1223 }
1224 Step::Done
1225 }
1226 }
1227 }
1228 Task::ExpandStockpile { site, progress } => {
1229 if tile.0 != *site {
1230 walk_to(&map, tile.0, *site, &mut path)
1231 } else {
1232 *progress += work_rate(&light, tile.0);
1233 if *progress >= EXPAND_WORK {
1234 if zones.has_stockpile() {
1235 let excluded = blueprints.tiles();
1236 let tiles = plan_expansion(&map, &zones, &excluded, EXPANSION_TILES);
1237 zones.add_tiles(&map, tiles);
1238 } else {
1239 zones.add_tiles(&map, new_stockpile_tiles(*site));
1240 }
1241 Step::Done
1242 } else {
1243 Step::Continue
1244 }
1245 }
1246 }
1247 Task::Build {
1248 site,
1249 kind,
1250 pickup,
1251 progress,
1252 } => {
1253 let (site, kind) = (*site, *kind);
1254 let ours = reservations.holder(Target::Site(site)) == Some(entity);
1255 let planned = match kind {
1256 BuildKind::Structure(
1257 StructureKind::Campfire | StructureKind::Torch | StructureKind::Bed,
1258 ) => true,
1259 _ => blueprints.get(site) == Some(kind),
1260 };
1261 let blocked = map.plant(site.as_ivec2()).is_some()
1262 || (kind != BuildKind::Roof && structures.iter().any(|(pos, _)| pos.0 == site));
1263 let (material, cost) = kind.cost();
1264 if !ours || blocked || !planned {
1265 Step::Done
1266 } else if let Some(from) = *pickup {
1267 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1268 Step::Done
1269 } else if tile.0 != from {
1270 walk_to(&map, tile.0, from, &mut path)
1271 } else if carrying.0.is_some_and(|load| load.kind != material) {
1272 Step::Done
1273 } else {
1274 let have = carrying.0.map_or(0, |load| load.count);
1275 let taken = take_items(&mut commands, &mut items, from, cost - have)
1276 .filter(|load| load.kind == material)
1277 .map_or(0, |load| load.count);
1278 reservations.release(Target::Pickup(from));
1279 let total = have + taken;
1280 carrying.0 = (total > 0).then_some(Item::new(material, total));
1281 let next = nearest_tile(&map, tile.0, SEARCH_TILES, |p| {
1282 reservations.is_free(Target::Pickup(p))
1283 && items.iter().any(|(_, item, pos)| {
1284 pos.0 == p && item.kind == material && item.count > 0
1285 })
1286 });
1287 match next {
1288 _ if total >= cost => {
1289 *pickup = None;
1290 Step::Continue
1291 }
1292 Some(next) => {
1293 reservations.reserve(Target::Pickup(next), entity);
1294 *pickup = Some(next);
1295 Step::Continue
1296 }
1297 None => Step::Done,
1298 }
1299 }
1300 } else if !carrying
1301 .0
1302 .is_some_and(|load| load.kind == material && load.count >= cost)
1303 {
1304 Step::Done
1305 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
1306 match find_path_adjacent(&map, tile.0, site) {
1307 Some(p) if !p.is_empty() => {
1308 path.0 = p.into();
1309 Step::Continue
1310 }
1311 _ => Step::Done,
1312 }
1313 } else {
1314 *progress = (*progress + work_rate(&light, tile.0)).min(kind.work());
1315 let someone_in_the_way = kind.blocks_tile() && occupied.contains(&site);
1316 if *progress < kind.work() || someone_in_the_way {
1317 Step::Continue
1318 } else {
1319 goals.record_use(material, cost);
1320 carrying.0 = carrying.0.and_then(|load| {
1321 (load.count > cost).then_some(Item {
1322 count: load.count - cost,
1323 ..load
1324 })
1325 });
1326 match kind {
1327 BuildKind::Structure(structure) => {
1328 spawn_structure(&mut commands, &structure_assets, site, structure);
1329 if kind.blocks_tile() {
1330 map.set_wall(site, true);
1331 changed.write(TileChanged(site));
1332 }
1333 }
1334 BuildKind::Roof => {
1335 map.set_roof(site, true);
1336 changed.write(TileChanged(site));
1337 }
1338 BuildKind::Pave => {
1339 map.set(site, Terrain::Paved);
1340 changed.write(TileChanged(site));
1341 }
1342 }
1343 blueprints.0.remove(&site);
1344 Step::Done
1345 }
1346 }
1347 }
1348 Task::Haul { pickup, to } => {
1349 let to = *to;
1350 let destination_valid = zones.is_stockpile(to)
1351 && reservations.holder(Target::Storage(to)) == Some(entity);
1352 if !destination_valid {
1353 Step::Done
1354 } else if let Some(from) = *pickup {
1355 if reservations.holder(Target::Pickup(from)) != Some(entity) {
1356 Step::Done
1357 } else if tile.0 != from {
1358 walk_to(&map, tile.0, from, &mut path)
1359 } else {
1360 let kind = items
1361 .iter()
1362 .find(|(_, _, pos)| pos.0 == from)
1363 .map(|(_, item, _)| item.kind);
1364 let room = kind.map_or(0, |kind| {
1365 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
1366 });
1367 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
1368 .filter(|load| load.count > 0)
1369 {
1370 Some(load) => {
1371 carrying.0 = Some(load);
1372 reservations.release(Target::Pickup(from));
1373 *pickup = None;
1374 Step::Continue
1375 }
1376 None => Step::Done,
1377 }
1378 }
1379 } else if let Some(load) = carrying.0 {
1380 if tile.0 != to {
1381 walk_to(&map, tile.0, to, &mut path)
1382 } else {
1383 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
1384 let dropped = load.count.min(room);
1385 if dropped > 0 {
1386 drop_items(
1387 &mut commands,
1388 &mut items,
1389 &item_assets,
1390 to,
1391 load.with_count(dropped),
1392 );
1393 }
1394 carrying.0 = (load.count > dropped).then_some(Item {
1395 count: load.count - dropped,
1396 ..load
1397 });
1398 Step::Done
1399 }
1400 } else {
1401 Step::Done
1402 }
1403 }
1404 };
1405 match step {
1406 Step::Continue => current.0 = Some(job),
1407 Step::Done => {
1408 reservations.release_all(entity);
1409 current.0 = None;
1410 let ordered_move = matches!(
1411 job,
1412 Job {
1413 task: Task::MoveTo(_),
1414 ordered: true
1415 }
1416 );
1417 idle.restart(if ordered_move {
1418 IDLE_AFTER_ORDER_SECS
1419 } else {
1420 rng.range_f32(WORK_PAUSE_SECS)
1421 });
1422 }
1423 }
1424 }
1425 }
1426
1427 #[cfg(test)]
1428 mod tests;