src/jobs/mod.rs 51.4 K · 1477 lines · raw · history

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