Skip to main content

ob_game/
player.rs

1//! Player movement and state.
2
3use crate::world::World;
4use ob_engine::collide::{self, CircleObstacle, Hit, Mover};
5use ob_engine::geom::ang_to_rad;
6
7/// One frame of player input.
8#[derive(Debug, Clone, Copy, Default)]
9pub struct Input {
10    /// -1..1 forward/back.
11    pub forward: f64,
12    /// -1..1 strafe right/left.
13    pub strafe: f64,
14    /// Turn delta in Build angle units.
15    pub turn: f64,
16    /// Look delta (200-line units, positive = look up).
17    pub look: f64,
18    pub run: bool,
19    pub jump: bool,
20    pub crouch: bool,
21    pub use_key: bool,
22    pub fire: bool,
23    pub alt_fire: bool,
24    pub weapon: Option<u8>,
25    pub center_view: bool,
26    pub inv_prev: bool,
27    pub inv_next: bool,
28    pub inv_use: bool,
29}
30
31/// Eye height above the feet. Fitted against screenshots of the original's opening views
32/// on six maps (with the renderer's vertical scale 1.0).
33fn no_ceiling() -> f64 {
34    f64::MIN / 4.0
35}
36
37pub const EYE_STAND: f64 = 0x3800 as f64;
38pub const EYE_CROUCH: f64 = 0x1400 as f64;
39pub const HEIGHT_STAND: f64 = 0x3400 as f64;
40pub const HEIGHT_CROUCH: f64 = 0x1c00 as f64;
41pub const RADIUS: f64 = 64.0;
42pub const STEP: f64 = 0x1a00 as f64;
43/// z units / s^2. With [`JUMP_VEL`] a jump lasts 0.8 s and peaks 16000 units up, as measured
44/// in the original (DOSBox video, E1M1 coffin).
45pub const GRAVITY: f64 = 200_000.0;
46pub const JUMP_VEL: f64 = 80_000.0;
47/// Fall speed scaled to what it would be under the old 0x10000 gravity, so fall damage
48/// keeps depending on the same fall heights.
49pub fn legacy_fall_speed(v: f64) -> f64 {
50    v * (0x10000 as f64 / GRAVITY).sqrt()
51}
52/// Top speeds and responsiveness measured from the original (DOSBox video, E1M1 start).
53pub const WALK_SPEED: f64 = 4600.0;
54pub const RUN_SPEED: f64 = 5600.0;
55pub const SWIM_SPEED: f64 = 2400.0;
56
57#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
58pub struct Player {
59    pub x: f64,
60    pub y: f64,
61    /// Feet z.
62    pub z: f64,
63    pub vx: f64,
64    pub vy: f64,
65    pub vz: f64,
66    pub ang: f64,
67    /// Look offset in 200-line units (positive = up).
68    pub horiz: f64,
69    pub sector: i32,
70    pub on_ground: bool,
71    pub crouching: bool,
72    pub eye: f64,
73    pub health: i32,
74    pub armor: [i32; 3],
75    pub dead: bool,
76    pub bob_phase: f64,
77    pub bob_amp: f64,
78    pub underwater: bool,
79    pub keys: [bool; 8],
80    pub use_was_down: bool,
81    pub jump_was_down: bool,
82    pub last_hit: Hit,
83    pub sprite: i32,
84    pub fall_speed_peak: f64,
85    /// Ceiling height above the player at the last update (keeps the eye, which is higher
86    /// than the collision height, below low ceilings). Not saved; refreshed every tick.
87    #[serde(skip, default = "no_ceiling")]
88    pub ceil_z: f64,
89    /// Jump strength multiplier (jumping boots).
90    pub jump_scale: f64,
91}
92
93impl Player {
94    pub fn spawn(world: &World) -> Player {
95        let (x, y, z, ang, sect) = match world.player_start(0) {
96            Some(s) => (s.x as f64, s.y as f64, s.z as f64, s.ang as f64, s.sectnum as i32),
97            None => (0.0, 0.0, 0.0, 0.0, 0),
98        };
99        let mut p = Player {
100            x,
101            y,
102            z,
103            vx: 0.0,
104            vy: 0.0,
105            vz: 0.0,
106            ang: ang.rem_euclid(2048.0),
107            horiz: 0.0,
108            sector: sect,
109            on_ground: true,
110            crouching: false,
111            eye: EYE_STAND,
112            health: 100,
113            armor: [0; 3],
114            dead: false,
115            bob_phase: 0.0,
116            bob_amp: 0.0,
117            underwater: false,
118            keys: [false; 8],
119            use_was_down: false,
120            jump_was_down: false,
121            last_hit: Hit::None,
122            sprite: -1,
123            fall_speed_peak: 0.0,
124            ceil_z: no_ceiling(),
125            jump_scale: 1.0,
126        };
127        if sect >= 0 {
128            let (_, f) = world.zs_at(sect as usize, x, y);
129            p.z = f;
130        }
131        p
132    }
133
134    pub fn height(&self) -> f64 {
135        if self.crouching {
136            HEIGHT_CROUCH
137        } else {
138            HEIGHT_STAND
139        }
140    }
141
142    pub fn mover(&self) -> Mover {
143        Mover {
144            radius: RADIUS,
145            height: self.height(),
146            // Full step height in the air too, so a jump can mantle onto a ledge (climbing
147            // out of the E1M1 coffin works this way in the original).
148            step: STEP,
149        }
150    }
151
152    /// Camera z (eye position) including view bob.
153    pub fn view_z(&self) -> f64 {
154        let bob = (self.bob_phase).sin() * self.bob_amp;
155        // Under a ceiling lower than the eye, stay just below it (and above the feet).
156        (self.z - self.eye + bob)
157            .max(self.ceil_z + 0x400 as f64)
158            .min(self.z - 0x400 as f64)
159    }
160
161    /// Advances movement by `dt` seconds.
162    pub fn update(&mut self, world: &World, input: &Input, obstacles: &[CircleObstacle], dt: f64) {
163        if self.dead {
164            self.eye = (self.eye - 0x4000 as f64 * dt).max(0x400 as f64);
165            self.apply_gravity(world, dt);
166            return;
167        }
168        self.ang = (self.ang + input.turn).rem_euclid(2048.0);
169        self.horiz = (self.horiz + input.look).clamp(-100.0, 100.0);
170        if input.center_view {
171            self.horiz = 0.0;
172        }
173
174        self.crouching = input.crouch;
175        let target_eye = if self.crouching { EYE_CROUCH } else { EYE_STAND };
176        self.eye += (target_eye - self.eye) * (dt * 12.0).min(1.0);
177
178        // Desired horizontal velocity.
179        let a = ang_to_rad(self.ang);
180        let (c, s) = (a.cos(), a.sin());
181        let speed = if self.underwater {
182            SWIM_SPEED
183        } else if input.run {
184            RUN_SPEED
185        } else {
186            WALK_SPEED
187        } * if self.crouching { 0.5 } else { 1.0 };
188        let fwd = input.forward.clamp(-1.0, 1.0);
189        let strafe = input.strafe.clamp(-1.0, 1.0);
190        let wx = (c * fwd - s * strafe) * speed;
191        let wy = (s * fwd + c * strafe) * speed;
192        // Ground control vs air control.
193        let accel = if self.on_ground || self.underwater { 20.0 } else { 3.0 };
194        let k = (accel * dt).min(1.0);
195        self.vx += (wx - self.vx) * k;
196        self.vy += (wy - self.vy) * k;
197
198        // Jump / swim up.
199        if self.underwater {
200            if input.jump {
201                self.vz = -0x3000 as f64;
202            } else if input.crouch {
203                self.vz = 0x3000 as f64;
204            } else {
205                self.vz *= 1.0 - (dt * 3.0).min(1.0);
206            }
207        } else if input.jump && !self.jump_was_down && self.on_ground {
208            self.vz = -JUMP_VEL * self.jump_scale;
209            self.on_ground = false;
210        }
211        self.jump_was_down = input.jump;
212
213        // Horizontal move with collision.
214        let m = self.mover();
215        let (nx, ny, ns, hit) = collide::clip_move(
216            &world.sectors,
217            &world.walls,
218            obstacles,
219            self.x,
220            self.y,
221            self.z,
222            self.sector,
223            self.vx * dt,
224            self.vy * dt,
225            &m,
226        );
227        if ns >= 0 {
228            // Kill velocity into walls to avoid jitter.
229            let mdx = nx - self.x;
230            let mdy = ny - self.y;
231            if dt > 0.0 && hit != Hit::None {
232                self.vx = mdx / dt;
233                self.vy = mdy / dt;
234            }
235            self.x = nx;
236            self.y = ny;
237            self.sector = ns;
238        }
239        self.last_hit = hit;
240
241        let moving = (self.vx * self.vx + self.vy * self.vy).sqrt();
242        if self.on_ground && moving > 50.0 {
243            self.bob_phase += dt * moving / 450.0;
244            self.bob_amp = (moving / RUN_SPEED * 384.0).min(384.0);
245        } else {
246            self.bob_amp *= 1.0 - (dt * 8.0).min(1.0);
247        }
248
249        self.apply_gravity(world, dt);
250    }
251
252    fn apply_gravity(&mut self, world: &World, dt: f64) {
253        if self.sector < 0 {
254            return;
255        }
256        let (mut cz, cs, mut fz, fs) = collide::get_z_range(
257            &world.sectors,
258            &world.walls,
259            self.x,
260            self.y,
261            self.z,
262            self.sector,
263            RADIUS,
264            STEP,
265        );
266        // Floors/ceilings linked to another room are passable.
267        if fs >= 0 && world.links.get(fs as usize).is_some_and(|l| l.floor.is_some()) {
268            fz = f64::MAX / 4.0;
269        }
270        if cs >= 0 && world.links.get(cs as usize).is_some_and(|l| l.ceil.is_some()) {
271            cz = f64::MIN / 4.0;
272        }
273        if !self.underwater {
274            self.vz += GRAVITY * dt;
275        }
276        self.z += self.vz * dt;
277        if self.z >= fz {
278            if self.vz > self.fall_speed_peak {
279                self.fall_speed_peak = self.vz;
280            }
281            // Smooth step-up instead of snapping.
282            if self.on_ground && fz < self.z - 1.0 {
283                self.z += (fz - self.z) * (dt * 20.0).min(1.0);
284            } else {
285                self.z = fz;
286            }
287            if self.vz > 0.0 {
288                self.vz = 0.0;
289            }
290            self.on_ground = true;
291        } else {
292            self.on_ground = self.z >= fz - 16.0;
293        }
294        self.ceil_z = cz;
295        let head = self.z - self.height();
296        if head < cz {
297            self.z = (cz + self.height()).min(fz);
298            if self.vz < 0.0 {
299                self.vz = 0.0;
300            }
301        }
302    }
303}