Skip to main content

ob_game/game/
ai.rs

1//! Enemy behaviour: perception (sight, hearing, editor flags), movement (chase, flee,
2//! strafe, obstacle and ledge avoidance) and special states (rising zombies, stone
3//! gargoyles, burning dudes). OpenBlood's own design, tuned to feel like the original.
4
5use super::{Ai, Game, TICK_RATE};
6use crate::dudes::{dude_info, is_dude, Attack, DudeInfo};
7use crate::resources::Resources;
8use crate::world::stat;
9use ob_engine::collide;
10
11/// Zombies that start buried or lying down and rise when the player comes close.
12pub fn starts_buried(t: i16) -> bool {
13    matches!(t, 205 | 244)
14}
15
16/// Stone/flesh statues that stay inert until shot or triggered.
17pub fn is_statue(t: i16) -> bool {
18    matches!(t, 208 | 209)
19}
20
21/// Idle dudes only wander while the player is beyond their sight range.
22const WANDER_DISTANCE: f64 = 12000.0;
23
24/// Distance at which ranged attackers stop advancing and start strafing.
25const KEEP_DISTANCE: f64 = 2600.0;
26
27impl Game {
28    /// Initial AI state for a dude placed in the map.
29    pub(super) fn initial_ai(&self, i: usize) -> Ai {
30        let t = self.world.sprites[i].lotag;
31        if starts_buried(t) || is_statue(t) {
32            Ai::Dormant
33        } else {
34            Ai::Idle
35        }
36    }
37
38    /// True when the dude was placed as an ambusher or guard and has not been provoked.
39    fn holds_position(&self, i: usize) -> bool {
40        !self.provoked[i] && self.world.xsprite(i).is_some_and(|x| x.dude_ambush || x.dude_guard)
41    }
42
43    pub(super) fn tick_dudes(&mut self, res: &Resources, dt: f64) {
44        let (px, py) = (self.player.x, self.player.y);
45        for i in 0..self.world.sprites.len() {
46            let s = self.world.sprites[i].clone();
47            if s.statnum == stat::FREE || !is_dude(s.lotag) {
48                continue;
49            }
50            let Some(info) = dude_info(s.lotag) else { continue };
51            let ai = self.ai[i];
52            if matches!(ai, Ai::Dead | Ai::Dying) {
53                self.dude_gravity(i, &info, dt);
54                continue;
55            }
56            self.attack_cd[i] = (self.attack_cd[i] - dt).max(0.0);
57            if self.tick_burning(res, i, &info, dt) {
58                continue;
59            }
60            let dist = (px - s.x as f64).hypot(py - s.y as f64);
61            match ai {
62                Ai::Dormant => {
63                    if starts_buried(s.lotag)
64                        && !self.player.dead
65                        && dist < 1400.0
66                        && (self.clock as usize + i).is_multiple_of(10)
67                        && self.can_see_player(i)
68                    {
69                        self.rise(res, i);
70                    }
71                }
72                Ai::Rise | Ai::Attack | Ai::Recoil => self.dude_gravity(i, &info, dt),
73                Ai::Idle => {
74                    self.idle_wander(res, i, &info, dist, dt);
75                    if self.player.dead || dist > 12000.0 || !(self.clock as usize + i).is_multiple_of(15) {
76                        continue;
77                    }
78                    let to = (py - s.y as f64).atan2(px - s.x as f64).to_degrees() / 360.0 * 2048.0;
79                    let rel = (to - s.ang as f64 + 1024.0).rem_euclid(2048.0) - 1024.0;
80                    if (rel.abs() < 400.0 || dist < 1500.0) && self.can_see_player(i) {
81                        self.wake(res, i, &info);
82                    }
83                }
84                Ai::Flee => {
85                    self.flee_step(i, &info, dt);
86                    self.dude_gravity(i, &info, dt);
87                }
88                Ai::Chase => {
89                    if self.player.dead {
90                        self.ai[i] = Ai::Idle;
91                        self.play_dude_anim(res, i, "I1");
92                        continue;
93                    }
94                    self.chase_step(res, i, &info, dist, dt);
95                }
96                Ai::Dying | Ai::Dead => {}
97            }
98        }
99    }
100
101    fn chase_step(&mut self, res: &Resources, i: usize, info: &DudeInfo, dist: f64, dt: f64) {
102        let (px, py) = (self.player.x, self.player.y);
103        let s = &self.world.sprites[i];
104        let to = (py - s.y as f64).atan2(px - s.x as f64);
105        self.world.sprites[i].ang = ((to.to_degrees() / 360.0 * 2048.0).rem_euclid(2048.0)) as i16;
106        let in_range = match info.attack {
107            Attack::Melee { range, .. } => dist < range + info.radius + crate::player::RADIUS,
108            Attack::Hitscan { range, .. } | Attack::Projectile { range, .. } => dist < range,
109            Attack::None => false,
110        };
111        // Sight is re-checked every few ticks and cached in `sees`.
112        if (self.clock as usize + i).is_multiple_of(6) {
113            self.sees[i] = self.can_see_player(i);
114        }
115        let sees = self.sees[i];
116        if in_range && sees && self.attack_cd[i] <= 0.0 && info.attack != Attack::None {
117            self.ai[i] = Ai::Attack;
118            self.attack_cd[i] = info.cooldown * (0.8 + 0.4 * (self.rand() % 100) as f64 / 100.0);
119            if !self.play_dude_anim(res, i, "A1") {
120                self.dude_attack(res, i);
121                self.ai[i] = Ai::Chase;
122            }
123            return;
124        }
125        if info.speed > 0.0 && !self.holds_position(i) {
126            let ranged = matches!(info.attack, Attack::Hitscan { .. } | Attack::Projectile { .. });
127            let (ang, speed) = if ranged && sees && dist < KEEP_DISTANCE {
128                // Strafe around the player instead of walking into the line of fire.
129                self.world.rt[i].ai_timer -= 1;
130                if self.world.rt[i].ai_timer <= 0 {
131                    self.world.rt[i].ai_timer = (TICK_RATE * (0.8 + (self.rand() % 70) as f64 / 100.0)) as i32;
132                    self.world.rt[i].ai_state = if self.rand().is_multiple_of(2) { 1 } else { -1 };
133                }
134                let side = self.world.rt[i].ai_state.signum().max(-1) as f64;
135                let side = if side == 0.0 { 1.0 } else { side };
136                (to + side * std::f64::consts::FRAC_PI_2, info.speed * 0.6)
137            } else {
138                (to, info.speed)
139            };
140            let close =
141                matches!(info.attack, Attack::Melee { .. }) && dist < info.radius + crate::player::RADIUS + 16.0;
142            if !close {
143                self.dude_walk(i, info, ang, speed * dt);
144            }
145        }
146        if info.flying {
147            let target = self.player.z - 0x2000 as f64;
148            let s = &mut self.world.sprites[i];
149            let dz = (target - s.z as f64).clamp(-0x6000 as f64 * dt, 0x6000 as f64 * dt);
150            s.z += dz as i32;
151        }
152        self.dude_gravity(i, info, dt);
153    }
154
155    /// Moves a dude `dist` units toward `ang`, sliding around obstacles and refusing to
156    /// step off high ledges. Returns true if it moved.
157    ///
158    /// Moves that keep (almost) full speed win over grinding along an obstacle: the first
159    /// pass accepts only those, trying straight ahead, then wider detours in a fixed order;
160    /// the second pass falls back to any move that gets somewhere. That way a dude rounds an
161    /// obstacle briskly, like the E4M9 axe zombies around the central planter in the original.
162    fn dude_walk(&mut self, i: usize, info: &DudeInfo, ang: f64, dist: f64) -> bool {
163        let m = Self::dude_mover(info);
164        for min_part in [0.9, 0.3] {
165            for k in [0.0, 0.7, -0.7, 1.4, -1.4] {
166                let a = ang + k;
167                let s = &self.world.sprites[i];
168                let (x, y, z) = (s.x as f64, s.y as f64, s.z as f64);
169                let (nx, ny, ns, _) = collide::clip_move(
170                    &self.world.sectors,
171                    &self.world.walls,
172                    &[],
173                    x,
174                    y,
175                    z,
176                    s.sectnum as i32,
177                    a.cos() * dist,
178                    a.sin() * dist,
179                    &m,
180                );
181                if ns < 0 {
182                    continue;
183                }
184                let moved = (nx - x).hypot(ny - y);
185                if moved < dist * min_part {
186                    continue;
187                }
188                if !info.flying {
189                    let (_, f) = self.world.zs_at(ns as usize, nx, ny);
190                    if f - z > 0x3000 as f64 {
191                        continue; // don't walk off cliffs
192                    }
193                }
194                if self.crowded(i, info, x, y, nx, ny) {
195                    continue;
196                }
197                let s = &mut self.world.sprites[i];
198                s.x = nx.round() as i32;
199                s.y = ny.round() as i32;
200                s.sectnum = ns as i16;
201                if k != 0.0 {
202                    s.ang = ((a.to_degrees() / 360.0 * 2048.0).rem_euclid(2048.0)) as i16;
203                }
204                return true;
205            }
206        }
207        false
208    }
209    /// True when moving dude `i` from (x, y) to (nx, ny) pushes it further into another
210    /// live dude or the player (dudes don't walk through each other).
211    fn crowded(&self, i: usize, info: &DudeInfo, x: f64, y: f64, nx: f64, ny: f64) -> bool {
212        let into = |ox: f64, oy: f64, r: f64| {
213            let d1 = (nx - ox).hypot(ny - oy);
214            d1 < r && d1 < (x - ox).hypot(y - oy)
215        };
216        if !self.player.dead && into(self.player.x, self.player.y, info.radius + crate::player::RADIUS) {
217            return true;
218        }
219        let z = self.world.sprites[i].z;
220        self.world.sprites.iter().enumerate().any(|(j, o)| {
221            j != i
222                && o.statnum != stat::FREE
223                && is_dude(o.lotag)
224                && !matches!(self.ai[j], Ai::Dead | Ai::Dying)
225                && (o.z - z).abs() < 0x3000
226                && dude_info(o.lotag).is_some_and(|oi| into(o.x as f64, o.y as f64, info.radius + oi.radius))
227        })
228    }
229
230    /// Unalerted dudes don't stand frozen: they take a few slow steps around their spawn
231    /// point, pause, and wander again. Ambushers, statues and sleepers stay put.
232    fn idle_wander(&mut self, res: &Resources, i: usize, info: &DudeInfo, dist: f64, dt: f64) {
233        if info.speed <= 0.0 || info.flying || self.holds_position(i) {
234            return;
235        }
236        // Close to the player: stand and face the way the map placed us (sight checks
237        // look along the facing).
238        if dist < WANDER_DISTANCE {
239            if self.world.rt[i].ai_state == 1 {
240                self.world.rt[i].ai_state = 0;
241                self.world.rt[i].ai_timer = 0;
242                self.world.sprites[i].ang = self.world.rt[i].home_ang;
243                self.play_dude_anim(res, i, "I1");
244            }
245            return;
246        }
247        let rt = &mut self.world.rt[i];
248        rt.ai_timer -= 1;
249        if rt.ai_timer <= 0 {
250            if rt.ai_state == 1 {
251                // Pause.
252                self.world.rt[i].ai_state = 0;
253                self.world.rt[i].ai_timer = (TICK_RATE * (1.0 + (self.rand() % 200) as f64 / 100.0)) as i32;
254                self.play_dude_anim(res, i, "I1");
255            } else {
256                // Walk a short way: back toward home when strayed, else somewhere nearby.
257                let s = &self.world.sprites[i];
258                let (hx, hy, _) = self.world.base_sprite_xy.get(i).copied().unwrap_or((s.x, s.y, s.z));
259                let (dx, dy) = ((hx - s.x) as f64, (hy - s.y) as f64);
260                let a = if dx.hypot(dy) > 384.0 {
261                    dy.atan2(dx)
262                } else {
263                    (self.rand() % 360) as f64 / 180.0 * std::f64::consts::PI
264                };
265                self.world.sprites[i].ang = ((a.to_degrees() / 360.0 * 2048.0).rem_euclid(2048.0)) as i16;
266                self.world.rt[i].ai_state = 1;
267                self.world.rt[i].ai_timer = (TICK_RATE * (0.5 + (self.rand() % 70) as f64 / 100.0)) as i32;
268                self.play_dude_anim(res, i, "M1");
269            }
270        }
271        if self.world.rt[i].ai_state == 1 {
272            let a = ob_engine::geom::ang_to_rad(self.world.sprites[i].ang as f64);
273            if !self.dude_walk(i, info, a, info.speed * 0.25 * dt) {
274                self.world.rt[i].ai_timer = 0;
275            }
276        }
277        self.dude_gravity(i, info, dt);
278    }
279
280    /// Running away from the player (innocents, burning dudes).
281    fn flee_step(&mut self, i: usize, info: &DudeInfo, dt: f64) {
282        let s = &self.world.sprites[i];
283        let away = (s.y as f64 - self.player.y).atan2(s.x as f64 - self.player.x);
284        self.world.rt[i].ai_timer -= 1;
285        if self.world.rt[i].ai_timer <= 0 {
286            self.world.rt[i].ai_timer = (TICK_RATE * (0.6 + (self.rand() % 100) as f64 / 100.0)) as i32;
287            self.world.rt[i].ai_state = (self.rand() % 120) as i32 - 60;
288        }
289        let jitter = self.world.rt[i].ai_state as f64 / 60.0 * 0.9;
290        let a = away + jitter;
291        self.world.sprites[i].ang = ((a.to_degrees() / 360.0 * 2048.0).rem_euclid(2048.0)) as i16;
292        let speed = info.speed.max(1500.0) * 1.2;
293        self.dude_walk(i, info, a, speed * dt);
294    }
295
296    /// Burning dudes panic and take damage. Returns true when burning handled the tick.
297    fn tick_burning(&mut self, res: &Resources, i: usize, info: &DudeInfo, dt: f64) -> bool {
298        if self.world.rt[i].burn_time <= 0 {
299            return false;
300        }
301        self.world.rt[i].burn_time -= 1;
302        let p = self.sprite_pos(i);
303        if self.world.rt[i].burn_time % 30 == 0 {
304            let sect = self.world.sprites[i].sectnum as i32;
305            self.spawn_fx(55, p.0, p.1, p.2 - info.height * 0.4, sect);
306            self.burn_kill = true;
307            self.damage_sprite(res, i, 3, false);
308            self.burn_kill = false;
309        }
310        if matches!(self.ai[i], Ai::Dead | Ai::Dying) {
311            self.world.rt[i].burn_time = 0;
312            return true;
313        }
314        if self.world.rt[i].burn_time % 90 == 0 {
315            self.sound_group(info.pain_sound, p);
316        }
317        self.flee_step(i, info, dt);
318        self.dude_gravity(i, info, dt);
319        true
320    }
321
322    fn rise(&mut self, res: &Resources, i: usize) {
323        if self.play_dude_anim(res, i, "UP") {
324            self.ai[i] = Ai::Rise;
325        } else {
326            self.ai[i] = Ai::Chase;
327            self.play_dude_anim(res, i, "M1");
328        }
329        let p = self.sprite_pos(i);
330        self.sound(1100, Some(p));
331    }
332
333    pub(super) fn wake(&mut self, res: &Resources, i: usize, info: &DudeInfo) {
334        match self.ai[i] {
335            Ai::Idle => {}
336            Ai::Dormant => {
337                if starts_buried(self.world.sprites[i].lotag) {
338                    self.rise(res, i);
339                    return;
340                }
341            }
342            _ => return,
343        }
344        let p = self.sprite_pos(i);
345        if info.attack == Attack::None {
346            self.ai[i] = Ai::Flee;
347            self.play_dude_anim(res, i, "M1");
348            self.sound_group(info.spot_sound, p);
349            return;
350        }
351        self.ai[i] = Ai::Chase;
352        self.play_dude_anim(res, i, "M1");
353        self.sound_group(info.spot_sound, p);
354    }
355
356    /// Wakes dudes that can hear the player's weapon (deaf dudes ignore noise).
357    pub(super) fn alert_nearby(&mut self, res: &Resources, radius: f64) {
358        for i in 0..self.world.sprites.len() {
359            let s = &self.world.sprites[i];
360            if s.statnum == stat::FREE || !is_dude(s.lotag) || self.ai[i] != Ai::Idle {
361                continue;
362            }
363            if self.world.xsprite(i).is_some_and(|x| x.dude_deaf) {
364                continue;
365            }
366            let d = (s.x as f64 - self.player.x).hypot(s.y as f64 - self.player.y);
367            if d < radius && (d < radius * 0.4 || self.can_see_player(i)) {
368                if let Some(info) = dude_info(s.lotag) {
369                    self.wake(res, i, &info);
370                }
371            }
372        }
373    }
374
375    /// Called when a dude is hurt: provokes ambushers, wakes statues and sleepers.
376    pub(super) fn provoke(&mut self, res: &Resources, i: usize, info: &DudeInfo) {
377        self.provoked[i] = true;
378        if self.ai[i] == Ai::Dormant && is_statue(self.world.sprites[i].lotag) {
379            self.ai[i] = Ai::Idle;
380        }
381        if matches!(self.ai[i], Ai::Idle | Ai::Dormant) {
382            self.wake(res, i, info);
383        }
384    }
385}