Skip to main content

unbanished_game/nature/wildlife/
animals.rs

1//! Animals: creating and placing them, their schedule, one update (wander, idle, grow up, die), and being hunted.
2
3use super::*;
4
5impl Wild<'_, '_> {
6    /// `FUN_1400c8bf0` + `FUN_1400c9d70` for an entity without a map footprint: a placed
7    /// entry registered in its template's bucket.
8    pub(super) fn create(&mut self, template: usize, position: [f32; 3]) -> usize {
9        let id = self.place(template, position);
10        let handle = self
11            .scheduler
12            .register_at(id, id, self.templates[template].bucket);
13        debug_assert_eq!(handle, id);
14        id
15    }
16
17    /// The placed entry of [`Wild::create`] alone (its owner registers it in the buckets).
18    pub(super) fn place(&mut self, template: usize, position: [f32; 3]) -> usize {
19        let id = self.placed.len();
20        let cell = self.cell_of(position);
21        let n = self.n();
22        self.placed.push(Placed {
23            template,
24            bucket: self.templates[template].bucket,
25            cell: (cell % n, cell / n),
26            footprint: (1, 1),
27            position,
28            yaw: 0.0,
29            variant: 0,
30            mesh: usize::MAX,
31            growth: 0.0,
32            growth_state: None,
33            spawn_state: None,
34            alive: true,
35            removal_requested: false,
36            animation: None,
37            scale: [1.0; 4],
38        });
39        id
40    }
41
42    /// The setups `FUN_1400c8bf0` runs when it makes an animal, in its template's order (the model
43    /// before the animal in every animal template): the ModelComponent's variant (random when the
44    /// model says so) and its mesh (`FUN_140129f90`), then the AnimalComponent's lifespan
45    /// (`FUN_14010c220`).
46    pub(super) fn pick_variant(&mut self, template: usize) -> Option<(usize, usize, f32)> {
47        let d = self.wildlife.animal_kinds.get(&template)?.desc.clone();
48        let t = &self.templates[template];
49        let (mut variant, mut mesh) = (0usize, 0usize);
50        if let Some(m) = &t.model {
51            variant = m.variant.max(0) as usize;
52            if m.random_variant {
53                variant = self.rng.rand_below(m.variants.len() as u32) as usize;
54            }
55            mesh = m.mesh.max(0) as usize;
56        }
57        let life = self.rng.rand_float_tol() * d.life_range + d.life;
58        Some((variant, mesh, life))
59    }
60
61    /// A new animal of `template` with the variant and lifespan [`Wild::pick_variant`] chose
62    /// (`FUN_14010c8d0`: placed, turned, wild; a male takes the variant's second mesh).
63    pub(super) fn insert_animal(
64        &mut self,
65        template: usize,
66        (variant, mut mesh, life): (usize, usize, f32),
67        position: [f32; 3],
68        yaw: f32,
69        male: bool,
70    ) -> Option<usize> {
71        let kind = self.wildlife.animal_kinds.get(&template)?.clone();
72        if let Some(m) = &self.templates[template].model {
73            if male && m.variants.get(variant).is_some_and(|v| v.meshes.len() > 1) {
74                mesh = 1;
75            }
76        }
77        let id = self.placed.len();
78        let mut character = Character::new(kind.character, position, 1.0);
79        character.yaw = yaw;
80        self.wildlife.animals.insert(
81            id,
82            Animal {
83                template,
84                character,
85                herd: None,
86                flags: WILD,
87                home: -1,
88                timer: 0,
89                area: [0; 4],
90                male,
91                age: 0.0,
92                life,
93                breed: 0,
94                livestock: self
95                    .wildlife
96                    .livestock_kinds
97                    .contains_key(&template)
98                    .then(Livestock::default),
99                variant,
100                mesh,
101                scale: 1.0,
102                dying: false,
103            },
104        );
105        self.rescale(id);
106        Some(id)
107    }
108
109    /// `FUN_1400c9d70` for an animal: its entity and the activation (`FUN_14010c0f0`: home where it stands, its area around it, then the
110    /// scheduled update with no time).
111    pub(super) fn register_animal(&mut self, a: usize) {
112        self.register_animal_in(a, true);
113    }
114
115    /// [`Wild::register_animal`]; without `buckets` the owner registers the entity.
116    pub(super) fn register_animal_in(&mut self, a: usize, buckets: bool) {
117        let template = self.wildlife.animals[&a].template;
118        let position = self.wildlife.animals[&a].character.position;
119        let e = if buckets {
120            self.create(template, position)
121        } else {
122            self.place(template, position)
123        };
124        debug_assert_eq!(e, a);
125        self.wildlife.kinds.insert(a, Kind::Animal);
126        // CharacterComponent's start (`FUN_14010ee90`): the target heading takes the model's yaw
127        // (`+0x3c`), then into the tree.
128        let ch = &mut self.wildlife.animals.get_mut(&a).unwrap().character;
129        ch.target_heading = ch.yaw;
130        let ch = &self.wildlife.animals[&a].character;
131        let slot = self.wildlife.tree.insert(
132            crate::behaviour::character_tree::Who::Animal(a),
133            ch.position,
134            ch.desc.radius,
135        );
136        self.wildlife
137            .animals
138            .get_mut(&a)
139            .unwrap()
140            .character
141            .tree_slot = slot;
142        let d = self.wildlife.animal_kinds[&template].desc.clone();
143        let n = self.n();
144        let cell = self.cell_of(position);
145        let animal = self.wildlife.animals.get_mut(&a).unwrap();
146        if animal.flags & WILD != 0 {
147            animal.home = cell;
148            animal.area = area_around(n, cell, d.area);
149            self.update_animal(a, 0);
150        }
151        // LivestockComponent's activation (`FUN_140129140`): without a pasture it waits in the
152        // town's list.
153        let animal = &self.wildlife.animals[&a];
154        if animal.livestock.is_some_and(|l| l.pasture.is_none()) {
155            self.wildlife.unassigned.push(a);
156        }
157    }
158
159    /// `FUN_14010c7f0`: the model grows from a third to full size by the adult age.
160    pub(super) fn rescale(&mut self, a: usize) {
161        let Some(animal) = self.wildlife.animals.get_mut(&a) else {
162            return;
163        };
164        let d = &self.wildlife.animal_kinds[&animal.template].desc;
165        // jbe at 0x14010c842: held at 1 above it; a NaN stays (`f32::min` would give 1).
166        let s = animal.age / d.adult * 0.67 + 0.33;
167        let s = if s > 1.0 { 1.0 } else { s };
168        animal.scale = s;
169        animal.character.scale = s;
170    }
171
172    /// A scheduled visit of entity `e` with `elapsed` ticks.
173    pub fn scheduled(&mut self, e: usize, elapsed: i64) {
174        match self.wildlife.kinds.get(&e).copied() {
175            Some(Kind::Population(p)) => self.update_population(p, elapsed),
176            Some(Kind::Herd(h)) => self.update_herd(h, elapsed),
177            Some(Kind::Animal) => {
178                // CharacterComponent's scheduled notify (`FUN_14010e950`): MoveTo's follow
179                // check (`FUN_1400cde40`).
180                if let Some(animal) = self.wildlife.animals.get_mut(&e) {
181                    let following = self.wildlife.tree.follows(animal.character.tree_slot);
182                    animal.character.stack.notify_moves(following);
183                }
184                self.update_animal(e, elapsed);
185                self.update_livestock(e, elapsed);
186            }
187            None => {}
188        }
189    }
190
191    /// AnimalComponent's scheduled update.
192    ///
193    /// Original: `FUN_14010b8f0`.
194    pub fn update_animal(&mut self, a: usize, dt: i64) {
195        let Some(animal) = self.wildlife.animals.get_mut(&a) else {
196            return;
197        };
198        if animal.dying {
199            return;
200        }
201        let d = self.wildlife.animal_kinds[&animal.template].desc.clone();
202        animal.age += seconds(dt) * (1.0 / 3600.0);
203        if animal.life < animal.age {
204            self.kill(a);
205            return;
206        }
207        // A breeding male: once grown, young every `breed` years and up to as much again.
208        let animal = self.wildlife.animals.get_mut(&a).unwrap();
209        if animal.male && animal.flags & BIRTH == 0 && animal.flags & BREEDER != 0 {
210            // jbe at 0x14010ba12: not grown, or a NaN age, draws no breeding time.
211            #[allow(clippy::neg_cmp_op_on_partial_ord)]
212            if animal.breed != 0 || !(d.adult < animal.age) {
213                if 0 < animal.breed {
214                    animal.breed -= dt;
215                    if animal.breed <= 0 {
216                        // `FUN_14011de20(.., 0x200000, 0)`.
217                        animal.flags |= BIRTH;
218                        animal.breed = 0;
219                    }
220                }
221            } else {
222                let years = self.rng.rand_float() * d.breed + d.breed;
223                self.wildlife.animals.get_mut(&a).unwrap().breed = ticks(years * 3600.0);
224            }
225        }
226        self.rescale(a);
227        let n = self.n();
228        let animal = self.wildlife.animals.get_mut(&a).unwrap();
229        if animal.character.stack.is_active() {
230            return;
231        }
232        animal.timer -= dt;
233        if 0 < animal.timer {
234            return;
235        }
236        let mut anim = 1;
237        if animal.flags & HUNTED == 0 {
238            if animal.flags & WILD != 0 {
239                let home = animal.home;
240                // A home under an occupant other than a trading post (`+0x00`, its
241                // TradeComponent) or no longer ground: a new home and area.
242                let taken = home >= 0
243                    && self.cells.occupants[home as usize]
244                        .is_some_and(|o| !self.templates[self.placed[o].template].trading_post);
245                if home < 0 || self.cells.types[home as usize] != CellType(2) || taken {
246                    self.rehome(a, &d);
247                }
248            }
249            let animal = &self.wildlife.animals[&a];
250            let here = self.cell_of(animal.character.position);
251            let area = animal.area;
252            let mut wander = !inside(&area, here, n);
253            if !wander {
254                anim = self.rng.rand_below(4) as usize;
255                wander = anim == 0;
256            }
257            if wander {
258                let mut in_area = 0;
259                let mut total = 0;
260                let mut dest;
261                loop {
262                    let area = self.wildlife.animals[&a].area;
263                    let ry = self.rng.rand_below(area[3] as u32) as i32;
264                    let rx = self.rng.rand_below(area[2] as u32) as i32;
265                    let cell = rx + area[0] as i32 + (ry + area[1] as i32) * n;
266                    let base = self.ground(cell);
267                    let first = self.rng.rand_float_tol();
268                    let second = self.rng.rand_float_tol();
269                    dest = [base[0] + second * 0.4, base[1] + first * 0.4, base[2]];
270                    if 10 < in_area {
271                        self.rehome(a, &d);
272                        in_area = 0;
273                    }
274                    in_area += 1;
275                    total += 1;
276                    let at = self.cell_of(dest);
277                    if self.cells.types[at as usize] == CellType(2) || 100 <= total {
278                        break;
279                    }
280                }
281                if self.cells.types[self.cell_of(dest) as usize] == CellType(2) {
282                    let walk = MoveTo::new(dest, 0, 1, ANIMAL_WALK, 1, -1.0, self.rng);
283                    self.restack(a, Some(Action::move_to(walk)));
284                    self.wildlife.animals.get_mut(&a).unwrap().timer = 0;
285                    return;
286                }
287                anim = self.rng.rand_below(3) as usize + 1;
288            }
289        }
290        let idle = self.rng.rand_float() * d.idle + d.idle;
291        self.idle(a, anim, idle, d.turn);
292    }
293
294    /// `FUN_1400ca8d0` on the animal's stack, then (with `action`) `FUN_1400ca9b0`.
295    pub(super) fn restack(&mut self, a: usize, action: Option<Action>) {
296        let Some(animal) = self.wildlife.animals.get(&a) else {
297            return;
298        };
299        let Some(group) = self
300            .wildlife
301            .groups
302            .get(&(animal.template, animal.variant))
303            .cloned()
304        else {
305            return;
306        };
307        let ch = &mut self.wildlife.animals.get_mut(&a).unwrap().character;
308        let mut stack = std::mem::take(&mut ch.stack);
309        stack.clear(ch, &group, &mut []);
310        if let Some(action) = action {
311            stack.push(ch, &group, action);
312        }
313        ch.stack = stack;
314    }
315
316    /// A hunter has the animal: it stops what it does and stands.
317    ///
318    /// Original: `FUN_14010c730`.
319    pub fn hunted(&mut self, a: usize) {
320        let Some(animal) = self.wildlife.animals.get_mut(&a) else {
321            return;
322        };
323        animal.flags |= HUNTED;
324        if animal.character.stack.is_active() {
325            self.restack(a, None);
326            self.update_animal(a, 0);
327        }
328    }
329
330    /// `FUN_14010b720`: play clip `anim` for `seconds`; with `turn`, face a random way.
331    pub(super) fn idle(&mut self, a: usize, anim: usize, secs: f32, turn: bool) {
332        let group = {
333            let animal = &self.wildlife.animals[&a];
334            self.wildlife
335                .groups
336                .get(&(animal.template, animal.variant))
337                .cloned()
338        };
339        let animal = self.wildlife.animals.get_mut(&a).unwrap();
340        match &group {
341            Some(g) => animal.character.animation.play(g, anim, 0),
342            None => animal.character.animation = AnimationStack::new(anim, 0),
343        }
344        animal.timer = ticks(secs);
345        if turn {
346            // FUN_14010b720: (second draw, first draw, 0) normalized; the direction that
347            // normalized again, the heading of the first (`Vector3::Heading`).
348            let y = self.rng.rand_float_tol();
349            let x = self.rng.rand_float_tol();
350            let v = crate::math::normalize3([x, y, 0.0]);
351            let ch = &mut self.wildlife.animals.get_mut(&a).unwrap().character;
352            ch.flag_28 = false;
353            ch.direction = crate::math::normalize3(v);
354            ch.target_heading = crate::math::heading(v[0], v[1]);
355        }
356    }
357
358    /// `FUN_14010b4f0` then `FUN_14010b2f0`: the nearest free ground in growing squares around
359    /// the home becomes the home, and the area follows.
360    pub(super) fn rehome(&mut self, a: usize, d: &AnimalDescription) {
361        let n = self.n();
362        let home = self.wildlife.animals[&a].home.max(0);
363        let new = nearest_ground(self.cells, n, home);
364        let animal = self.wildlife.animals.get_mut(&a).unwrap();
365        animal.home = new;
366        animal.area = area_around(n, new, d.area);
367    }
368}