Skip to main content

unbanished_game/nature/seeding/
spawning.rs

1//! Spawning: where a child may grow, spawning one from a parent, planting, a template's spawn state, periodic and scheduled spawns, and removing an entity.
2
3use super::*;
4
5impl Seeder<'_> {
6    /// `FUN_1400a4aa0(map, x, y, 4, 0.98, 1000, 0, …)`: buildable ground with no entity and a
7    /// flat enough surface.
8    pub(super) fn spawn_spot_ok(&self, x: i32, y: i32) -> bool {
9        let n = self.n();
10        if x < 0 || y < 0 || x >= n || y >= n {
11            return false;
12        }
13        let i = y * n + x;
14        if self.cells.types[i as usize] != CellType::GROUND {
15            return false;
16        }
17        if self.cells.occupants[i as usize].is_some() || self.cells.flags[i as usize] != 0 {
18            return false;
19        }
20        let (px, py) = self.cell_position(i);
21        let mut normal = [0.0f32; 3];
22        let h = self
23            .cells
24            .floors
25            .ground_normal(self.cells.size, self.terrain, px, py, &mut normal);
26        SPAWN_NORMAL <= normal[2] && (h - 0.0).abs() <= SPAWN_HEIGHT_TOLERANCE
27    }
28
29    /// `FUN_140056620`: spawn children around a newly grown parent.
30    pub(super) fn spawn(&mut self, parent: usize) {
31        let template = self.placed[parent].template;
32        let growth = self.placed[parent].growth;
33        for (entry, (child, lo, hi)) in self.templates[template]
34            .spawn
35            .clone()
36            .into_iter()
37            .enumerate()
38        {
39            if !(lo <= growth && growth <= hi) {
40                continue;
41            }
42            let step = self.templates[child]
43                .growth
44                .as_ref()
45                .map_or(1.0, |g| g.max_base);
46            let attempts = (growth / step) as i32 + 1;
47            for _ in 0..attempts {
48                self.spawn_child(parent, entry, true, false);
49            }
50        }
51    }
52
53    /// Startup uses random_growth=true; scheduled spawning uses false. The child is registered in
54    /// the PARENT TEMPLATE's bucket (not its own template's bucket).
55    ///
56    /// Original: `FUN_1400560e0`.
57    pub fn spawn_child(
58        &mut self,
59        parent: usize,
60        entry: usize,
61        random_growth: bool,
62        disabled: bool,
63    ) -> Option<usize> {
64        if disabled {
65            return None;
66        }
67        let parent_template = self.placed[parent].template;
68        let child = self.templates[parent_template].spawn[entry].0;
69        let (px, py) = self.placed[parent].cell;
70        let g = self.templates[child].growth.clone()?;
71        if self.rng.rand_float() > ONE / g.spawn_one_in as f32 {
72            return None;
73        }
74        let x = px + self.rng.rand_tol(g.spawn_radius);
75        let y = py + self.rng.rand_tol(g.spawn_radius);
76        let n = self.n();
77        if x < 0 || y < 0 || x >= n || y >= n || !self.spawn_spot_ok(x, y) {
78            return None;
79        }
80        if !self.density_ok(child, x, y) {
81            return None;
82        }
83        let (variant, mesh, max_growth) = self.construct(child);
84        let (position, yaw) = self.position(child, n * y + x);
85        let (state, growth, scale) = self.set_growth(child, max_growth, 0.0);
86        let id = self.register(Placed {
87            template: child,
88            bucket: self.templates[parent_template].bucket,
89            cell: (x, y),
90            footprint: (1, 1),
91            position,
92            yaw,
93            variant,
94            mesh,
95            growth,
96            growth_state: Some(state),
97            spawn_state: self.spawn_state(child),
98            alive: true,
99            removal_requested: false,
100            animation: None,
101            scale,
102        });
103        if random_growth {
104            let fraction = self.rng.rand_float();
105            let (state, growth, scale) = self.set_growth(child, max_growth, fraction);
106            self.placed[id].growth = growth;
107            self.placed[id].scale = scale;
108            self.placed[id].growth_state = Some(state);
109        }
110        Some(id)
111    }
112
113    /// CreateNaturalResource's start on a free cell: clone the template, place it in the cell,
114    /// growth 0, then a random model variant and mesh, and register it.
115    ///
116    /// Original: `FUN_1400cbb20`, `FUN_1400c8bf0`, `FUN_14012ba10`, `FUN_140126280`,
117    /// `FUN_14012a8a0`.
118    pub fn plant(&mut self, template: usize, cell: i32) -> usize {
119        let (_, _, max_growth) = self.construct(template);
120        let (position, yaw) = self.position(template, cell);
121        let (state, growth, scale) = self.set_growth(template, max_growth, 0.0);
122        let variants = self.templates[template]
123            .model
124            .as_ref()
125            .map_or(1, |m| m.variants.len().max(1));
126        let variant = self.rng.rand_below(variants as u32) as usize;
127        let meshes = self.templates[template]
128            .model
129            .as_ref()
130            .and_then(|m| m.variants.get(variant))
131            .map_or(1, |v| v.meshes.len().max(1));
132        let mesh = self.rng.rand_below(meshes as u32) as usize;
133        let n = self.n();
134        self.register(Placed {
135            template,
136            bucket: self.templates[template].bucket,
137            cell: (cell % n, cell / n),
138            footprint: (1, 1),
139            position,
140            yaw,
141            variant,
142            mesh,
143            growth,
144            growth_state: Some(state),
145            spawn_state: self.spawn_state(template),
146            alive: true,
147            removal_requested: false,
148            animation: None,
149            scale,
150        })
151    }
152
153    pub(super) fn spawn_state(&self, template: usize) -> Option<Spawn> {
154        self.templates[template]
155            .updates
156            .contains(&ScheduledComponent::Spawn)
157            .then(|| Spawn::new(self.templates[template].spawn.len()))
158    }
159
160    /// Port of FUN_140125070: reproduce using the parent's template and model variant. Unlike
161    /// FUN_1400560e0's startup children, this path initializes the child's growth at zero and
162    /// selects a mesh after the timer draw; it never draws a random initial growth fraction.
163    pub(super) fn periodic_spawn(&mut self, parent: usize) -> Option<usize> {
164        let template = self.placed[parent].template;
165        let g = self.templates[template].growth.as_ref()?;
166        if self.rng.rand_float() > ONE / g.spawn_one_in as f32 {
167            return None;
168        }
169        let (px, py) = self.placed[parent].cell;
170        let x = px + self.rng.rand_tol(g.spawn_radius);
171        let y = py + self.rng.rand_tol(g.spawn_radius);
172        if !self.spawn_spot_ok(x, y) || !self.density_ok(template, x, y) {
173            return None;
174        }
175        let variant = self.placed[parent].variant;
176        let (_, _, maximum) = self.construct(template);
177        let (position, yaw) = self.position(template, y * self.n() + x);
178        let (state, growth, scale) = self.set_growth(template, maximum, 0.0);
179        let meshes = self.templates[template]
180            .model
181            .as_ref()?
182            .variants
183            .get(variant)?
184            .meshes
185            .len();
186        let mesh = self.rng.rand_below(meshes as u32) as usize;
187        Some(self.register(Placed {
188            template,
189            bucket: self.templates[template].bucket,
190            cell: (x, y),
191            footprint: (1, 1),
192            position,
193            yaw,
194            variant,
195            mesh,
196            growth,
197            growth_state: Some(state),
198            spawn_state: self.spawn_state(template),
199            alive: true,
200            removal_requested: false,
201            animation: None,
202            scale,
203        }))
204    }
205
206    /// SpawnComponent's scheduled update (`FUN_140056430`) for one visited entity: each entry
207    /// whose growth band holds the parent's growth runs its clock, and every child growth
208    /// period (`+0x28 × 300`) it tries a child (`FUN_1400560e0`, without random growth).
209    pub(super) fn scheduled_spawn(
210        &mut self,
211        scheduler: &mut EntityScheduler<usize>,
212        id: usize,
213        elapsed: i64,
214        disabled: bool,
215    ) -> bool {
216        let p = &self.placed[id];
217        if !p.alive || p.spawn_state.is_none() {
218            return false;
219        }
220        let growth = p.growth;
221        let entries: Vec<(f32, f32, f32)> = self.templates[p.template]
222            .spawn
223            .iter()
224            .map(|&(child, lo, hi)| {
225                let period = self.templates[child].growth.as_ref().map_or(0.0, |g| g.f28);
226                (lo, hi, period)
227            })
228            .collect();
229        let attempts = self.placed[id]
230            .spawn_state
231            .as_mut()
232            .unwrap()
233            .update(growth, elapsed, &entries);
234        let mut changed = false;
235        for (entry, count) in attempts {
236            for _ in 0..count {
237                if let Some(child) = self.spawn_child(id, entry, false, disabled) {
238                    let handle = scheduler.register_at(child, child, self.placed[child].bucket);
239                    debug_assert_eq!(handle, child);
240                    changed = true;
241                }
242            }
243        }
244        changed
245    }
246
247    /// Port of FUN_140125a30 and FUN_1400a33b0 for one-cell natural-resource removal. Keep
248    /// handles stable; the scheduler swaps its bucket entries separately at the end of the tick.
249    pub(super) fn remove(&mut self, id: usize) {
250        let p = &mut self.placed[id];
251        if !p.alive {
252            return;
253        }
254        p.alive = false;
255        self.removed.push(id);
256        let (x, y) = p.cell;
257        let i = y as usize * self.cells.size + x as usize;
258        if let Some(d) = &self.templates[p.template].growth {
259            if p.growth != 0.0 {
260                let factor = if self.cells.previous_template[i] == Some(p.template) {
261                    d.f3c
262                } else {
263                    d.f40
264                };
265                self.cells.growth_bytes[i] =
266                    adjust_map_byte(self.cells.growth_bytes[i], p.growth.min(1.0) * factor);
267                self.cells.previous_template[i] = Some(p.template);
268            }
269        }
270        if self.cells.objects[i] == Some(id) {
271            let ty = self.terrain.natural_cell_type(self.cells.size, i);
272            self.cells.set_type(i, ty);
273            self.cells.objects[i] = None;
274        }
275    }
276}