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