Skip to main content

unbanished_game/people/life/
households.rs

1//! Households: homes and their residents, guardians and dependents, finding a home and a partner, pregnancy and births, and a home's warmth and stock.
2
3use super::*;
4
5/// Citizen message 0: warm up at `home` if it is warm.
6///
7/// Original: `FUN_1401176b0`.
8pub fn warm_at(s: &mut CitizenState, home: Option<&Home>, temperature: f32) {
9    if home.is_some_and(|h| h.warm(temperature)) {
10        s.cold = 0.0;
11    }
12}
13
14// +0xc; +0x2c
15/// A residence's update. The fire burns down; with residents, while it is colder than the house's
16/// warmth, one unit of firewood keeps it burning for seconds. The food and firewood status icons
17/// clear when there is some. The ClearStorage work comes first
18/// ([`crate::town::Sim::residence_clear_storage`]). The firewood burned counts as used in the stock
19/// manager.
20///
21/// Original: `FUN_14012ee40`.
22pub fn update_home(
23    home: &mut Home,
24    storages: &mut [Storage],
25    materials: &[RawMaterial],
26    temperature: f32,
27    dt: i64,
28    counters: &mut crate::work::tracker::StockCounters,
29) {
30    home.fuel -= dt;
31    let storage = &mut storages[home.storage];
32    if 0 < stored(storage, materials, 5) {
33        crate::people::status::set_icon(&mut home.status, 6, false, false);
34    }
35    if 0 < stored(storage, materials, 6) {
36        crate::people::status::set_icon(&mut home.status, 7, false, false);
37    }
38    if temperature < home.desc.warm_temperature && home.fuel < 0 && !home.families.is_empty() {
39        let fuel = storage
40            .items
41            .iter()
42            .find(|i| materials[i.material].flags >> 6 & 1 != 0 && 0 < i.count - i.reserved)
43            .map(|i| i.material);
44        if let Some(m) = fuel {
45            home.fuel = ticks(home.desc.fuel_seconds);
46            storage.remove(m, 1);
47            if let Some(slot) = crate::work::produce::production_group(materials[m].flags) {
48                counters.used[slot] += 1;
49            }
50        }
51    }
52}
53
54impl People<'_, '_> {
55    /// Move citizen `c` (and its dependents) to `home` family `slot`.
56    ///
57    /// Original: `FUN_14011b8a0`.
58    pub fn set_home(&mut self, c: usize, home: Option<usize>, slot: i32) {
59        let s = &self.states[c];
60        if s.home == home && s.home_slot == slot {
61            return;
62        }
63        if let Some(old) = s.home {
64            let old_slot = s.home_slot;
65            self.remove_resident(old, old_slot, c);
66        }
67        self.states[c].home = home;
68        self.states[c].home_slot = slot;
69        if let Some(new) = home {
70            self.add_resident(new, slot, c);
71        }
72        for d in self.states[c].dependents.clone() {
73            self.set_home(d, home, slot);
74        }
75    }
76
77    /// `FUN_14012fbe0`: append and sort the family; the first resident lights the house.
78    pub(super) fn add_resident(&mut self, home: usize, slot: i32, c: usize) {
79        let citizens = &*self.citizens;
80        if let Some(h) = self.homes.get_mut(&home) {
81            if let Some(f) = h.families.get_mut(slot.max(0) as usize) {
82                f.push(c);
83                f.sort_by(|&a, &b| family_order(citizens, a, b));
84            }
85        }
86    }
87
88    /// `FUN_14012fa20`: remove; the last resident leaving clears the status icons 6 and 7.
89    pub(super) fn remove_resident(&mut self, home: usize, slot: i32, c: usize) {
90        if let Some(h) = self.homes.get_mut(&home) {
91            if let Some(f) = h.families.get_mut(slot.max(0) as usize) {
92                if let Some(i) = f.iter().position(|&x| x == c) {
93                    f.remove(i);
94                }
95            }
96            if h.occupants() == 0 {
97                crate::people::status::set_icon(&mut h.status, 6, false, false);
98                crate::people::status::set_icon(&mut h.status, 7, false, false);
99            }
100        }
101    }
102
103    /// Make `guardian` the guardian of `c`.
104    ///
105    /// Original: `FUN_140117470`.
106    pub fn set_guardian(&mut self, c: usize, guardian: Option<usize>) {
107        if self.citizens[c].parent == guardian {
108            return;
109        }
110        if let Some(g) = self.citizens[c].parent {
111            self.remove_dependent(g, c);
112        }
113        if let Some(g) = guardian {
114            self.add_dependent(g, c);
115        }
116    }
117
118    /// `FUN_14011bd70`: join `g`'s ring (at its end) and its home.
119    pub(super) fn add_dependent(&mut self, g: usize, c: usize) {
120        self.states[g].dependents.push(c);
121        self.citizens[c].parent = Some(g);
122        let (home, slot) = (self.states[g].home, self.states[g].home_slot);
123        self.set_home(c, home, slot);
124    }
125
126    /// `FUN_140117510`: leave `g`'s ring; homeless and without a guardian.
127    pub(super) fn remove_dependent(&mut self, g: usize, c: usize) {
128        self.states[g].dependents.retain(|&d| d != c);
129        self.set_home(c, None, -1);
130        self.citizens[c].parent = None;
131    }
132
133    /// `FUN_140115310`: the first registered single of the other sex old enough to marry and
134    /// close enough in age.
135    pub(super) fn find_partner(&self, c: usize) -> Option<usize> {
136        let r = self.rules;
137        let me = &self.citizens[c];
138        self.registry.iter().copied().find(|&i| {
139            let o = &self.citizens[i];
140            o.male != me.male
141                && o.spouse.is_none()
142                && r.f(0x48) < o.age
143                && (o.age - me.age).abs() <= r.f(0x4c)
144                && !self.dying(i)
145        })
146    }
147
148    /// `FUN_140116340`: a home for `c`. A partner's single-family home, unless an adult in a
149    /// shared home or homeless waits for one; else the first free family slot of a
150    /// single-family residence reachable from `c`, else (with `shared`) the first shared one.
151    pub(super) fn find_home(&mut self, c: usize, shared: bool) -> Option<(usize, i32)> {
152        if let Some(p) = self.citizens[c].spouse {
153            if let Some(home) = self.states[p].home {
154                if self.reaches(c, home)
155                    && self.homes.get(&home).is_some_and(|h| h.families.len() < 2)
156                {
157                    return Some((home, self.states[p].home_slot));
158                }
159            }
160        }
161        if let Some(mine) = self.states[c].home {
162            // Moving out of a shared residence waits while another adult is homeless, or (when
163            // this citizen's home is single-family) lives in a shared one.
164            let single = self.homes.get(&mine).is_some_and(|h| h.families.len() == 1);
165            let adult = self.rules.adult_age();
166            for &o in self.registry.iter() {
167                if o == c || self.citizens[o].age < adult || self.states[o].school.is_some() {
168                    continue;
169                }
170                let h = self.states[o].home?;
171                if single && self.homes.get(&h).is_some_and(|h| h.families.len() > 1) {
172                    return None;
173                }
174            }
175        }
176        let cell = self.cell(c);
177        let mut fallback = None;
178        for e in self.workforce.residences.clone() {
179            let Some(home) = self.homes.get(&e) else {
180                continue;
181            };
182            if !shared && home.families.len() >= 2 {
183                continue;
184            }
185            for (slot, family) in home.families.iter().enumerate() {
186                if !family.is_empty() {
187                    continue;
188                }
189                let entrance = self.town.point_cell(e);
190                if entrance < 0 || !self.town.reachable(WALKABLE, cell, entrance) {
191                    continue;
192                }
193                if home.families.len() == 1 {
194                    return Some((e, slot as i32));
195                }
196                if fallback.is_none() {
197                    fallback = Some((e, slot as i32));
198                }
199            }
200        }
201        fallback
202    }
203
204    /// The birth part of `FUN_140118340`.
205    pub(super) fn pregnancy(&mut self, c: usize, secs: f32) {
206        let r = self.rules;
207        // jb at 0x140118d5d: a NaN age is skipped, as a child's is.
208        #[allow(clippy::neg_cmp_op_on_partial_ord)]
209        if self.citizens[c].male
210            || !(r.adult_age() <= self.citizens[c].age)
211            || self.states[c].school.is_some()
212        {
213            return;
214        }
215        let s = &mut self.states[c];
216        if (r.hunger_warning() < s.hunger || r.cold_warning() < s.cold) && 0.0 < s.reproduction {
217            s.reproduction = 0.0;
218        }
219        let t = s.reproduction;
220        // jbe at 0x140118dda: only a time above 0 counts down; a NaN one is left as it is.
221        if 0.0 < t {
222            s.reproduction = t - secs;
223            if t - secs <= 0.0 {
224                let health = s.health;
225                let threshold = (health / r.f(0x70)) * (r.f(0x64) - r.f(0x68)) + r.f(0x68);
226                // jbe at 0x140118e2a: a NaN threshold gives a birth.
227                #[allow(clippy::neg_cmp_op_on_partial_ord)]
228                let born = !(self.rng.rand_float() < threshold);
229                if born {
230                    self.give_birth(c);
231                    let cooldown = self.rng.rand_float() * r.f(0x60) + r.f(0x5c);
232                    self.states[c].reproduction = -cooldown;
233                } else if self.die(c, reason::CHILDBIRTH, None) {
234                    return;
235                }
236            }
237        } else if t < 0.0 {
238            // The time after a birth counts up to 0.
239            s.reproduction = t + secs;
240            if 0.0 <= t + secs {
241                s.reproduction = 0.0;
242            }
243        }
244        let s = &self.states[c];
245        if self.citizens[c].spouse.is_some() && s.home.is_some() && s.reproduction == 0.0 {
246            let age = self.citizens[c].age;
247            if r.f(0x50) <= age && age <= r.f(0x54) {
248                let full = s
249                    .home
250                    .and_then(|h| self.homes.get(&h))
251                    .is_some_and(|h| h.full(s.home_slot.max(0) as usize));
252                if !full {
253                    self.states[c].reproduction = r.f(0x58);
254                }
255            }
256        }
257    }
258
259    /// `FUN_140117060`: a child, its sex chosen to even out the unmarried young.
260    pub(super) fn give_birth(&mut self, mother: usize) {
261        let r = self.rules;
262        // The unmarried no older than `D[0x4c]` and the boys among them: a boy is likelier the
263        // fewer boys there are.
264        let (mut young, mut boys) = (0, 0);
265        for &i in self.registry.iter() {
266            if self.citizens[i].spouse.is_none() && self.citizens[i].age <= r.f(0x4c) {
267                if self.citizens[i].male {
268                    boys += 1;
269                }
270                young += 1;
271            }
272        }
273        let male = if young != 0 {
274            let x = self.rng.rand_float();
275            boys as f32 / young as f32 <= x
276        } else {
277            self.rng.rand_below(2) == 1
278        };
279        let mut child = (self.newborn)(self.rng, &self.citizens[mother], male);
280        child.position = self.citizens[mother].position;
281        child.age = 0.0;
282        let id = self.citizens.len();
283        self.citizens.push(child);
284        self.states.push(CitizenState::newborn(r));
285        self.add_dependent(mother, id);
286        self.registry.push(id);
287        self.born.push(id);
288        self.report(id, reason::BORN, 0, None);
289        self.states[mother].flags |= 0x100;
290        if let Some(f) = self.citizens[mother].spouse {
291            self.states[f].flags |= 0x100;
292        }
293    }
294}