Skip to main content

unbanished_game/work/
destroy.rs

1//! Demolition, damage and rubble: DestroyComponent. See docs/JOBS.md "Demolition".
2//!
3//! - 3: the work and status icons go; a damaged building goes on to 6, else to 4 with the
4//!   BuildDestroy icon;
5//! - 4: the building becomes a site again; a finished one with goods has them carried out first
6//!   (ClearStorage), then 5;
7//! - 5: builders take a started building down (a BuildStructure work with the destroy flag, half
8//!   its construction work); then it is gone, leaving part of its materials in piles, or what
9//!   replaces it;
10//! - 6: damaged (burning): the goods are lost; it collapses when its time runs out;
11//! - 7: rubble, to rebuild (message 0) or clear (message 1).
12//!
13//! Message 0 in 4 and 5 cancels the demolition.
14//!
15//! Original: `FUN_140034520`, `FUN_1401231d0`.
16mod states;
17
18// vtable 0x140169500
19
20use crate::town::{Sim, CONSTRUCTION_MASK};
21use crate::work::construction::{run, BuildWork, Callbacks, Controller};
22use crate::work::jobs::{Jobs, Work, WorkKind};
23use crate::work::professions::icon;
24
25/// A resolved [`unbanished_formats::game::DestroyDescription`].
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct DestroyTemplate {
28    // +0x20
29    /// What is left in the building's place (a placed-object template).
30    pub replace: Option<usize>,
31    // +0x28
32    /// The ModelComponent's material set once damaged.
33    ///
34    /// Original: `FUN_14012a4f0`.
35    pub material: i32,
36    // +0x2c
37    /// The decal's material while damaged.
38    pub decal: i32,
39    // +0x30
40    /// The lowest construction mesh a collapse steps down to.
41    pub min_mesh: i32,
42}
43
44// +0x48; +0x50; +0x51; +0x54; +0x58; +0x60; +0x20
45// 0x68 bytes; set up by FUN_140122fd0 from the description.
46/// The demolition state of a building: the damage time left, whether it is damaged, whether its
47/// materials come back, the demolition work done and needed, and what to put in its place.
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct Destroy {
50    /// The damage time left.
51    pub time: i64,
52    /// Whether it is damaged.
53    pub damaged: bool,
54    /// Whether its materials come back.
55    pub refund: bool,
56    /// The demolition work done.
57    pub count: i32,
58    /// The demolition work needed.
59    pub target: i32,
60    /// The template to put in its place, if any.
61    pub rebuild: Option<usize>,
62    // +0x28
63    /// The model shows the description's damaged material set (set by the damage with time left and
64    /// by every collapse).
65    pub damaged_look: bool,
66}
67
68impl Destroy {
69    /// The demolition state of a new building.
70    pub fn new(t: &DestroyTemplate) -> Destroy {
71        Destroy {
72            rebuild: t.replace,
73            ..Default::default()
74        }
75    }
76}
77
78/// An entity put in a torn-down building's place: its template over the same map rectangle, turned
79/// as it was, with its model's position and variant.
80///
81/// Original: `FUN_1401215f0`.
82#[derive(Debug, Clone, Copy, PartialEq)]
83pub struct Rebuild {
84    /// The template.
85    pub template: usize,
86    /// The map cell.
87    pub cell: (i32, i32),
88    /// The footprint.
89    pub footprint: (i32, i32),
90    /// The heading, in degrees.
91    pub yaw: f32,
92    /// The model's position.
93    pub position: [f32; 3],
94    /// The model variant.
95    pub variant: usize,
96}
97
98/// `DAT_140178904`, `DAT_1401787fc`.
99const QUARTER: f32 = 90.0;
100const FLAT: f32 = 0.2;
101
102impl Sim<'_, '_> {
103    fn destroy_state(&mut self, e: usize) -> Option<&mut Destroy> {
104        self.sites.get_mut(&e)?.destroy.as_mut()
105    }
106
107    /// The state machine's pending state, else its state (`+0x52`, `+0x50`).
108    fn shown_state(&self, e: usize) -> i8 {
109        self.sites.get(&e).map_or(-1, |s| {
110            if s.machine.pending < 0 {
111                s.machine.state
112            } else {
113                s.machine.pending
114            }
115        })
116    }
117
118    /// Damaged (6) or rubble (7).
119    ///
120    /// Original: `FUN_140123b60`.
121    pub fn is_damaged(&self, e: usize) -> bool {
122        matches!(self.shown_state(e), 6 | 7)
123    }
124
125    /// Being torn down (3 to 5).
126    ///
127    /// Original: `FUN_140123be0`.
128    pub fn is_demolishing(&self, e: usize) -> bool {
129        matches!(self.shown_state(e), 3..=5)
130    }
131
132    /// BuildComponent `+0x48 < BuildDescription +0x30 × +0x4c`: not finished.
133    fn unfinished(&self, e: usize) -> bool {
134        let site = &self.sites[&e];
135        let t = &self.site_templates[site.template];
136        site.progress < t.work * site.stages
137    }
138
139    /// A BuildComponent (removal markers have none).
140    pub(crate) fn has_build(&self, e: usize) -> bool {
141        let site = &self.sites[&e];
142        self.site_templates[site.template]
143            .controllers
144            .contains(&Controller::Build)
145    }
146
147    /// Remove Buildings and the demolish button. Damaged or rubble: clear it (message 1); else the
148    /// machine runs what is pending, then goes to 3.
149    ///
150    /// Original: `FUN_140123470`.
151    pub fn demolish(&mut self, jobs: &mut Jobs, e: usize) {
152        if self.destroy_state(e).is_none() {
153            return;
154        }
155        if self.is_damaged(e) {
156            self.destroy_message(jobs, e, 1);
157            return;
158        }
159        run(self, jobs, e, false, false);
160        self.machine(e).request(3);
161        run(self, jobs, e, false, false);
162    }
163
164    /// UpgradeUI's button: the replacement is `template`, and the building is torn down.
165    ///
166    /// Original: `FUN_14008c160`, `FUN_140123470`.
167    pub fn upgrade(&mut self, jobs: &mut Jobs, e: usize, template: usize) {
168        let Some(d) = self.destroy_state(e) else {
169            return;
170        };
171        d.rebuild = Some(template);
172        self.demolish(jobs, e);
173    }
174
175    // slot +0x20
176    /// DestroyUI's cancel (`0x1771`): message 0, and the replacement goes back to the
177    /// description's.
178    ///
179    /// Original: `FUN_1401238d0`.
180    pub fn cancel_demolition(&mut self, jobs: &mut Jobs, e: usize) {
181        self.destroy_message(jobs, e, 0);
182        let site = &self.sites[&e];
183        let replace = self.site_templates[site.template]
184            .destroy
185            .and_then(|d| d.replace);
186        if let Some(d) = self.destroy_state(e) {
187            d.rebuild = replace;
188        }
189    }
190
191    /// Damage for `time` (fire, the tornado). A building not started yet takes none; else it goes
192    /// to 3 (then 6).
193    ///
194    /// Original: `FUN_140123c80`.
195    pub fn damage(&mut self, jobs: &mut Jobs, e: usize, time: i64) -> bool {
196        if self.destroy_state(e).is_none() {
197            return false;
198        }
199        if self.has_build(e) && self.sites[&e].progress == 0 {
200            return false;
201        }
202        let d = self.destroy_state(e).unwrap();
203        d.damaged = true;
204        d.time = time;
205        if self.machine(e).index < 0 {
206            run(self, jobs, e, false, false);
207        }
208        self.machine(e).request(3);
209        run(self, jobs, e, false, false);
210        true
211    }
212
213    /// Straight to rubble.
214    ///
215    /// Original: `FUN_140123ee0`.
216    pub fn to_rubble(&mut self, jobs: &mut Jobs, e: usize) {
217        if self.machine(e).index < 0 {
218            run(self, jobs, e, false, false);
219        }
220        self.machine(e).request(7);
221        run(self, jobs, e, false, false);
222    }
223
224    // +0x10
225    /// The StateMachine's message slot for the Destroy states: the current state's handler.
226    pub fn destroy_message(&mut self, jobs: &mut Jobs, e: usize, msg: i32) {
227        if self.destroy_state(e).is_none() || self.machine(e).index < 0 {
228            return;
229        }
230        match (self.machine(e).state, msg) {
231            (4 | 5, 0) => self.cancel(jobs, e),
232            (6, 2) => self.machine(e).request(7),
233            // `FUN_140122770`: rebuild what stood here.
234            (7, 0) => {
235                self.become_site(jobs, e);
236                let template = self.placed[e].template;
237                let d = self.destroy_state(e).unwrap();
238                d.refund = true;
239                d.rebuild = Some(template);
240                self.machine(e).request(5);
241            }
242            // `FUN_140122670`: clear the rubble.
243            (7, 1) => {
244                self.become_site(jobs, e);
245                let build = self.has_build(e);
246                if build {
247                    self.destroy_state(e).unwrap().refund = true;
248                }
249                self.machine(e).request(5);
250            }
251            _ => {}
252        }
253    }
254
255    /// `FUN_140121190`: the demolition is called off. A building goes back to its finished
256    /// state (2), a site to building (8) or clearing (0, no mesh yet); a damaged one to rubble.
257    fn cancel(&mut self, jobs: &mut Jobs, e: usize) {
258        self.set_icon(e, icon::DESTROY, false);
259        self.remove_work(jobs, e);
260        if self.destroy_state(e).is_some_and(|d| d.damaged) {
261            self.become_building(jobs, e);
262            self.machine(e).request(7);
263            return;
264        }
265        if !self.has_build(e) {
266            self.machine(e).request(2);
267            run(self, jobs, e, false, false);
268        } else {
269            // The MultiObject's first part's model (`+0x166` mesh, `+0x164` variant).
270            let m = self.sites[&e].parts.first().copied().unwrap_or(e);
271            let mesh = self.placed[m].mesh;
272            let state = if mesh == usize::MAX {
273                0
274            } else if mesh as i32 == self.meshes_of(m) - 1 {
275                2
276            } else {
277                8
278            };
279            self.machine(e).request(state);
280        }
281        self.become_building(jobs, e);
282    }
283
284    fn meshes_of(&self, m: usize) -> i32 {
285        let p = &self.placed[m];
286        self.templates[p.template]
287            .model
288            .as_ref()
289            .and_then(|model| model.variants.get(p.variant))
290            .map_or(1, |v| v.meshes.len() as i32)
291    }
292
293    /// Residence state 3 enter (`FUN_14012edf0` → `FUN_14012f3c0`): the icons 6 and 7 go,
294    /// each family moves out (`FUN_14011b8a0(first, none, -1)`) and the residence leaves the
295    /// town's (`+0x20`). The ResidenceComponent is kept on the site meanwhile.
296    pub(crate) fn residence_leave(&mut self, e: usize) {
297        let Some(mut home) = self.homes.remove(&e) else {
298            return;
299        };
300        crate::people::status::set_icon(&mut home.status, icon::NO_FOOD, false, false);
301        crate::people::status::set_icon(&mut home.status, icon::NO_FIREWOOD, false, false);
302        for slot in 0..home.families.len() {
303            while let Some(&c) = home.families[slot].first() {
304                self.move_out(&mut home, c);
305            }
306        }
307        self.workforce.residences.retain(|&r| r != e);
308        if let Some(site) = self.sites.get_mut(&e) {
309            site.home = Some(home);
310        }
311    }
312
313    /// `FUN_14011b8a0` with no home: the citizen and its dependents leave theirs.
314    fn move_out(&mut self, home: &mut crate::people::life::Home, c: usize) {
315        for f in home.families.iter_mut() {
316            f.retain(|&x| x != c);
317        }
318        self.states[c].home = None;
319        self.states[c].home_slot = -1;
320        for d in self.states[c].dependents.clone() {
321            if self.states[d].home.is_some() {
322                self.move_out(home, d);
323            }
324        }
325    }
326
327    /// `FUN_1400c8370` on an active entity: each component's deactivate slot runs now (the
328    /// zone and the map stamp are lifted); the entity is removed after the machine has run.
329    pub(crate) fn deactivate(&mut self, jobs: &mut Jobs, e: usize) {
330        self.remove_work(jobs, e);
331        let n = self.size as i32;
332        let stamped = {
333            let p = &self.placed[e];
334            let (x, y) = p.cell;
335            let (w, h) = p.footprint;
336            (y..y + h).any(|cy| {
337                (x..x + w).any(|cx| self.cells.objects[(cy * n + cx) as usize] == Some(e))
338            })
339        };
340        if stamped {
341            self.unstamp(e);
342        }
343        let p = &self.placed[e];
344        let (x, y) = p.cell;
345        let (w, h) = p.footprint;
346        for cy in y..y + h {
347            for cx in x..x + w {
348                let i = (cy * n + cx) as usize;
349                if self.cells.occupants[i] == Some(e) {
350                    self.cells.occupants[i] = None;
351                }
352            }
353        }
354        if let Some(site) = self.sites.get_mut(&e) {
355            site.destroyed = true;
356        }
357    }
358
359    /// `FUN_140121a00`: piles of the materials over the rectangle (`x`, `y`, `w`, `h`), by rows,
360    /// on free flat ground: an unfinished building's stored materials (half once work
361    /// began), else half its build materials (a quarter when damaged); at most `100 / size`
362    /// a pile, each turned a random quarter.
363    fn refund(&mut self, e: usize, x: i32, y: i32, w: i32, h: i32) {
364        let site = &self.sites[&e];
365        let t = &self.site_templates[site.template];
366        let mut piles: Vec<(usize, i32)> = Vec::new();
367        if site.progress < t.work * site.stages {
368            let div = if 0 < site.progress { 2 } else { 1 };
369            for item in &self.storages[site.storage].items {
370                let Some(k) = t.materials.iter().position(|&(_, m)| m == item.material) else {
371                    continue;
372                };
373                if let Some(&Some(pile)) = t.material_templates.get(k) {
374                    piles.push((pile, (item.count - item.reserved) / div));
375                }
376            }
377        } else {
378            let div = if self.sites[&e].destroy.as_ref().is_some_and(|d| d.damaged) {
379                4
380            } else {
381                2
382            };
383            for (k, &(count, _)) in t.materials.iter().enumerate() {
384                if let Some(&Some(pile)) = t.material_templates.get(k) {
385                    piles.push((pile, count / div));
386                }
387            }
388        }
389        let n = self.size as i32;
390        let (mut col, mut row) = (0, 0);
391        for (pile, mut left) in piles {
392            if left <= 0 {
393                continue;
394            }
395            let Some(material) = self.templates[pile].pile_material else {
396                continue;
397            };
398            // The cursor carries on from the last material's, and the scan checks the last
399            // row after the cell (a material after the rectangle is full scans on below it).
400            loop {
401                let cell = (y + row) * n + x + col;
402                if cell < 0 || n * n <= cell {
403                    break;
404                }
405                let i = cell as usize;
406                let ground = self.ground_at(cell);
407                if self.cells.occupants[i].is_none()
408                    && self.cells.types[i].0 == 2
409                    && 0.0 <= ground[2]
410                    && ground[2] < FLAT
411                {
412                    let amount = left.min(100 / self.materials[material].size.max(1));
413                    let yaw = self.rng.rand_tol(2) as f32 * QUARTER;
414                    self.spawn_pile(pile, (x + col, y + row), amount, yaw, None);
415                    left -= amount;
416                }
417                col += 1;
418                if w <= col {
419                    col = 0;
420                    row += 1;
421                }
422                if row == h || left <= 0 {
423                    break;
424                }
425            }
426        }
427    }
428}