Skip to main content

unbanished_game/work/
produce.rs

1//! Workplace production: ResourceProduceComponent's states and the `ConsumeProduce` work of
2//! ConsumeProduceComponent: the wood cutter, blacksmith, tailor, tavern, quarry and mine. See
3//! docs/JOBS.md "Production".
4//!
5//! A worker of the workplace's profession takes the work at a free "use" point. In order it hauls
6//! goods the current recipe does not use out of the building, fetches missing inputs, hauls the
7//! workplace's own output piles away while its "create" points are full, and otherwise works one
8//! cycle at its use point. Every `cycles` completed cycles the next cycle also consumes the inputs
9//! and leaves the output as a pile on a free create point.
10//!
11//! Original: `FUN_140130700`.
12mod cycle;
13mod sequence;
14
15// vtable 0x140167640
16
17use crate::behaviour::character::{Action, MoveTo};
18use crate::pathfind::WALKABLE;
19use crate::town::{Haul, Sim};
20use crate::work::construction::{ProduceWork, Recipe};
21use crate::work::jobs::{Jobs, Work, WorkKind};
22
23/// The stock-manager slot a raw material counts towards (production limits).
24///
25/// Original: `FUN_14008e460`.
26pub fn production_group(flags: u32) -> Option<usize> {
27    const ORDER: [(u32, usize); 21] = [
28        (10, 0),
29        (11, 1),
30        (12, 2),
31        (7, 3),
32        (8, 9),
33        (9, 4),
34        (5, 5),
35        (13, 6),
36        (14, 7),
37        (17, 8),
38        (16, 10),
39        (18, 11),
40        (19, 12),
41        (20, 13),
42        (21, 14),
43        (22, 15),
44        (23, 16),
45        (24, 17),
46        (25, 18),
47        (26, 19),
48        (27, 20),
49    ];
50    ORDER
51        .iter()
52        .find(|(bit, _)| flags >> bit & 1 != 0)
53        .map(|&(_, g)| g)
54}
55
56/// What the try decided before offering the output piles' pickups ([`Sim::produce_resume`]).
57#[derive(Debug, Clone, Copy)]
58pub(crate) struct ProduceResume {
59    /// The recipe selected at the start of the try (its output is the one produced).
60    selected: usize,
61    slot: usize,
62    point: Option<(usize, i32)>,
63    all_inputs: bool,
64}
65
66// ConsumeProduce +0x50 the selector, +0x58 the weights (count +0x60).
67/// The recipe a production cycle uses: the selected one; or, with the selector at −1 (any), one
68/// `RandFloat` over the weights, the first whose running sum passes the draw times their total;
69/// 0 for any other selector, or when no weight passes.
70///
71/// Measured: `tools/emu/recipe_pick.py` (the original on 2,000 cases).
72///
73/// Original: `FUN_14011e940`.
74pub fn pick_recipe(selector: i32, weights: &[f32], rng: &mut crate::random::Random) -> usize {
75    if selector >= 0 {
76        return selector as usize;
77    }
78    if selector != -1 {
79        return 0;
80    }
81    let mut total = 0.0f32;
82    for w in weights {
83        total += w;
84    }
85    let r = rng.rand_float();
86    let mut acc = 0.0f32;
87    for (i, w) in weights.iter().enumerate() {
88        acc += w;
89        if r * total < acc {
90            return i;
91        }
92    }
93    0
94}
95
96impl Sim<'_, '_> {
97    fn recipes(&self, e: usize) -> Option<&crate::work::construction::ProduceTemplate> {
98        let site = self.sites.get(&e)?;
99        self.site_templates[site.template].produce.as_ref()
100    }
101
102    /// `FUN_14011e940`: the selected recipe; selector −1 draws `RandFloat` over the weights.
103    pub(crate) fn produce_select(&mut self, e: usize) -> usize {
104        let Some(state) = self.sites.get(&e).and_then(|s| s.produce.as_ref()) else {
105            return 0;
106        };
107        let (selector, weights) = (state.selector, state.weights.clone());
108        pick_recipe(selector, &weights, self.rng)
109    }
110
111    /// `FUN_1401282f0(interact, 0, i)`: use point `i` in the world and its heading: the
112    /// point's direction (`FromYawPitch(yaw, 0)` at load, `FUN_1401289d0`) turned by the
113    /// entity transform, then `Heading`. The entity's own points come first, then its
114    /// MultiObject parts' in turn, each turned by its own transform; past them all, the
115    /// entity's origin.
116    pub(crate) fn use_point(&self, e: usize, i: usize) -> ([f32; 3], f32) {
117        let mut i = i;
118        for x in self.interact_entities(e) {
119            let p = &self.placed[x];
120            let t = &self.templates[p.template];
121            if i < t.use_points.len() {
122                let yaw = t.use_yaws.get(i).copied().unwrap_or(0.0);
123                let model = p.model(t);
124                return (model.apply(t.use_points[i]), model.heading_of(yaw));
125            }
126            i -= t.use_points.len();
127        }
128        let p = &self.placed[e];
129        let model = p.model(&self.templates[p.template]);
130        (model.apply([0.0; 3]), model.heading_of(0.0))
131    }
132
133    /// `FUN_140128540(interact, 0)`: the use points of the entity and its MultiObject parts.
134    pub(crate) fn use_point_count(&self, e: usize) -> usize {
135        self.interact_entities(e)
136            .iter()
137            .map(|&x| self.templates[self.placed[x].template].use_points.len())
138            .sum()
139    }
140
141    /// The cell of create point `i` (`FUN_1401282f0(interact, 2, i)`).
142    pub(crate) fn create_cell(&self, e: usize, i: usize) -> i32 {
143        // The entity's own create points, then its MultiObject parts' (`FUN_1401282f0`).
144        let mut i = i;
145        for x in self.interact_entities(e) {
146            let points = &self.templates[self.placed[x].template].create_points;
147            if i < points.len() {
148                return self.cell_of(self.world_point(x, points[i]));
149            }
150            i -= points.len();
151        }
152        self.cell_of(self.world_point(e, [0.0; 3]))
153    }
154
155    /// ConsumeProduceComponent slot `+0x90` (`FUN_14011e1d0`) and the work's constructor
156    /// (`FUN_1400ee6d0`): one worker slot per use point, one state per create point.
157    pub(crate) fn produce_work(&self, e: usize) -> Work {
158        let t = &self.templates[self.placed[e].template];
159        let profession = self
160            .workforce
161            .workplaces
162            .get(&e)
163            .and_then(|w| w.profession)
164            .unwrap_or(self.professions.laborer);
165        Work::new(
166            e,
167            self.rect_cell(e),
168            profession,
169            WorkKind::Produce(ProduceWork {
170                workers: vec![None; t.use_points.len()],
171                points: vec![0; t.create_points.len()],
172                full: false,
173                cycles: 0,
174            }),
175        )
176    }
177
178    /// `FUN_1401307e0`: switch production off (`+0x48`) and go idle (0xe).
179    pub(crate) fn produce_disable(&mut self, e: usize) {
180        let Some(site) = self.sites.get_mut(&e) else {
181            return;
182        };
183        if let Some(p) = &mut site.produce {
184            p.disabled = true;
185        }
186        let m = &site.machine;
187        let state = if m.pending < 0 { m.state } else { m.pending };
188        if state != 0xe {
189            site.machine.request(0xe);
190        }
191    }
192
193    /// `FUN_140130460` (transition 2 → 0xd): every create point's cell becomes ground with no
194    /// object, ready for output piles.
195    pub(crate) fn produce_clear_points(&mut self, e: usize) {
196        // `FUN_140128540(.., 2)`: the entity's and its MultiObject parts' create points.
197        let n: usize = self
198            .interact_entities(e)
199            .iter()
200            .map(|&x| self.templates[self.placed[x].template].create_points.len())
201            .sum();
202        for i in 0..n {
203            let cell = self.create_cell(e, i) as usize;
204            self.cells.set_type(cell, crate::terrain::CellType(2));
205            self.cells.objects[cell] = None;
206        }
207    }
208
209    /// `FUN_1400a1210(map, cell, 1, owner, mask)`: the nearest cell, in rings of radius 0..=6
210    /// (rows, then columns), with no object, no occupant (or `owner`), not water, no road
211    /// (built or planned), whose type is in `mask`.
212    pub(crate) fn free_cell(&self, cell: i32, owner: Option<usize>, mask: u32) -> Option<i32> {
213        self.free_cell_where(cell, owner, |t, _| mask >> (t & 0x1f) & 1 != 0)
214    }
215
216    /// `FUN_1400a1210(map, cell, 0, none, _)` (a loose pile's cell, `FUN_1400ccd90`): as
217    /// [`Sim::free_cell`], on ground (type 2) with no occupant, no flags, and the terrain's
218    /// normal at the cell's middle within `0.97` of up.
219    pub(crate) fn free_flat_cell(&self, cell: i32) -> Option<i32> {
220        let n = self.size as i32;
221        self.free_cell_where(cell, None, |t, i| {
222            if t != 2 || self.cells.occupants[i].is_some() || self.cells.flags[i] != 0 {
223                return false;
224            }
225            let half = (n >> 1) as f32 - 0.5;
226            let (x, y) = ((i as i32 % n) as f32 - half, (i as i32 / n) as f32 - half);
227            let mut normal = [0.0; 3];
228            self.cells
229                .floors
230                .ground_normal(self.size, self.terrain, x, y, &mut normal);
231            0.97 <= normal[2]
232        })
233    }
234
235    fn free_cell_where(
236        &self,
237        cell: i32,
238        owner: Option<usize>,
239        ok: impl Fn(u32, usize) -> bool,
240    ) -> Option<i32> {
241        let n = self.size as i32;
242        let (cx, cy) = (cell % n, cell / n);
243        for r in 0..=6 {
244            for y in cy - r..=cy + r {
245                for x in cx - r..=cx + r {
246                    if (y - cy).abs() != r && (x - cx).abs() != r {
247                        continue;
248                    }
249                    if x < 0 || y < 0 || x >= n || y >= n {
250                        continue;
251                    }
252                    let i = (y * n + x) as usize;
253                    if self.cells.objects[i].is_some() {
254                        continue;
255                    }
256                    if let Some(o) = self.cells.occupants[i] {
257                        if Some(o) != owner {
258                            continue;
259                        }
260                    }
261                    let t = self.cells.types[i].0 as u32;
262                    // Types 0 and 1 (`1 << t & 3`), a road (`+0x2a`) or a planned one.
263                    if 1u32 << (t & 0x1f) & 3 != 0
264                        || self.cells.road_kind[i] != 0xff
265                        || self.pending_roads.contains_key(&(i as i32))
266                    {
267                        continue;
268                    }
269                    if ok(t, i) {
270                        return Some(y * n + x);
271                    }
272                }
273            }
274        }
275        None
276    }
277}
278
279/// `FUN_1400c4440`'s arguments.
280struct ProduceSequence {
281    target: [f32; 3],
282    facing: f32,
283    recipe: Recipe,
284    produce: bool,
285    out_cell: i32,
286    work_type: u32,
287    duration: f32,
288    param: i32,
289}