Skip to main content

unbanished_game/behaviour/
commute.rs

1//! The town's commute optimisation, run from StockManager::Update every 300 s of game time. See
2//! docs/COMMUTE.md.
3//!
4//! - Start: one cell pair (residence entrance, workplace entrance) per distinct pair of map
5//!   regions, each region pair cached with rank 0.
6//! - Step (every update): up to seven pairs, last first, get their path rank (`Map::PathRank` mode
7//!   0; 0 or 1 become the straight distance). With none left:
8//! - Homes: families in single-family residences, the longest commute first, move to the empty
9//!   residence that shortens theirs most, goods and all.
10//! - Jobs: every working adult is let go, then each workplace takes back as many as it had, the
11//!   workplace whose nearest candidate is furthest (weighted by how much of it is still to fill)
12//!   choosing first; the rest get the professions left over.
13//!
14//! Pointer orders in the original's trees (citizens, residences, professions) are taken as index
15//! order here.
16//!
17//! Original: `FUN_140091780`, `FUN_1400dc590`, `FUN_1400dc3d0`, `FUN_1400db770`, `FUN_1400d9880`.
18
19mod jobs;
20
21use std::cmp::Reverse;
22use std::collections::{BTreeMap, BTreeSet};
23
24use crate::people::citizens::Citizen;
25use crate::scheduler::ticks;
26use crate::town::Sim;
27
28/// `DAT_140178934`: seconds between runs.
29const PERIOD_SECONDS: f32 = 300.0;
30/// The cost of an unreachable or homeless commute (`0x1000000`).
31const FAR: i32 = 0x100_0000;
32/// The pairs ranked per update (`min(index, 6) + 1`).
33const STEP: i32 = 7;
34
35// +0x190; +0x1b8
36/// The optimisation's state: StockManager (the time since the last run) and the job object (its
37/// pairs, the next pair's index and the region-pair ranks).
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Commute {
40    /// The time since the last run.
41    pub timer: i64,
42    /// The pairs of cells to rank: a workplace entrance and a home.
43    pub pairs: Vec<(i32, i32)>,
44    /// The next pair to rank (−1 when done).
45    pub index: i32,
46    /// The rank of each pair of regions.
47    pub ranks: BTreeMap<(i32, i32), i32>,
48}
49
50impl Default for Commute {
51    fn default() -> Self {
52        Commute {
53            timer: 0,
54            pairs: Vec::new(),
55            index: -1,
56            ranks: BTreeMap::new(),
57        }
58    }
59}
60
61/// A workplace while the jobs are dealt (`0x28`-byte records): its entity, profession,
62/// entrance, places left and total (its workers at the start), and the candidates by score.
63struct Place {
64    entity: usize,
65    profession: Option<usize>,
66    entrance: i32,
67    left: i32,
68    total: i32,
69    candidates: BTreeSet<(i32, usize)>,
70}
71
72impl Place {
73    /// The queue priority: the best candidate's score times the share still to fill.
74    fn priority(&self, score: i32) -> i32 {
75        (score as f32 * (1.0 - (self.total - self.left) as f32 / self.total as f32)) as i32
76    }
77}
78
79impl Sim<'_, '_> {
80    /// Map cell `+0x18`: the region (port 0 is none, the original's −1).
81    fn region(&self, cell: i32) -> i32 {
82        match self.regions.get(cell as usize) {
83            Some(&r) if r != 0 => r as i32,
84            _ => -1,
85        }
86    }
87
88    fn region_key(&self, a: i32, b: i32) -> (i32, i32) {
89        let (ra, rb) = (self.region(a), self.region(b));
90        (ra.max(rb), ra.min(rb))
91    }
92
93    /// `(int)sqrtf(dy² + dx²)` in cells.
94    fn straight(&self, a: i32, b: i32) -> i32 {
95        let n = self.size as i32;
96        let (dy, dx) = (a / n - b / n, a % n - b % n);
97        ((dy * dy + dx * dx) as f32).sqrt() as i32
98    }
99
100    /// StockManager::Update's part: the clock, then a step, or a new start when idle.
101    pub fn update_commute(&mut self, job: &mut Commute, citizens: &[Citizen], dt: i64) {
102        job.timer += dt;
103        let period = ticks(PERIOD_SECONDS);
104        if job.timer < period {
105            return;
106        }
107        if !self.commute_step(job, citizens) {
108            self.commute_start(job);
109        } else if job.index < 0 && period < job.timer {
110            loop {
111                job.timer -= period;
112                if job.timer <= period {
113                    break;
114                }
115            }
116        }
117    }
118
119    /// `FUN_1400dc590` (only while idle).
120    fn commute_start(&mut self, job: &mut Commute) {
121        if 0 <= job.index {
122            return;
123        }
124        let residences = self.workforce.residences.clone();
125        let homes: Vec<i32> = residences.iter().map(|&r| self.entrance_cell(r)).collect();
126        job.ranks.clear();
127        job.pairs.clear();
128        for p in 0..self.professions.list.len() {
129            let places = self.workforce.registry.get(&p).cloned().unwrap_or_default();
130            for w in places {
131                let entrance = self.entrance_cell(w);
132                if self.region(entrance) < 0 {
133                    continue;
134                }
135                for &home in &homes {
136                    if self.region(home) < 0 {
137                        continue;
138                    }
139                    let key = self.region_key(entrance, home);
140                    if job.ranks.contains_key(&key) {
141                        continue;
142                    }
143                    job.pairs.push((entrance.max(home), entrance.min(home)));
144                    job.ranks.insert(key, 0);
145                }
146            }
147        }
148        job.index = job.pairs.len() as i32 - 1;
149    }
150
151    /// `FUN_1400dc3d0`: false while idle; with the last pair ranked, the homes and the jobs.
152    fn commute_step(&mut self, job: &mut Commute, citizens: &[Citizen]) -> bool {
153        if job.index < 0 {
154            return false;
155        }
156        for _ in 0..job.index.min(STEP - 1) + 1 {
157            let (a, b) = job.pairs[job.index as usize];
158            let mut rank = self.path_rank(a, b, false);
159            if (rank as u32) < 2 {
160                rank = self.straight(a, b);
161            }
162            let key = self.region_key(a, b);
163            job.ranks.insert(key, rank);
164            job.index -= 1;
165        }
166        if job.index < 0 {
167            self.commute_homes(citizens);
168            self.commute_jobs(job);
169            job.pairs.clear();
170        }
171        true
172    }
173
174    /// `FUN_1400dc130`: the commute of `family`'s working adults (no laborers, students or
175    /// unreachable workplaces) from `home`'s use point: the sum of the path ranks
176    /// (`FUN_140008830`).
177    fn family_cost(&mut self, family: usize, home: usize) -> i32 {
178        let from = self.point_cell(home);
179        let laborer = self.professions.laborer;
180        let members = self
181            .homes
182            .get(&family)
183            .map(|h| h.families[0].clone())
184            .unwrap_or_default();
185        let mut cost = 0i32;
186        for c in members {
187            let s = &self.states[c];
188            if !self.adult[c] || s.profession == laborer {
189                continue;
190            }
191            let Some(wp) = s.workplace else {
192                continue;
193            };
194            let to = self.entrance_cell(wp);
195            if self.reachable(from, to) {
196                cost = cost.wrapping_add(self.rank_or_distance(from, to));
197            }
198        }
199        cost
200    }
201
202    /// `FUN_1400db770`.
203    fn commute_homes(&mut self, citizens: &[Citizen]) {
204        let mut empty = BTreeSet::new();
205        // Longest commute first; equal ones by residence.
206        let mut occupied = BTreeSet::new();
207        for r in self.workforce.residences.clone() {
208            let Some(h) = self.homes.get(&r) else {
209                continue;
210            };
211            if 2 <= h.families.len() {
212                continue;
213            }
214            if h.families[0].is_empty() {
215                empty.insert(r);
216            } else {
217                let cost = self.family_cost(r, r);
218                occupied.insert((Reverse(cost), r));
219            }
220        }
221        if empty.is_empty() {
222            return;
223        }
224        for (Reverse(cost), from) in occupied {
225            let mut best = (cost, None);
226            for &to in &empty {
227                let c = self.family_cost(from, to);
228                if c < best.0 {
229                    best = (c, Some(to));
230                }
231            }
232            let Some(to) = best.1 else {
233                continue;
234            };
235            // `FUN_14011b8a0` for each member, over the live list.
236            let mut i = 0;
237            while let Some(&c) = self.homes.get(&from).and_then(|h| h.families[0].get(i)) {
238                self.move_home(citizens, c, to, 0);
239                i += 1;
240            }
241            self.move_goods(from, to);
242            empty.remove(&to);
243            if empty.is_empty() {
244                break;
245            }
246        }
247    }
248
249    /// The family's goods follow it, each item whole where it fits (`FUN_140132250`,
250    /// `FUN_1401324d0`), then leave the old home (`FUN_140132620`).
251    fn move_goods(&mut self, from: usize, to: usize) {
252        let (Some(a), Some(b)) = (
253            self.homes.get(&from).map(|h| h.storage),
254            self.homes.get(&to).map(|h| h.storage),
255        ) else {
256            return;
257        };
258        let items: Vec<(usize, i32)> = self.storages[a]
259            .items
260            .iter()
261            .map(|i| (i.material, i.count - i.reserved))
262            .collect();
263        let mut moved = Vec::new();
264        for (m, n) in items {
265            if self.storages[b].fits(self.materials, m, n) {
266                self.storages[b].add(m, n);
267                moved.push((m, n));
268            }
269        }
270        for (m, n) in moved {
271            self.storages[a].remove(m, n);
272        }
273    }
274
275    /// `FUN_14011b8a0`: citizen `c` (and its dependents) to `home`'s family `slot`.
276    fn move_home(&mut self, citizens: &[Citizen], c: usize, home: usize, slot: i32) {
277        let s = &self.states[c];
278        if s.home == Some(home) && s.home_slot == slot {
279            return;
280        }
281        if let Some(old) = s.home {
282            let old_slot = s.home_slot.max(0) as usize;
283            if let Some(h) = self.homes.get_mut(&old) {
284                if let Some(f) = h.families.get_mut(old_slot) {
285                    f.retain(|&x| x != c);
286                }
287                if h.occupants() == 0 {
288                    crate::people::status::set_icon(&mut h.status, 6, false, false);
289                    crate::people::status::set_icon(&mut h.status, 7, false, false);
290                }
291            }
292        }
293        self.states[c].home = Some(home);
294        self.states[c].home_slot = slot;
295        if let Some(f) = self
296            .homes
297            .get_mut(&home)
298            .and_then(|h| h.families.get_mut(slot.max(0) as usize))
299        {
300            f.push(c);
301            f.sort_by(|&a, &b| crate::people::life::family_order(citizens, a, b));
302        }
303        for d in self.states[c].dependents.clone() {
304            self.move_home(citizens, d, home, slot);
305        }
306    }
307}
308
309#[cfg(test)]
310mod tests;