unbanished_game/work/professions.rs
1//! Professions (`Game`), workplaces (WorkPlaceComponent, the town manager's workplace registry
2//! `Game →`) and who takes a job when the player changes a profession's count. See docs/JOBS.md.
3//!
4//! The ProfessionUI spinners and the WorkPlaceUI buttons call the town manager directly in the
5//! original, between simulation iterations; the port queues them as [`Command`]s that the
6//! simulation applies before its next iteration, which is the same point in the game's Random
7//! stream.
8//!
9//! Original: `FUN_14007b890`, `FUN_14008ccb0`.
10mod commands;
11mod hiring;
12mod settings;
13pub use commands::Command;
14
15// Game +0xb0; Game +0xf0 → +0x100
16
17use std::collections::BTreeMap;
18
19use crate::people::life::Home;
20use crate::random::Random;
21use crate::work::stock::StorageSearchMap;
22
23/// What the workplace searches read.
24///
25/// Original: `FUN_140115490`, `FUN_140115940`, `FUN_140115eb0`.
26pub trait Search {
27 /// Citizen `c`'s map cell.
28 fn cell(&self, c: usize) -> i32;
29 /// Profession `+0x4c` ([`Professions::works_anywhere`]).
30 fn anywhere(&self, profession: usize) -> bool;
31 /// The workplace's work priority (`Jobs` entry `+0x24`, lower first).
32 fn priority(&self, workplace: usize) -> i32;
33 /// `FUN_14011ada0`: the workplace's entrance can be reached from `cell`.
34 fn reach(&mut self, cell: i32, workplace: usize) -> bool;
35 /// The game's random generator (the reachability test and the hiring draw from it).
36 fn rng(&mut self) -> &mut Random;
37}
38
39/// `Profession` fields the simulation reads.
40///
41/// Original: `FUN_1400ae3e0`.
42#[derive(Debug, Clone, Default)]
43pub struct Profession {
44 /// `Game\Profession\Profession.rsc:<key>`.
45 pub reference: String,
46 // +0x30; +0x20
47 /// Name key (`ProfessionBuilder`), in the string table.
48 pub name: String,
49 /// The string table of the name, if not the default one.
50 pub string_table: Option<String>,
51 // +0x28; +0x30
52 /// The icon's sprite sheet (sprite).
53 pub sprite_sheet: Option<String>,
54 // +0x4c
55 /// Works anywhere (laborers and builders): `Jobs::TryList` offers it work outside its
56 /// workplace, and the job status icon stays off without one.
57 ///
58 /// Original: `FUN_1400fce80`.
59 pub works_anywhere: bool,
60 // +0x4d
61 /// With a workplace, the citizen does not catch diseases (the doctor).
62 ///
63 /// Original: `FUN_14011c060`.
64 pub immune_at_work: bool,
65 // +0x40
66 /// The death-message key of an accident at its work.
67 pub death: String,
68 // +0x54, +0x58; +0x54; +0x58
69 /// The accident odds `(years, factor)`: on average one accident per `years × factor` years
70 /// at work; none when the factor is not positive.
71 ///
72 /// Original: `FUN_1400ae760`.
73 pub accident: (f32, f32),
74 // +0x50
75 /// How much a citizen of this profession carries (100; 500 for traders and vendors).
76 ///
77 /// Original: `FUN_140114c70`.
78 pub carry: i32,
79}
80
81// +0x20/+0x28; +0x30; +0x38; Game +0xb0; +0x40; +0x48
82/// The profession manager (`Profession.rsc:resource`): the list of professions
83/// (`Profession.rsc:professionList`), the laborer and builder entries, and the child and student
84/// entries.
85///
86/// Original: `FUN_1400ae300`.
87#[derive(Debug, Clone, Default)]
88pub struct Professions {
89 /// Every profession.
90 pub list: Vec<Profession>,
91 /// The laborer's index in `list`.
92 pub laborer: usize,
93 /// The builder's index in `list`.
94 pub builder: usize,
95}
96
97impl Professions {
98 /// Whether a profession works anywhere (its description says so), not at one workplace.
99 pub fn works_anywhere(&self, p: usize) -> bool {
100 self.list.get(p).is_some_and(|p| p.works_anywhere)
101 }
102}
103
104// vtable 0x14016b160; +0x30
105/// WorkPlaceComponent plus the entity's WorkComponent most-workers value.
106///
107/// Original: `FUN_1401347b0`.
108#[derive(Debug, Clone)]
109pub struct WorkPlace {
110 // +0x48
111 /// The profession its workers take (builder while under construction).
112 pub profession: Option<usize>,
113 // +0x20
114 /// WorkPlaceDescription: the profession once built (none for houses and barns).
115 pub description_profession: Option<usize>,
116 // +0x50
117 /// Accepting workers (the constructor sets it).
118 pub enabled: bool,
119 // +0x58/+0x60
120 /// Citizen indices, in assignment order.
121 pub workers: Vec<usize>,
122 // +0x30
123 /// WorkComponent: most workers; 0 until first read, and every reader recomputes it from the
124 /// description while it is 0 (see [`WorkPlace::max`]).
125 pub max_workers: i32,
126 // WorkDescription +0x24, scaled when +0x34 is set.
127 /// The default number of workers, from the work description; scaled by the footprint's area
128 /// when the description says so.
129 ///
130 /// Original: `WorkComponent::MaxWorkers`, `FUN_140133a90`.
131 pub default_max: i32,
132 // +0xf0
133 /// The building's StatusIconComponent bits ([`icon`]).
134 pub status: u32,
135}
136
137/// The building status icons (`StatusIcons\BuildingIconSpriteSheet`): the bit of each.
138pub mod icon {
139 /// `BuildPaused`: switched off while being built.
140 pub const BUILD_PAUSED: u8 = 0;
141 /// `WorkDisabled`: switched off.
142 pub const WORK_DISABLED: u8 = 1;
143 /// `LimitProduction`: the stock is at its limit (or the building is full).
144 pub const LIMIT: u8 = 2;
145 /// `WorkUnavailable`: inputs are missing.
146 pub const NO_WORK: u8 = 3;
147 /// `WorkersUnavailable`: nobody works there.
148 pub const NO_WORKERS: u8 = 4;
149 /// `BuildDestroy`: marked to be torn down.
150 pub const DESTROY: u8 = 5;
151 /// A house without food, without firewood.
152 pub const NO_FOOD: u8 = 6;
153 /// The icon for no firewood.
154 pub const NO_FIREWOOD: u8 = 7;
155}
156
157impl WorkPlace {
158 /// A workplace with its profession and its default number of workers.
159 pub fn new(description_profession: Option<usize>, default_max: i32) -> WorkPlace {
160 WorkPlace {
161 profession: None,
162 description_profession,
163 enabled: true,
164 workers: Vec::new(),
165 max_workers: 0,
166 default_max,
167 status: 0,
168 }
169 }
170
171 /// Show or hide a status icon of the building.
172 ///
173 /// Original: `FUN_1401318c0` on the building's status icon component.
174 pub fn set_icon(&mut self, bit: u8, on: bool) {
175 crate::people::status::set_icon(&mut self.status, bit, on, false);
176 }
177
178 // +0x30; if +0x30 == 0 { +0x30 = MaxWorkers() }
179 /// WorkComponent as every reader sees it: `if == 0 { = MaxWorkers }`.
180 pub fn max(&self) -> i32 {
181 if self.max_workers == 0 {
182 self.default_max
183 } else {
184 self.max_workers
185 }
186 }
187}
188
189// +0x248; +0x238; +0x1f0
190/// The citizen fields assignment reads and writes (Citizen).
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub struct Worker {
193 // +0x208; desc+0x44 <= age
194 /// `desc <= age` and no school: the citizens every search counts.
195 pub adult: bool,
196 /// The profession.
197 pub profession: usize,
198 /// The workplace, if any.
199 pub workplace: Option<usize>,
200 /// The home, if any.
201 pub home: Option<usize>,
202}
203
204/// The town manager's workplace and residence registries and every WorkPlaceComponent.
205#[derive(Debug, Clone, Default)]
206pub struct Workforce {
207 /// Entity → WorkPlaceComponent.
208 pub workplaces: BTreeMap<usize, WorkPlace>,
209 // +0x100
210 /// Profession → workplace entities, in registration order.
211 ///
212 /// Original: `FUN_14008ea70`.
213 pub registry: BTreeMap<usize, Vec<usize>>,
214 // +0x20/+0x28; FUN_14012f2b0 appends a residence when it is built.
215 /// The residences, in the order they were built.
216 pub residences: Vec<usize>,
217 /// Workplaces being torn down (their state machine in 3 to 5), kept by the sites' update: the
218 /// last worker leaving one shows no `WorkersUnavailable`.
219 ///
220 /// Original: `FUN_140123be0`.
221 pub demolishing: std::collections::BTreeSet<usize>,
222}
223
224impl Workforce {
225 /// Register `entity` under `profession` once.
226 ///
227 /// Original: `FUN_14008ea70`.
228 pub fn register(&mut self, entity: usize, profession: usize) {
229 let list = self.registry.entry(profession).or_default();
230 if !list.contains(&entity) {
231 list.push(entity);
232 }
233 }
234
235 /// Remove a workplace from a profession's list (every occurrence), keeping the order.
236 ///
237 /// Original: `FUN_140002cc0`.
238 pub fn unregister(&mut self, entity: usize, profession: usize) {
239 if let Some(list) = self.registry.get_mut(&profession) {
240 list.retain(|&e| e != entity);
241 }
242 }
243
244 /// Move citizen `c` to workplace `wp` (removing it from its old one, then appending to the new
245 /// one).
246 ///
247 /// Original: `FUN_140134cb0`, `FUN_140134ef0`, `FUN_1401173b0`.
248 pub fn set_workplace(&mut self, workers: &mut [Worker], c: usize, wp: Option<usize>) {
249 self.move_worker(c, workers[c].workplace, wp);
250 workers[c].workplace = wp;
251 }
252
253 /// The workplaces' side of [`Workforce::set_workplace`]: `c` leaves `old` and joins `new`
254 /// (not while it is being torn down). When the last worker leaves, the limit and work icons go,
255 /// and an enabled workplace of its own profession shows `WorkersUnavailable`; joining removes
256 /// that icon. The entity events 2 and 3 (work sounds and smoke) are only for presentation; the
257 /// app drives them from the workers.
258 ///
259 /// Original: `FUN_140123be0`; leaving `FUN_140134cb0`, joining `FUN_140134ef0`.
260 pub fn move_worker(&mut self, c: usize, old: Option<usize>, new: Option<usize>) {
261 if let Some(old) = old {
262 let demolishing = self.demolishing.contains(&old);
263 if let Some(w) = self.workplaces.get_mut(&old) {
264 w.workers.retain(|&x| x != c);
265 if w.workers.is_empty() {
266 w.set_icon(icon::LIMIT, false);
267 w.set_icon(icon::NO_WORK, false);
268 if w.enabled
269 && !demolishing
270 && w.profession.is_some()
271 && w.profession == w.description_profession
272 {
273 w.set_icon(icon::NO_WORKERS, true);
274 }
275 }
276 }
277 }
278 if let Some(new) = new {
279 if let Some(w) = self.workplaces.get_mut(&new) {
280 w.set_icon(icon::NO_WORKERS, false);
281 w.workers.push(c);
282 }
283 }
284 }
285
286 /// The assignment tail shared by every search: change the workplace and profession only
287 /// when either differs.
288 fn assign(&mut self, workers: &mut [Worker], c: usize, profession: usize, wp: Option<usize>) {
289 if workers[c].profession != profession || workers[c].workplace != wp {
290 self.set_workplace(workers, c, wp);
291 workers[c].profession = profession;
292 }
293 }
294
295 /// `FUN_14008e940`: shuffle a profession's workplace list (`Rand(n)` per position, when it
296 /// has at least two).
297 fn shuffle_workplaces(&mut self, profession: usize, rng: &mut Random) {
298 if let Some(list) = self.registry.get_mut(&profession) {
299 shuffle(list, rng);
300 }
301 }
302}
303
304/// For each position `i`, swap with `Rand(n)` (no draws below two entries).
305///
306/// Original: `FUN_14008e940`, `FUN_14008eb70`.
307pub fn shuffle<T>(list: &mut [T], rng: &mut Random) {
308 let n = list.len();
309 if n < 2 {
310 return;
311 }
312 for i in 0..n {
313 let j = rng.rand_below(n as u32) as usize;
314 if i != j {
315 list.swap(i, j);
316 }
317 }
318}
319
320#[cfg(test)]
321mod tests;