Skip to main content

unbanished_game/nature/wildlife/
herds.rs

1//! Herds: their area within a block, spawning and regrowing their animals, and moving home.
2
3use super::*;
4
5/// `FUN_14010bfe0`: `cell` within `area`.
6pub(super) fn inside(area: &[i16; 4], cell: i32, n: i32) -> bool {
7    let (x, y) = (cell % n, cell / n);
8    let (ax, ay, aw, ah) = (
9        area[0] as i32,
10        area[1] as i32,
11        area[2] as i32,
12        area[3] as i32,
13    );
14    !(x < ax || y < ay || ax + aw <= x || ay + ah <= y)
15}
16
17/// `FUN_14010b2f0`: a `size` square around `cell`, clamped to the map.
18pub(super) fn area_around(n: i32, cell: i32, size: i32) -> [i16; 4] {
19    let half = size / 2;
20    let x = (cell % n - half).max(0);
21    let y = (cell / n - half).max(0);
22    let mut w = size;
23    let mut h = size;
24    if n <= w + x {
25        w = n - x - 1;
26    }
27    if n <= h + y {
28        h = n - y - 1;
29    }
30    [x as i16, y as i16, w as i16, h as i16]
31}
32
33/// `FUN_14010b4f0`: the first ground cell without an occupant on the border of squares of
34/// side 5, 7, … 31 around `home` (top and bottom rows by column, then the sides by row), else
35/// `home`.
36pub(super) fn nearest_ground(cells: &Cells, n: i32, home: i32) -> i32 {
37    let free = |c: i32| {
38        c >= 0
39            && (c as usize) < cells.types.len()
40            && cells.types[c as usize] == CellType(2)
41            && cells.occupants[c as usize].is_none()
42    };
43    let mut s = 3;
44    loop {
45        s += 2;
46        let half = s / 2;
47        let x0 = (home % n - half).max(0);
48        let y0 = (home / n - half).max(0);
49        let mut w = s;
50        if n <= s + x0 {
51            w = n - x0 - 1;
52        }
53        let mut h = s;
54        if n <= s + y0 {
55            h = n - y0 - 1;
56        }
57        let bottom = y0 - 1 + h;
58        let right = w - 1 + x0;
59        for x in x0..=right {
60            if free(y0 * n + x) {
61                return y0 * n + x;
62            }
63            if free(n * bottom + x) {
64                return n * bottom + x;
65            }
66        }
67        let mut y = y0;
68        loop {
69            y += 1;
70            if y > bottom - 1 {
71                break;
72            }
73            if free(n * y + x0) {
74                return x0 + n * y;
75            }
76            if free(n * y + right) {
77                return y * n + right;
78            }
79        }
80        if 30 < s {
81            return home;
82        }
83    }
84}
85
86impl Wild<'_, '_> {
87    /// The herd's area around its target (`FUN_140126fa0` / `FUN_140127810`): `area` wide,
88    /// kept a cell off the map's edge (the height test adds the possibly shortened width, as
89    /// the original does).
90    pub(super) fn herd_area(&self, h: usize) -> [i16; 4] {
91        let herd = &self.wildlife.herds[h];
92        let size = self.wildlife.herd_kinds[&herd.template].desc.area;
93        let n = self.n();
94        let x0 = (herd.target % n - (size >> 1)).max(1);
95        let y0 = (herd.target / n - (size >> 1)).max(1);
96        let mut w = size;
97        if n - 1 <= x0 + size {
98            w = n - x0 - 2;
99        }
100        let mut h = size;
101        if n - 1 <= y0 + w {
102            h = n - y0 - 2;
103        }
104        [x0 as i16, y0 as i16, w as i16, h as i16]
105    }
106
107    /// A new target in the herd's block; every animal keeps to the area around it. Without habitat
108    /// the herd's animals are removed.
109    ///
110    /// Original: `FUN_140127810`.
111    pub fn retarget(&mut self, h: usize) {
112        let (p, index, template) = {
113            let herd = &self.wildlife.herds[h];
114            (herd.population, herd.index, herd.template)
115        };
116        let _ = template;
117        let pt = self.wildlife.populations[p].template;
118        let d = self.wildlife.population_kinds[&pt].desc.clone();
119        let n = self.n();
120        let target = self.wildlife.populations[p].pick(&d, index, n, self.rng);
121        self.wildlife.herds[h].target = target;
122        if target < 0 {
123            for a in std::mem::take(&mut self.wildlife.herds[h].animals) {
124                self.kill(a);
125            }
126            return;
127        }
128        let area = self.herd_area(h);
129        for a in self.wildlife.herds[h].animals.clone() {
130            if let Some(animal) = self.wildlife.animals.get_mut(&a) {
131                animal.area = area;
132            }
133        }
134    }
135
136    /// `FUN_140126420`: a new target, then `count` animals at random cells of its area.
137    pub(super) fn spawn_herd(&mut self, h: usize, count: i32) {
138        self.retarget(h);
139        let template = self.wildlife.herds[h].template;
140        let hk = self.wildlife.herd_kinds[&template].clone();
141        let area = self.herd_area(h);
142        let (x0, y0, w, hh) = (
143            area[0] as i32,
144            area[1] as i32,
145            area[2] as i32,
146            area[3] as i32,
147        );
148        // The first animal's sex; the rest alternate (`sete` after each, `0x1401267d9`).
149        let mut male = self.rng.rand_below(2) == 0;
150        let n = self.n();
151        for _ in 0..count {
152            let x = x0 + self.rng.rand_below(w.max(0) as u32) as i32;
153            let y = y0 + self.rng.rand_below(hh.max(0) as u32) as i32;
154            // The entity is made here (`FUN_1400c8bf0`): its model's setup draws the variant
155            // before the offsets and the heading.
156            let Some(variant) = self.pick_variant(hk.animal) else {
157                return;
158            };
159            let base = self.ground(n * y + x);
160            let dy = self.rng.rand_float_tol();
161            let dx = self.rng.rand_float_tol();
162            let position = [base[0] + dx * 0.4, base[1] + dy * 0.4, base[2]];
163            let yaw = self.rng.rand_float_tol() * 180.0;
164            let Some(a) = self.insert_animal(hk.animal, variant, position, yaw, male) else {
165                return;
166            };
167            male = !male;
168            let life = self.wildlife.animal_kinds[&hk.animal].desc.life;
169            let age = self.rng.rand_float() * life;
170            if let Some(animal) = self.wildlife.animals.get_mut(&a) {
171                animal.age = age;
172            }
173            self.rescale(a);
174            self.join(a, h);
175            self.register_animal(a);
176        }
177        let rest = self.rng.rand_float() * (hk.desc.rest_range + hk.desc.rest) * PERIOD;
178        let herd = &mut self.wildlife.herds[h];
179        herd.rest = ticks(rest);
180        herd.moving = false;
181    }
182
183    /// `FUN_140126920`: animals join at the target until the herd has `target`.
184    pub(super) fn regrow_herd(&mut self, h: usize, target: i32) {
185        let template = self.wildlife.herds[h].template;
186        let hk = self.wildlife.herd_kinds[&template].clone();
187        // The first animal's sex; the rest alternate (`sete` after each, `0x140126cb0`).
188        let mut male = self.rng.rand_below(2) == 0;
189        while (self.wildlife.herds[h].animals.len() as i32) < target {
190            // The entity is made first (`FUN_1400c8bf0`), so its variant's draw comes before the
191            // offsets and the heading.
192            let Some(variant) = self.pick_variant(hk.animal) else {
193                return;
194            };
195            let area = hk.desc.area as f32;
196            let base = self.ground(self.wildlife.herds[h].target);
197            let dy = self.rng.rand_float_tol();
198            let dx = self.rng.rand_float_tol();
199            let position = [base[0] + dx * area, base[1] + dy * area, base[2]];
200            let yaw = self.rng.rand_float_tol() * 180.0;
201            let Some(a) = self.insert_animal(hk.animal, variant, position, yaw, male) else {
202                return;
203            };
204            male = !male;
205            self.join(a, h);
206            self.register_animal(a);
207        }
208    }
209
210    /// `FUN_1401270c0`.
211    pub(super) fn update_herd(&mut self, h: usize, dt: i64) {
212        let template = self.wildlife.herds[h].template;
213        let hd = self.wildlife.herd_kinds[&template].desc.clone();
214        let p = self.wildlife.herds[h].population;
215        let pt = self.wildlife.populations[p].template;
216        let pd = self.wildlife.population_kinds[&pt].desc.clone();
217        let n = self.n();
218        let herd = &mut self.wildlife.herds[h];
219        herd.regrow += dt;
220        let period = ticks(hd.regrowth * PERIOD);
221        if period < herd.regrow {
222            herd.regrow -= period;
223            let share = self.wildlife.populations[p].habitable_share(herd.index);
224            let f = if share < 0.5 { share * 2.0 } else { 1.0 };
225            let count = self.wildlife.herds[h].animals.len() as i32;
226            let mut target = if count * 2 == 0 { 2 } else { count * 2 };
227            let by_share = (hd.max as f32 * f + 0.5) as i32;
228            if by_share < target {
229                target = by_share;
230            }
231            self.regrow_herd(h, target);
232        }
233        let herd = &self.wildlife.herds[h];
234        let habitable = self.wildlife.populations[p].capacity_at(&pd, n, herd.target) != 0;
235        if !herd.moving {
236            let rest = herd.rest - dt;
237            self.wildlife.herds[h].rest = rest;
238            if 0 < rest && habitable {
239                return;
240            }
241            self.retarget(h);
242            let herd = &mut self.wildlife.herds[h];
243            herd.rest = 0;
244            herd.moving = true;
245        } else {
246            if self.all_home(h) {
247                let rest = (self.rng.rand_float() * hd.rest_range + hd.rest) * PERIOD;
248                let herd = &mut self.wildlife.herds[h];
249                herd.moving = false;
250                herd.rest = ticks(rest);
251                return;
252            }
253            if !habitable {
254                self.retarget(h);
255            }
256        }
257    }
258
259    /// `FUN_140126e50`: every animal stands in its area (`FUN_14010bfe0`).
260    pub(super) fn all_home(&self, h: usize) -> bool {
261        self.wildlife.herds[h].animals.iter().all(|a| {
262            self.wildlife.animals.get(a).is_some_and(|animal| {
263                inside(
264                    &animal.area,
265                    self.cell_of(animal.character.position),
266                    self.n(),
267                )
268            })
269        })
270    }
271
272    /// `FUN_1401339e0`: the animal joins the herd and keeps to its area.
273    pub(super) fn join(&mut self, a: usize, h: usize) {
274        let area = self.herd_area(h);
275        self.wildlife.herds[h].animals.push(a);
276        if let Some(animal) = self.wildlife.animals.get_mut(&a) {
277            animal.herd = Some(h);
278            animal.area = area;
279        }
280    }
281}