unbanished_game/events.rs
1//! The town event log (`Game`) and the stock warnings that post to it. See docs/EVENT-LOG.md.
2// Game +0x138
3
4use crate::work::stock::{stock_table, RawMaterial, Storage, STOCK_SLOTS};
5
6/// `DAT_140178910`: a warning waits 120 s before it can repeat.
7const WARNING_COOLDOWN: i64 = 120_000_000;
8
9/// Event types: entry `type` of `Dialog/StringTable.rsc:events`.
10pub mod kind {
11 /// A citizen starved.
12 pub const STARVED: i32 = 0;
13 /// A citizen froze.
14 pub const FROZE: i32 = 1;
15 /// A citizen died of old age.
16 pub const OLD_AGE: i32 = 2;
17 /// A child was born.
18 pub const BORN: i32 = 8;
19 /// A child became an adult.
20 pub const ADULT: i32 = 9;
21 /// A child became a student.
22 pub const STUDENT: i32 = 10;
23 /// The town is low on logs.
24 pub const LOW_LOGS: i32 = 17;
25 /// The storage for goods is nearly full.
26 pub const NEAR_CAPACITY_GOODS: i32 = 23;
27 /// The storage for raw materials is nearly full.
28 pub const NEAR_CAPACITY_RAW: i32 = 24;
29 /// A tornado touched down.
30 pub const TORNADO: i32 = 30;
31 /// A fire started.
32 pub const FIRE: i32 = 31;
33}
34
35/// One log entry (0x28 bytes: colour, formatted text, type, severity, cell, category, icon).
36/// The port keeps the format arguments; the text is formatted with the string tables when
37/// shown, from the month and year the event happened in.
38#[derive(Debug, Clone, PartialEq)]
39pub struct EventEntry {
40 /// The event type.
41 pub kind: i32,
42 /// How important the event is.
43 pub severity: i32,
44 /// ARGB from the severity.
45 ///
46 /// Original: `FUN_14009a2d0`.
47 pub color: u32,
48 /// The month (`@0`, an index into `:seasons`).
49 pub month: usize,
50 /// The year (`@1`).
51 pub year: i32,
52 /// `@2`, `@3`, `@4`.
53 pub args: [String; 3],
54 /// The entity's map-rectangle centre cell, or -1.
55 ///
56 /// Original: `FUN_14009a500`.
57 pub cell: i32,
58 /// Notification category.
59 ///
60 /// Original: `FUN_14009a5a0`.
61 pub category: i32,
62 /// Popup icon (12, 13 for types 0x1a-0x1d), -1 otherwise.
63 pub icon: i32,
64 /// The text as formatted when the event was posted, for entries loaded from a save (the
65 /// original keeps only the text); shown as is.
66 ///
67 /// Original: `FUN_14009a790`.
68 pub text: Option<String>,
69 /// Whether `text` is shown after the event's season and year, as the game's own lines are
70 /// ("Autumn 22: …"): a rule hook's line. Deviation: not in the original, which has no rule
71 /// hooks.
72 pub dated: bool,
73}
74
75/// The event log: its entries and which categories notify the player.
76#[derive(Debug, Clone)]
77pub struct EventLog {
78 /// The entries.
79 pub entries: Vec<EventEntry>,
80 // +0x10..+0x15
81 /// Notify flags per group (old age, deaths, disasters, storage, town, other), set by the Event
82 /// Log's checkboxes. Default as in every inspected save: old-age deaths off, the rest on.
83 pub notify: [bool; 6],
84 /// Set when an event asks the game to slow down (option `AutoSlow`, types 11, 12, 30, 31).
85 pub slow_request: bool,
86}
87
88impl Default for EventLog {
89 fn default() -> Self {
90 EventLog {
91 entries: Vec::new(),
92 notify: [false, true, true, true, true, true],
93 slow_request: false,
94 }
95 }
96}
97
98/// The colour of an event's severity, `0xAARRGGBB`.
99///
100/// Original: the colours of `FUN_14009a2d0`.
101pub fn severity_color(severity: i32) -> u32 {
102 match severity {
103 1 => 0xffff_ff00,
104 2 => 0xff80_80ff,
105 3 => 0xffff_6060,
106 4 => 0xffea_7517,
107 _ => 0xffff_ffff,
108 }
109}
110
111/// The category of an event type, which the log filters by.
112///
113/// Original: `FUN_14009a5a0`.
114pub fn category(kind: i32) -> i32 {
115 match kind {
116 0..=7 => 0,
117 0xb => 1,
118 0xc => 2,
119 0xd => 5,
120 0xe => 8,
121 0x11..=0x16 => 6,
122 0x17 | 0x18 => 7,
123 0x19 => 9,
124 0x1a | 0x1c => 10,
125 0x1b | 0x1d => 11,
126 0x1e => 4,
127 0x1f => 3,
128 _ => -1,
129 }
130}
131
132impl EventLog {
133 /// Add an event to the log.
134 ///
135 /// Original: `FUN_14009a2d0(log, type, severity, entity, @2, @3, @4)`.
136 #[allow(clippy::too_many_arguments)]
137 pub fn add(
138 &mut self,
139 kind: i32,
140 severity: i32,
141 cell: i32,
142 month: usize,
143 year: i32,
144 args: [String; 3],
145 auto_slow: bool,
146 ) {
147 let icon = match kind {
148 0x1a | 0x1c => 12,
149 0x1b | 0x1d => 13,
150 _ => -1,
151 };
152 self.entries.push(EventEntry {
153 text: None,
154 dated: false,
155 kind,
156 severity,
157 color: severity_color(severity),
158 month,
159 year,
160 args,
161 cell,
162 category: category(kind),
163 icon,
164 });
165 if kind > 10 && (kind < 0xd || (0x1e..=0x1f).contains(&kind)) && auto_slow {
166 self.slow_request = true;
167 }
168 }
169}
170
171// Game +0xf0; +0x170; +0x180
172/// The stock manager's warning state (`Game`: slots, capacity records).
173#[derive(Debug, Clone)]
174pub struct StockWarnings {
175 // +0x0; +0x4
176 /// The count of each slot.
177 ///
178 /// Original: `FUN_14008f3a0`.
179 pub count: [i32; STOCK_SLOTS],
180 /// The count of each slot at the last check.
181 pub previous: [i32; STOCK_SLOTS],
182 // +0x8; the defaults come from FUN_140095f00.
183 /// The production limit of each stock slot (the Town Hall changes them).
184 pub limits: [i32; STOCK_SLOTS],
185 // +0x18
186 /// Warning cooldown.
187 pub cooldown: [i64; STOCK_SLOTS],
188 // +0x180
189 /// records: produced goods and logs/stone/iron, `(used, capacity, cooldown)`.
190 pub capacity: [(i32, i32, i64); 2],
191}
192
193impl Default for StockWarnings {
194 fn default() -> Self {
195 let mut limits = [1000; STOCK_SLOTS];
196 limits[..12].copy_from_slice(&[200, 200, 200, 200, 50, 5000, 100, 50, 500, 200, 200, 1000]);
197 StockWarnings {
198 count: [0; STOCK_SLOTS],
199 previous: [0; STOCK_SLOTS],
200 limits,
201 cooldown: [0; STOCK_SLOTS],
202 capacity: [(0, 0, 0); 2],
203 }
204 }
205}
206
207/// `FUN_14008f3a0`'s capacity split: materials with flags `0x1c40` (logs, stone, iron) are raw.
208const RAW_FLAGS: u32 = 0x1c40;
209
210impl StockWarnings {
211 /// Shift counts to `previous`, recount, and total used/capacity by kind.
212 ///
213 /// Original: `FUN_14008f3a0`.
214 pub fn recompute(&mut self, storages: &[Storage], materials: &[RawMaterial]) {
215 self.previous = self.count;
216 self.count = stock_table(storages, materials);
217 let mut used = [0i32; 2];
218 let mut cap = [0i32; 2];
219 for s in storages {
220 let (mut goods, mut raw) = (false, false);
221 for item in &s.items {
222 let m = &materials[item.material];
223 let size = m.size * item.count;
224 if m.flags & RAW_FLAGS == 0 {
225 used[0] += size;
226 goods = true;
227 } else {
228 used[1] += size;
229 raw = true;
230 }
231 }
232 if raw {
233 cap[1] += s.capacity;
234 }
235 if goods {
236 cap[0] += s.capacity;
237 }
238 }
239 for i in 0..2 {
240 self.capacity[i].0 = used[i];
241 self.capacity[i].1 = cap[i];
242 }
243 }
244
245 /// Low reserve (types 17..22) when a slot falls below 5% of its limit, near capacity (23 goods,
246 /// 24 logs/stone/iron) above 95%, each at most every 120 s. Returns the event types to post at
247 /// severity 3.
248 ///
249 /// Original: `FUN_1400915d0`.
250 pub fn check(&mut self, dt: i64) -> Vec<i32> {
251 let mut out = Vec::new();
252 for i in 0..STOCK_SLOTS {
253 self.cooldown[i] -= dt;
254 if self.cooldown[i] >= 1 {
255 continue;
256 }
257 self.cooldown[i] = 0;
258 if i >= 6 {
259 continue;
260 }
261 let (mut count, mut previous, mut limit) =
262 (self.count[i], self.previous[i], self.limits[i]);
263 // Firewood includes coal (slot 9).
264 if i == 3 {
265 count += self.count[9];
266 previous += self.previous[9];
267 limit += self.limits[9];
268 }
269 if count < limit / 20 && limit / 20 <= previous {
270 out.push(kind::LOW_LOGS + i as i32);
271 self.cooldown[i] = WARNING_COOLDOWN;
272 }
273 }
274 for (i, (used, cap, cooldown)) in self.capacity.iter_mut().enumerate() {
275 *cooldown -= dt;
276 if *cooldown >= 1 {
277 continue;
278 }
279 *cooldown = 0;
280 if (*cap / 20) * 19 < *used {
281 out.push(kind::NEAR_CAPACITY_GOODS + i as i32);
282 *cooldown = WARNING_COOLDOWN;
283 }
284 }
285 out
286 }
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[test]
294 fn low_reserve_fires_on_crossing_only() {
295 let mut w = StockWarnings::default();
296 w.previous[0] = 10;
297 w.count[0] = 9;
298 assert_eq!(w.check(0), vec![kind::LOW_LOGS]);
299 // Cooling down.
300 assert!(w.check(1_000_000).is_empty());
301 // No crossing: both below the threshold.
302 w.cooldown[0] = 0;
303 w.previous[0] = 5;
304 w.count[0] = 4;
305 assert!(w.check(0).is_empty());
306 }
307
308 #[test]
309 fn colours_and_categories() {
310 assert_eq!(severity_color(3), 0xffff6060);
311 assert_eq!(category(17), 6);
312 assert_eq!(category(23), 7);
313 }
314}