Skip to main content

ob_engine/
collide.rs

1//! Movement and collision against sector geometry (Build `clipmove` / `getzrange`
2//! equivalents, written from scratch).
3//!
4//! The mover is a vertical cylinder: radius `r` (xy units), feet at `z`, extending
5//! `height` z units upward. A portal wall blocks when the step into the next sector is
6//! higher than `step`, when the head would hit its ceiling, or when the wall's blocking
7//! flag is set.
8
9use crate::geom::{inside_sector, zs_of_slope};
10use crate::map::{Sector, Wall};
11
12pub const WALL_BLOCK_FLAG: u16 = 1;
13
14#[derive(Debug, Clone, Copy)]
15pub struct Mover {
16    pub radius: f64,
17    pub height: f64,
18    pub step: f64,
19}
20
21#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq)]
22pub enum Hit {
23    None,
24    Wall(usize),
25    Sprite(usize),
26}
27
28/// Circle obstacle (blocking sprite) for collision.
29#[derive(Debug, Clone, Copy)]
30pub struct CircleObstacle {
31    pub x: f64,
32    pub y: f64,
33    pub radius: f64,
34    pub zbot: f64,
35    pub ztop: f64,
36    pub id: usize,
37}
38
39#[inline]
40fn closest_on_seg(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> (f64, f64) {
41    let dx = bx - ax;
42    let dy = by - ay;
43    let l2 = dx * dx + dy * dy;
44    if l2 < 1e-12 {
45        return (ax, ay);
46    }
47    let t = (((px - ax) * dx + (py - ay) * dy) / l2).clamp(0.0, 1.0);
48    (ax + dx * t, ay + dy * t)
49}
50
51/// Collects sectors reachable through portals whose walls come within `reach` of (x, y).
52pub fn nearby_sectors(sectors: &[Sector], walls: &[Wall], start: i32, x: f64, y: f64, reach: f64) -> Vec<usize> {
53    let mut out = Vec::new();
54    if start < 0 || start as usize >= sectors.len() {
55        return out;
56    }
57    out.push(start as usize);
58    let mut i = 0;
59    while i < out.len() && out.len() < 64 {
60        let s = &sectors[out[i]];
61        for wi in s.wallptr as usize..(s.wallptr + s.wallnum) as usize {
62            let w = &walls[wi];
63            if w.nextsector < 0 {
64                continue;
65            }
66            let w2 = &walls[w.point2 as usize];
67            let (cx, cy) = closest_on_seg(x, y, w.x as f64, w.y as f64, w2.x as f64, w2.y as f64);
68            if (cx - x).hypot(cy - y) <= reach {
69                let ns = w.nextsector as usize;
70                if !out.contains(&ns) {
71                    out.push(ns);
72                }
73            }
74        }
75        i += 1;
76    }
77    out
78}
79
80/// True if wall `wi` (seen from its own sector) blocks a mover with feet at `z`.
81pub fn wall_blocks(sectors: &[Sector], walls: &[Wall], wi: usize, px: f64, py: f64, z: f64, m: &Mover) -> bool {
82    let w = &walls[wi];
83    if w.nextsector < 0 || w.cstat & WALL_BLOCK_FLAG != 0 {
84        return true;
85    }
86    let (c, f) = zs_of_slope(sectors, walls, w.nextsector as usize, px, py);
87    f < z - m.step || c > z - m.height || f - c < m.height * 0.5
88}
89
90/// Moves (x, y) by (dx, dy) with sliding collision. Returns the new position, sector
91/// and the first obstacle touched.
92#[allow(clippy::too_many_arguments)]
93pub fn clip_move(
94    sectors: &[Sector],
95    walls: &[Wall],
96    obstacles: &[CircleObstacle],
97    x: f64,
98    y: f64,
99    z: f64,
100    sect: i32,
101    dx: f64,
102    dy: f64,
103    m: &Mover,
104) -> (f64, f64, i32, Hit) {
105    let mut hit = Hit::None;
106    let dist = dx.hypot(dy);
107    if sect < 0 {
108        return (x + dx, y + dy, sect, hit);
109    }
110    let steps = ((dist / (m.radius * 0.5).max(1.0)).ceil() as usize).clamp(1, 64);
111    let (sx, sy) = (dx / steps as f64, dy / steps as f64);
112    let (mut px, mut py, mut cur) = (x, y, sect);
113    for _ in 0..steps {
114        let (ox, oy) = (px, py);
115        px += sx;
116        py += sy;
117        // Resolve penetration a few times for corners.
118        for _ in 0..4 {
119            let mut moved = false;
120            let near = nearby_sectors(sectors, walls, cur, px, py, m.radius + dist + 16.0);
121            for &s in &near {
122                let sec = &sectors[s];
123                for wi in sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize {
124                    let w = &walls[wi];
125                    let w2 = &walls[w.point2 as usize];
126                    let (ax, ay, bx, by) = (w.x as f64, w.y as f64, w2.x as f64, w2.y as f64);
127                    let (cx, cy) = closest_on_seg(px, py, ax, ay, bx, by);
128                    let d = (px - cx).hypot(py - cy);
129                    if d >= m.radius {
130                        continue;
131                    }
132                    // Only walls facing the mover: use the side we came from.
133                    let side = (bx - ax) * (oy - ay) - (by - ay) * (ox - ax);
134                    // Build walls have their sector interior on the right (side > 0 in our
135                    // y-down coordinates means right of a->b when looking along it).
136                    let from_inside = side >= 0.0;
137                    if !from_inside && w.nextsector >= 0 {
138                        // Seen from the other side: test the reverse wall instead.
139                        continue;
140                    }
141                    if !wall_blocks(sectors, walls, wi, cx, cy, z, m) {
142                        continue;
143                    }
144                    let (nx, ny) = if d > 1e-6 {
145                        ((px - cx) / d, (py - cy) / d)
146                    } else {
147                        let l = (bx - ax).hypot(by - ay).max(1e-9);
148                        (-(by - ay) / l, (bx - ax) / l)
149                    };
150                    let push = m.radius - d + 0.01;
151                    px += nx * push;
152                    py += ny * push;
153                    moved = true;
154                    if hit == Hit::None {
155                        hit = Hit::Wall(wi);
156                    }
157                }
158            }
159            for o in obstacles {
160                if o.zbot < z - m.height || o.ztop > z {
161                    continue;
162                }
163                let d = (px - o.x).hypot(py - o.y);
164                let rr = m.radius + o.radius;
165                if d < rr && d > 1e-6 {
166                    let push = rr - d + 0.01;
167                    px += (px - o.x) / d * push;
168                    py += (py - o.y) / d * push;
169                    moved = true;
170                    if hit == Hit::None {
171                        hit = Hit::Sprite(o.id);
172                    }
173                }
174            }
175            if !moved {
176                break;
177            }
178        }
179        cur = find_sector_near(sectors, walls, px, py, cur);
180        if cur < 0 {
181            // Escaped the map: undo this step.
182            px = ox;
183            py = oy;
184            cur = find_sector_near(sectors, walls, px, py, sect);
185            break;
186        }
187    }
188    (px, py, cur, hit)
189}
190
191/// Sector lookup preferring neighbours of `hint` (breadth-first over a few levels).
192pub fn find_sector_near(sectors: &[Sector], walls: &[Wall], x: f64, y: f64, hint: i32) -> i32 {
193    if hint >= 0 && (hint as usize) < sectors.len() {
194        let mut list = vec![hint as usize];
195        let mut i = 0;
196        while i < list.len() && list.len() < 128 {
197            let s = list[i];
198            if inside_sector(sectors, walls, s, x, y) {
199                return s as i32;
200            }
201            let sec = &sectors[s];
202            for wall in &walls[sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize] {
203                let ns = wall.nextsector;
204                if ns >= 0 && !list.contains(&(ns as usize)) {
205                    list.push(ns as usize);
206                }
207            }
208            i += 1;
209            if i > 24 {
210                break;
211            }
212        }
213    }
214    (0..sectors.len())
215        .find(|&s| inside_sector(sectors, walls, s, x, y))
216        .map_or(-1, |s| s as i32)
217}
218
219/// Highest floor and lowest ceiling under a cylinder of `radius` at (x, y).
220/// Returns `(ceil_z, ceil_sector, floor_z, floor_sector)`.
221#[allow(clippy::too_many_arguments)]
222pub fn get_z_range(
223    sectors: &[Sector],
224    walls: &[Wall],
225    x: f64,
226    y: f64,
227    z: f64,
228    sect: i32,
229    radius: f64,
230    step: f64,
231) -> (f64, i32, f64, i32) {
232    if sect < 0 {
233        return (f64::MIN, -1, f64::MAX, -1);
234    }
235    let (mut cz, mut fz) = zs_of_slope(sectors, walls, sect as usize, x, y);
236    let (mut cs, mut fs) = (sect, sect);
237    for s in nearby_sectors(sectors, walls, sect, x, y, radius) {
238        if s as i32 == sect {
239            continue;
240        }
241        let (c, f) = zs_of_slope(sectors, walls, s, x, y);
242        // Floors above the step height act as walls (handled by clip_move), not ground.
243        if f < fz && f >= z - step {
244            fz = f;
245            fs = s as i32;
246        }
247        if c > cz && c <= z {
248            cz = c;
249            cs = s as i32;
250        }
251    }
252    (cz, cs, fz, fs)
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::map::{Sector, Wall};
259
260    /// Two 1024x1024 rooms side by side (x 0..1024 and 1024..2048); the right room's
261    /// floor is `step` units higher.
262    fn rooms(right_floor: i32) -> (Vec<Sector>, Vec<Wall>) {
263        let mut walls = Vec::new();
264        let mk = |x, y, p2, nw, ns| Wall {
265            x,
266            y,
267            point2: p2,
268            nextwall: nw,
269            nextsector: ns,
270            ..Default::default()
271        };
272        // room 0 clockwise in y-down coords: (0,0)->(1024,0)->(1024,1024)->(0,1024)
273        walls.push(mk(0, 0, 1, -1, -1));
274        walls.push(mk(1024, 0, 2, 7, 1));
275        walls.push(mk(1024, 1024, 3, -1, -1));
276        walls.push(mk(0, 1024, 0, -1, -1));
277        // room 1: (1024,0)->(2048,0)->(2048,1024)->(1024,1024)
278        walls.push(mk(1024, 0, 5, -1, -1));
279        walls.push(mk(2048, 0, 6, -1, -1));
280        walls.push(mk(2048, 1024, 7, -1, -1));
281        walls.push(mk(1024, 1024, 4, 1, 0));
282        let mut s0 = Sector {
283            wallptr: 0,
284            wallnum: 4,
285            ..Default::default()
286        };
287        s0.ceiling.z = -32768;
288        s0.floor.z = 0;
289        let mut s1 = Sector {
290            wallptr: 4,
291            wallnum: 4,
292            ..Default::default()
293        };
294        s1.ceiling.z = -32768;
295        s1.floor.z = right_floor;
296        (vec![s0, s1], walls)
297    }
298
299    const M: Mover = Mover {
300        radius: 64.0,
301        height: 8192.0,
302        step: 4096.0,
303    };
304
305    #[test]
306    fn solid_wall_stops() {
307        let (s, w) = rooms(0);
308        let (x, _y, sect, hit) = clip_move(&s, &w, &[], 512.0, 512.0, 0.0, 0, -1000.0, 0.0, &M);
309        assert!(x >= 63.9, "x={x}");
310        assert_eq!(sect, 0);
311        assert!(matches!(hit, Hit::Wall(3)));
312    }
313
314    #[test]
315    fn walk_through_portal() {
316        let (s, w) = rooms(-2048);
317        let (x, _, sect, _) = clip_move(&s, &w, &[], 900.0, 512.0, 0.0, 0, 400.0, 0.0, &M);
318        assert!((x - 1300.0).abs() < 1.0);
319        assert_eq!(sect, 1);
320    }
321
322    #[test]
323    fn high_step_blocks() {
324        let (s, w) = rooms(-8192);
325        let (x, _, sect, _) = clip_move(&s, &w, &[], 900.0, 512.0, 0.0, 0, 400.0, 0.0, &M);
326        assert!(x <= 1024.0 - 63.9, "x={x}");
327        assert_eq!(sect, 0);
328    }
329
330    #[test]
331    fn zrange_sees_step() {
332        let (s, w) = rooms(-2048);
333        let (_, _, fz, fs) = get_z_range(&s, &w, 1000.0, 512.0, 0.0, 0, 64.0, 4096.0);
334        assert_eq!((fz, fs), (-2048.0, 1));
335    }
336}
337
338/// Vertical cylinder that can be hit by traces (dudes, things...).
339#[derive(Debug, Clone, Copy)]
340pub struct HitCylinder {
341    pub id: usize,
342    pub x: f64,
343    pub y: f64,
344    pub radius: f64,
345    pub ztop: f64,
346    pub zbot: f64,
347}
348
349#[derive(Debug, Clone, Copy, PartialEq)]
350pub enum TraceTarget {
351    Nothing,
352    Wall(usize),
353    Floor(usize),
354    Ceiling(usize),
355    Sprite(usize),
356}
357
358#[derive(Debug, Clone, Copy)]
359pub struct TraceHit {
360    pub x: f64,
361    pub y: f64,
362    pub z: f64,
363    pub sector: i32,
364    pub dist: f64,
365    pub target: TraceTarget,
366}
367
368/// 3D hitscan. Direction: unit xy vector `(dx, dy)` and `dz` z units per xy unit.
369#[allow(clippy::too_many_arguments)]
370pub fn hitscan(
371    sectors: &[Sector],
372    walls: &[Wall],
373    cylinders: &[HitCylinder],
374    ox: f64,
375    oy: f64,
376    oz: f64,
377    sect: i32,
378    dx: f64,
379    dy: f64,
380    dz: f64,
381    max_dist: f64,
382) -> TraceHit {
383    use crate::geom::{plane_eq, ray_segment};
384    let mut s = sect;
385    let mut t_in = 0.0f64;
386    let mut result = TraceHit {
387        x: ox + dx * max_dist,
388        y: oy + dy * max_dist,
389        z: oz + dz * max_dist,
390        sector: sect,
391        dist: max_dist,
392        target: TraceTarget::Nothing,
393    };
394    'walk: for _ in 0..256 {
395        if s < 0 || s as usize >= sectors.len() {
396            break;
397        }
398        let sec = &sectors[s as usize];
399        let mut best: Option<(f64, usize)> = None;
400        for wi in sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize {
401            let w1 = &walls[wi];
402            let w2 = &walls[w1.point2 as usize];
403            if let Some((t, _)) = ray_segment(ox, oy, dx, dy, w1.x as f64, w1.y as f64, w2.x as f64, w2.y as f64) {
404                if t > t_in + 1e-7 && best.is_none_or(|b| t < b.0) {
405                    best = Some((t, wi));
406                }
407            }
408        }
409        let t_out = best.map_or(max_dist, |b| b.0).min(max_dist);
410        // Plane hits inside this sector.
411        for (is_ceil, plane) in [(true, &sec.ceiling), (false, &sec.floor)] {
412            let eq = plane_eq(sec, walls, plane);
413            let a = eq.z_at(ox, oy);
414            let b = eq.bx * dx + eq.by * dy;
415            let den = dz - b;
416            if den.abs() < 1e-12 {
417                continue;
418            }
419            let t = (a - oz) / den;
420            let toward = if is_ceil { den < 0.0 } else { den > 0.0 };
421            if toward && t >= t_in - 1e-6 && t <= t_out {
422                let t = t.max(t_in);
423                result = TraceHit {
424                    x: ox + dx * t,
425                    y: oy + dy * t,
426                    z: oz + dz * t,
427                    sector: s,
428                    dist: t,
429                    target: if is_ceil {
430                        TraceTarget::Ceiling(s as usize)
431                    } else {
432                        TraceTarget::Floor(s as usize)
433                    },
434                };
435                break 'walk;
436            }
437        }
438        let Some((t, wi)) = best else { break };
439        if t > max_dist {
440            break;
441        }
442        let w = &walls[wi];
443        let z = oz + dz * t;
444        let (hx, hy) = (ox + dx * t, oy + dy * t);
445        let blocked = if w.nextsector < 0 || w.cstat & WALL_BLOCK_FLAG != 0 && w.cstat & 64 != 0 {
446            true
447        } else {
448            let (c, f) = zs_of_slope(sectors, walls, w.nextsector as usize, hx, hy);
449            z < c || z > f
450        };
451        if blocked {
452            result = TraceHit {
453                x: hx,
454                y: hy,
455                z,
456                sector: s,
457                dist: t,
458                target: TraceTarget::Wall(wi),
459            };
460            break;
461        }
462        t_in = t;
463        s = w.nextsector as i32;
464    }
465    // Sprites closer than the geometry hit.
466    for c in cylinders {
467        let fx = c.x - ox;
468        let fy = c.y - oy;
469        let along = fx * dx + fy * dy;
470        if along <= 0.0 || along > result.dist {
471            continue;
472        }
473        let perp2 = fx * fx + fy * fy - along * along;
474        let r2 = c.radius * c.radius;
475        if perp2 > r2 {
476            continue;
477        }
478        let t = along - (r2 - perp2).sqrt();
479        let t = t.max(0.0);
480        let z = oz + dz * t;
481        if z >= c.ztop && z <= c.zbot && t < result.dist {
482            result = TraceHit {
483                x: ox + dx * t,
484                y: oy + dy * t,
485                z,
486                sector: result.sector,
487                dist: t,
488                target: TraceTarget::Sprite(c.id),
489            };
490        }
491    }
492    result
493}
494
495#[cfg(test)]
496mod trace_tests {
497    use super::*;
498    use crate::map::{Sector, Wall};
499
500    fn room() -> (Vec<Sector>, Vec<Wall>) {
501        let pts = [(0, 0), (4096, 0), (4096, 4096), (0, 4096)];
502        let walls: Vec<Wall> = pts
503            .iter()
504            .enumerate()
505            .map(|(i, &(x, y))| Wall {
506                x,
507                y,
508                point2: ((i + 1) % 4) as i16,
509                nextwall: -1,
510                nextsector: -1,
511                ..Default::default()
512            })
513            .collect();
514        let mut s = Sector {
515            wallptr: 0,
516            wallnum: 4,
517            ..Default::default()
518        };
519        s.ceiling.z = -32768;
520        s.floor.z = 0;
521        (vec![s], walls)
522    }
523
524    #[test]
525    fn hits_wall_floor_and_sprite() {
526        let (s, w) = room();
527        let h = hitscan(&s, &w, &[], 1000.0, 2048.0, -8192.0, 0, 1.0, 0.0, 0.0, 1e6);
528        assert_eq!(h.target, TraceTarget::Wall(1));
529        assert!((h.x - 4096.0).abs() < 1e-6);
530        let h = hitscan(&s, &w, &[], 1000.0, 2048.0, -8192.0, 0, 1.0, 0.0, 8.0, 1e6);
531        assert_eq!(h.target, TraceTarget::Floor(0));
532        assert!((h.dist - 1024.0).abs() < 1e-6);
533        let cyl = [HitCylinder {
534            id: 7,
535            x: 2000.0,
536            y: 2048.0,
537            radius: 64.0,
538            ztop: -12000.0,
539            zbot: 0.0,
540        }];
541        let h = hitscan(&s, &w, &cyl, 1000.0, 2048.0, -8192.0, 0, 1.0, 0.0, 0.0, 1e6);
542        assert_eq!(h.target, TraceTarget::Sprite(7));
543        assert!((h.dist - 936.0).abs() < 1e-6);
544    }
545}