Skip to main content

unbanished_game/nature/seeding/
growth.rs

1//! Growth: the iteration over scheduled entities, a scheduled growth step, smoothing and animation.
2
3use super::*;
4
5impl Seeder<'_> {
6    // +0xd0
7    /// One iteration of the placed entities' growth components. `disabled` is the game's bit 10,
8    /// which stops spawning and the change at full growth, but not growth or the decay in frost.
9    /// The callbacks of other components are not installed yet.
10    ///
11    /// Original: `FUN_1400c9560`, then `FUN_140125520`.
12    pub fn iterate(
13        &mut self,
14        scheduler: &mut EntityScheduler<usize>,
15        dt: f32,
16        temperature: f32,
17        disabled: bool,
18    ) -> bool {
19        self.iterate_with(scheduler, dt, temperature, disabled, &mut |_, _, _, _| {
20            false
21        })
22    }
23
24    /// [`Seeder::iterate`] with the scheduled update of entities without growth (`visit`
25    /// returns whether the models changed).
26    pub fn iterate_with(
27        &mut self,
28        scheduler: &mut EntityScheduler<usize>,
29        dt: f32,
30        temperature: f32,
31        disabled: bool,
32        visit: &mut dyn FnMut(&mut Seeder, &mut EntityScheduler<usize>, usize, i64) -> bool,
33    ) -> bool {
34        let mut changed = self.begin_iteration(scheduler, dt);
35        for bucket in 0..5 {
36            let visits = scheduler.visit_bucket(bucket);
37            changed |= self.run_visits(scheduler, &visits, temperature, disabled, visit);
38        }
39        self.end_iteration(scheduler);
40        changed
41    }
42
43    /// The start of an iteration: the clock advances, then the models' every-iteration update
44    /// (bit `0x04`). True when the models changed.
45    ///
46    /// Original: `FUN_1400c9560`.
47    pub fn begin_iteration(&mut self, scheduler: &mut EntityScheduler<usize>, dt: f32) -> bool {
48        scheduler.advance(dt);
49        // FUN_1400c9560's bit-0x04 component phase precedes scheduled growth. Within a tree
50        // the ModelComponent (FUN_140129e30) runs before NaturalResource (FUN_14012b110).
51        self.animate(ticks(dt))
52    }
53
54    /// One bucket's visits (from [`EntityScheduler::visit_bucket`]), in order: each visited
55    /// entity's scheduled components the seeder owns (growth, spawning, then `visit` for the
56    /// others). Citizens (from `EXTRA`) are the agents' and are passed over. True when the models
57    /// changed.
58    ///
59    /// Original: `FUN_1400c9560`.
60    pub fn run_visits(
61        &mut self,
62        scheduler: &mut EntityScheduler<usize>,
63        visits: &[(usize, usize, i64)],
64        temperature: f32,
65        disabled: bool,
66        visit: &mut dyn FnMut(&mut Seeder, &mut EntityScheduler<usize>, usize, i64) -> bool,
67    ) -> bool {
68        let mut changed = false;
69        for &(_, id, elapsed) in visits {
70            if id >= crate::scheduler::EXTRA {
71                continue;
72            }
73            changed |= self.scheduled_growth(scheduler, id, elapsed, temperature, disabled);
74            // SpawnComponent (`FUN_140056430`) follows Growth in the template's list.
75            changed |= self.scheduled_spawn(scheduler, id, elapsed, disabled);
76            // The entity's other scheduled components (FruitComponent after Growth, wildlife).
77            if self.placed[id].alive {
78                changed |= visit(self, scheduler, id, elapsed);
79            }
80        }
81        changed
82    }
83
84    /// The end of an iteration: the entities queued for removal leave the buckets, after all
85    /// five buckets.
86    ///
87    /// Original: `FUN_1400c9560`.
88    pub fn end_iteration(&mut self, scheduler: &mut EntityScheduler<usize>) {
89        for id in self.removed.drain(..) {
90            scheduler.remove(id);
91        }
92    }
93
94    /// GrowthComponent's scheduled update for one visited entity; true when the models changed.
95    pub(super) fn scheduled_growth(
96        &mut self,
97        scheduler: &mut EntityScheduler<usize>,
98        id: usize,
99        elapsed: i64,
100        temperature: f32,
101        disabled: bool,
102    ) -> bool {
103        let mut changed = false;
104        {
105            let p = &mut self.placed[id];
106            if !p.alive {
107                return changed;
108            }
109            let Some(state) = &mut p.growth_state else {
110                return changed;
111            };
112            let d = self.templates[p.template].growth.as_ref().unwrap();
113            let result = state.update(d, &mut p.growth, elapsed, temperature, disabled);
114            if !disabled {
115                for _ in 0..result.spawn_attempts {
116                    if let Some(child) = self.periodic_spawn(id) {
117                        let handle = scheduler.register_at(
118                            child,
119                            child,
120                            self.templates[self.placed[child].template].bucket,
121                        );
122                        debug_assert_eq!(handle, child);
123                        changed = true;
124                    }
125                }
126            }
127            if let Some(adjustment) = result.map_adjustment {
128                let p = &self.placed[id];
129                let i = (p.cell.1 * self.n() + p.cell.0) as usize;
130                self.cells.growth_bytes[i] =
131                    adjust_map_byte(self.cells.growth_bytes[i], adjustment);
132                self.cells.previous_template[i] = Some(p.template);
133                if self.templates[p.template]
134                    .natural
135                    .as_ref()
136                    .is_some_and(|n| n.flag)
137                {
138                    // FUN_14012bc50 -> FUN_14012b910 -> FUN_14012a5c0: use the selected
139                    // model variant's animation group, index 2, start time zero.
140                    let p = &mut self.placed[id];
141                    p.removal_requested = true;
142                    p.animation = self.templates[p.template]
143                        .animations
144                        .get(p.variant)
145                        .and_then(Option::as_ref)
146                        .and_then(|g| g.clips.get(2))
147                        .map(|_| Playback::new(2, 0));
148                } else {
149                    self.remove(id);
150                    changed = true;
151                }
152            }
153        }
154        changed
155    }
156
157    /// A single post-iteration smoothing phase.
158    ///
159    /// Original: `FUN_1400c98a0`, `FUN_140125370`.
160    pub fn smooth(&mut self) -> bool {
161        let mut changed = false;
162        for p in self.placed.iter_mut() {
163            if !p.alive {
164                continue;
165            }
166            if let Some(state) = &mut p.growth_state {
167                let d = self.templates[p.template].growth.as_ref().unwrap();
168                changed |= state.smooth(d, p.growth, &mut p.scale);
169            }
170        }
171        changed
172    }
173
174    /// Port of FUN_140129e30 -> Runtime MeshInstance::Update (0x180103090), followed by
175    /// FUN_14012b110's completion/removal callback. The clock advances per simulation iteration,
176    /// while the published pose uses the old clock; pause runs neither callback.
177    pub(super) fn animate(&mut self, dt: i64) -> bool {
178        let mut finished = Vec::new();
179        let mut changed = false;
180        for (id, p) in self.placed.iter_mut().enumerate() {
181            if !p.alive {
182                continue;
183            }
184            let Some(playback) = &mut p.animation else {
185                if p.removal_requested {
186                    finished.push(id);
187                }
188                continue;
189            };
190            let Some(clip) = self.templates[p.template]
191                .animations
192                .get(p.variant)
193                .and_then(Option::as_ref)
194                .and_then(|g| g.clips.get(playback.clip))
195            else {
196                continue;
197            };
198            if !playback.is_animating(clip) {
199                continue;
200            }
201            for event in playback.update(clip, dt) {
202                let Some(reference) = &clip.events[event].resource else {
203                    continue;
204                };
205                // `AnimAudioEvent` slot +0x40 (`FUN_14008d310`): `RandFloat()` from the game
206                // stream against the probability, then `PlayEffect3D(effect, 4)` at the entity.
207                let audio = self.templates[p.template]
208                    .audio_events
209                    .iter()
210                    .find(|(r, _, _)| r == reference);
211                if let Some((_, effect, probability)) = audio {
212                    if self.rng.rand_float() <= *probability {
213                        if let Some(effect) = effect {
214                            self.animation_events.push((id, effect.clone()));
215                        }
216                    }
217                }
218            }
219            changed = true;
220            if !playback.is_animating(clip) && p.removal_requested {
221                finished.push(id);
222            }
223        }
224        for id in finished {
225            self.remove(id);
226            changed = true;
227        }
228        changed
229    }
230}