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