Skip to main content

unbanished_game/work/
tracker.rs

1//! What the town makes and uses: the stock manager's counters for each slot (used and made since
2//! the last sample) and each workplace's tracker (what it made this year and last). See
3//! docs/TOWN-INFO.md.
4//!
5//! Original: the trackers, `FUN_140059930`.
6// Game +0xf0 → +0x170; +0xc; +0x10
7
8use crate::crt::truncate;
9use crate::town::Sim;
10
11// +0x28; +0x38; +0x48
12/// A workplace's tracker: what it made this year (material and amount), what it made last year,
13/// and the year these belong to.
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct Tracker {
16    /// What it made this year: `(raw material, amount)`.
17    pub this_year: Vec<(usize, i32)>,
18    /// What it made last year.
19    pub last_year: Vec<(usize, i32)>,
20    /// The year these belong to.
21    pub year: u32,
22}
23
24impl Tracker {
25    /// In a new year this year's list becomes last year's; then the material's amount grows, or it
26    /// joins the list.
27    ///
28    /// Original: `FUN_140059930`.
29    pub fn add(&mut self, year: u32, material: usize, amount: i32) {
30        if year != self.year {
31            self.last_year = std::mem::take(&mut self.this_year);
32            self.year = year;
33        }
34        if let Some(e) = self.this_year.iter_mut().find(|e| e.0 == material) {
35            e.1 += amount;
36            return;
37        }
38        self.this_year.push((material, amount));
39    }
40}
41
42// +0xc; +0x10
43/// The stock manager's slot counters since the last sample (of each slot).
44#[derive(Debug, Clone, PartialEq, Eq, Default)]
45pub struct StockCounters {
46    /// The amount used, per slot.
47    pub used: [i32; 21],
48    /// The amount made, per slot.
49    pub made: [i32; 21],
50}
51
52impl Sim<'_, '_> {
53    /// `FUN_14008e3c0(stock, owner, update, material, amount)`: the owner's TrackerComponent
54    /// (when `update`) and the material's slot count what was made.
55    pub(crate) fn count_made(
56        &mut self,
57        owner: Option<usize>,
58        update: bool,
59        material: usize,
60        n: i32,
61    ) {
62        if let (Some(o), true) = (owner, update) {
63            let year = self.year;
64            if let Some(t) = self.trackers.get_mut(&o) {
65                t.add(year, material, n);
66            }
67        }
68        if let Some(slot) = crate::work::produce::production_group(self.materials[material].flags) {
69            self.counters.made[slot] += n;
70        }
71    }
72
73    /// The `+0xc` count of the material's slot (`FUN_14008e460`): eaten, burned, used to build,
74    /// visited or traded away.
75    pub(crate) fn count_used(&mut self, material: usize, n: i32) {
76        if let Some(slot) = crate::work::produce::production_group(self.materials[material].flags) {
77            self.counters.used[slot] += n;
78        }
79    }
80}
81
82// +0x150
83/// The series the stock manager samples: 8 of the citizens, then per stock slot its count, used and
84/// made.
85pub const SERIES: usize = 8 + 3 * 21;
86/// A sample every 75 s.
87///
88/// Original: `FUN_140091780`.
89pub const SAMPLE_SECONDS: f32 = 75.0;
90
91// +0x3c; +0x44; +0x208; +0x50; +0x80; +0x210; +0x118; +0x1e4
92/// What a sample reads of each citizen (age against, school, health, happiness, education against,
93/// coat).
94#[derive(Debug, Clone, Copy, Default, PartialEq)]
95pub struct CitizenSample {
96    /// Whether the citizen is an adult.
97    pub adult: bool,
98    /// Whether it attends school.
99    pub school: bool,
100    /// The health.
101    pub health: f32,
102    /// The happiness.
103    pub happiness: f32,
104    /// Whether it is educated.
105    pub educated: bool,
106    /// Whether it has a coat.
107    pub coat: bool,
108}
109
110// +0x198; +0x150
111/// The Town Info graphs' history (StockManager) and the time to the next sample.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Statistics {
114    /// The history of each graph.
115    pub series: Vec<Vec<i32>>,
116    /// The time to the next sample.
117    pub timer: i64,
118}
119
120impl Default for Statistics {
121    fn default() -> Self {
122        Statistics {
123            series: vec![Vec::new(); SERIES],
124            timer: 0,
125        }
126    }
127}
128
129impl Statistics {
130    /// The timer counts down `dt`; below 1 a sample is taken and the next is 75 s off.
131    ///
132    /// Original: `FUN_14008fc00`, `FUN_140091780` (sampling).
133    pub fn update(
134        &mut self,
135        dt: i64,
136        citizens: &[CitizenSample],
137        health_max: f32,
138        happiness_max: f32,
139        stock: &[i32; 21],
140        counters: &mut StockCounters,
141    ) -> bool {
142        self.timer -= dt;
143        if 0 < self.timer {
144            return false;
145        }
146        self.sample(citizens, health_max, happiness_max, stock, counters);
147        self.timer = crate::scheduler::ticks(SAMPLE_SECONDS);
148        true
149    }
150
151    /// The population (all, adults, students, children), the average health and happiness and the
152    /// share educated (of the adults) and with coats, in percent; each stock slot's count, used and
153    /// made; then the used and made counts restart.
154    ///
155    /// Original: `FUN_14008fc00`.
156    pub fn sample(
157        &mut self,
158        citizens: &[CitizenSample],
159        health_max: f32,
160        happiness_max: f32,
161        stock: &[i32; 21],
162        counters: &mut StockCounters,
163    ) {
164        let (mut adults, mut students, mut children) = (0, 0, 0);
165        let (mut health, mut happiness) = (0.0f32, 0.0f32);
166        let (mut educated, mut coats) = (0, 0);
167        for c in citizens {
168            if !c.adult || c.school {
169                if c.school {
170                    students += 1;
171                } else {
172                    children += 1;
173                }
174            } else {
175                adults += 1;
176            }
177            health += c.health;
178            happiness += c.happiness;
179            if c.educated && c.adult && !c.school {
180                educated += 1;
181            }
182            if c.coat {
183                coats += 1;
184            }
185        }
186        let (mut h, mut j, mut e, mut k) = (0, 0, 0, 0);
187        if !citizens.is_empty() {
188            let n = citizens.len() as f32;
189            h = truncate(((health / n) / health_max) * 100.0);
190            j = truncate(((happiness / n) / happiness_max) * 100.0);
191            e = truncate((educated as f32 / adults as f32) * 100.0);
192            k = truncate((coats as f32 / n) * 100.0);
193        }
194        let people = [
195            citizens.len() as i32,
196            adults,
197            students,
198            children,
199            h,
200            e,
201            j,
202            k,
203        ];
204        for (s, v) in self.series.iter_mut().zip(people) {
205            s.push(v);
206        }
207        for slot in 0..21 {
208            self.series[8 + 3 * slot].push(stock[slot]);
209            self.series[9 + 3 * slot].push(counters.used[slot]);
210            self.series[10 + 3 * slot].push(counters.made[slot]);
211        }
212        *counters = StockCounters::default();
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn a_tracker_keeps_this_year_and_last() {
222        let mut t = Tracker::default();
223        t.add(0, 3, 5);
224        t.add(0, 3, 2);
225        t.add(0, 4, 1);
226        assert_eq!(t.this_year, vec![(3, 7), (4, 1)]);
227        t.add(1, 4, 9);
228        assert_eq!(t.last_year, vec![(3, 7), (4, 1)]);
229        assert_eq!(t.this_year, vec![(4, 9)]);
230    }
231
232    #[test]
233    fn a_sample_counts_the_town() {
234        let adult = CitizenSample {
235            adult: true,
236            health: 2.0,
237            happiness: 1.0,
238            educated: true,
239            coat: true,
240            ..Default::default()
241        };
242        let child = CitizenSample {
243            health: 2.0,
244            happiness: 1.0,
245            ..Default::default()
246        };
247        let student = CitizenSample {
248            school: true,
249            ..child
250        };
251        let mut stats = Statistics::default();
252        let mut counters = StockCounters::default();
253        counters.made[2] = 7;
254        counters.used[2] = 3;
255        let stock = [1; 21];
256        assert!(stats.update(
257            1,
258            &[adult, child, student, adult],
259            4.0,
260            2.0,
261            &stock,
262            &mut counters
263        ));
264        let last: Vec<i32> = stats.series.iter().map(|s| *s.last().unwrap()).collect();
265        assert_eq!(&last[..8], &[4, 2, 1, 1, 50, 100, 50, 50]);
266        assert_eq!(&last[8 + 6..8 + 9], &[1, 3, 7]);
267        assert_eq!(counters, StockCounters::default());
268        // The next sample is 75 s off; with no one, the shares are 0.
269        assert!(!stats.update(
270            crate::scheduler::ticks(74.0),
271            &[],
272            4.0,
273            2.0,
274            &stock,
275            &mut counters
276        ));
277        assert!(stats.update(
278            crate::scheduler::ticks(1.0),
279            &[],
280            4.0,
281            2.0,
282            &stock,
283            &mut counters
284        ));
285        assert_eq!(stats.series[4], vec![50, 0]);
286    }
287}