diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c5fea0539..5b9dac9ec 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1996,6 +1996,7 @@ impl Game<'_> { self.with_player_actor(|game| game.break_block_as_player(pos)) } fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { + self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); let facts = self.res.facts.get(state).clone(); @@ -2652,6 +2653,7 @@ impl Game<'_> { } self.previous_position = feet; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.apply_equipment(); self.eye = 1.62; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index fa60228de..e6be63093 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -485,6 +485,7 @@ impl Game<'_> { player.fall_distance = 0.0; self.previous_position = player.position; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.apply_equipment(); let pitch = self.world.random.next_float() * 0.4 + 0.8; diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 9aaafd045..1332ad51d 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -335,6 +335,15 @@ impl Game<'_> { interaction: BlockInteraction, fire: bool, ) -> Result<()> { + if let Some(p) = &self.player { + let d = [ + p.position.x - center[0], + p.position.y - center[1], + p.position.z - center[2], + ]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius }); + } let mut targets = self.exploded_positions(center, radius); // Explosion.explode: the blast is heard. let ctx = horizon_client::sculk::Context::default(); diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index a6296d09b..829f1e6ab 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -361,6 +361,7 @@ impl Game<'_> { player.velocity = rotate_y(player.velocity, -rotation); self.previous_position = player.position; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.apply_equipment(); let pitch = self.world.random.next_float() * 0.4 + 0.8; diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index 1251eab25..2f050fdec 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -6,12 +6,12 @@ use super::{Game, Screen}; use horizon_client::{ Result, - gamepad::{self, Button, Edges, GlyphStyle, PadState}, + gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble}, keybinds::{KeyBinds, key_code, mouse_button}, mouse::Rotation, }; use serde_json::{Value, json}; -use std::time::Instant; +use std::time::{Duration, Instant}; use winit::{event_loop::ActiveEventLoop, keyboard::KeyCode}; pub(super) const HELP: &[&str] = &[ @@ -48,6 +48,12 @@ pub(super) struct Pads { pub(super) style: GlyphStyle, /// The cursor the pad drives in menus. pub(super) menu: super::pad_menu::MenuCursor, + /// Vibrations playing (an effect stops when dropped) and when they end. + rumbles: Vec<(gilrs::ff::Effect, Instant)>, + /// The last vibration asked for, for `pad status`. + last_rumble: Option<(&'static str, gamepad::Pulse)>, + /// The player's health between polls (a drop is damage taken). + health: HealthWatch, } fn gilrs_button(button: Button) -> gilrs::Button { @@ -73,6 +79,11 @@ fn gilrs_button(button: Button) -> gilrs::Button { } impl Pads { + /// A new player entity took over (spawn, respawn, a server joined, a + /// dimension change): its health is not compared with the old one's. + pub(super) fn player_replaced(&mut self) { + self.health.forget(); + } /// Open gilrs on first use. A platform without it (or a Linux without /// udev) leaves controllers off; the game runs as before. fn start(&mut self) { @@ -181,6 +192,18 @@ impl Game<'_> { self.pad.in_use = true; } self.pad.state = state; + // Damage from any source, here or on a server; nothing counts on + // the title screen. + let health = self + .player + .as_ref() + .filter(|_| self.title.is_none()) + .map(|p| p.health.health()); + if let Some(damage) = self.pad.health.observe(health) { + self.pad_rumble(Rumble::Hurt(damage)); + } + let now = Instant::now(); + self.pad.rumbles.retain(|(_, end)| *end > now); let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause; for button in std::mem::take(&mut self.pad.late_releases) { if !ticking || self.pad.pressed_at[button as usize] != Some(self.ticks) { @@ -359,6 +382,57 @@ impl Game<'_> { self.pitch = rotation.x_rot; } + /// Vibrate the active pad, when vibration is on and the pad is the one + /// playing (a pad lying idle while the mouse plays stays still). + /// Platforms without force feedback (gilrs on macOS) skip it. + pub(super) fn pad_rumble(&mut self, rumble: Rumble) { + let settings = &self.settings.controller; + if !settings.enabled || !settings.vibration || !self.pad.in_use { + return; + } + let Some(pulse) = rumble.pulse() else { + return; + }; + self.pad.last_rumble = Some((rumble.name(), pulse)); + let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else { + return; + }; + if !gilrs + .connected_gamepad(id) + .is_some_and(|g| g.is_ff_supported()) + { + return; + } + use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks}; + let length = Ticks::from_ms(pulse.millis); + let motor = |kind| BaseEffect { + kind, + scheduling: Replay { + play_for: length, + ..Default::default() + }, + envelope: Default::default(), + }; + let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + let effect = EffectBuilder::new() + .add_effect(motor(BaseEffectType::Strong { + magnitude: magnitude(pulse.strong), + })) + .add_effect(motor(BaseEffectType::Weak { + magnitude: magnitude(pulse.weak), + })) + .repeat(Repeat::For(length)) + .gamepads(&[id]) + .finish(gilrs); + match effect.and_then(|e| e.play().map(|()| e)) { + Ok(effect) => { + let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50); + self.pad.rumbles.push((effect, end)); + } + Err(e) => log::debug!("Horizon: controller vibration: {e}"), + } + } + /// `horizon-ctl pad ...`. pub(super) fn pad_command(&mut self, words: &[&str]) -> Result { let arg = |i: usize| -> Result<&str> { @@ -400,6 +474,9 @@ impl Game<'_> { "backend": self.pad.gilrs.is_some(), "controllers": pads, "glyphs": self.pad.style.name(), + "last_rumble": self.pad.last_rumble.map(|(why, p)| json!({ + "reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis, + })), "in_use": self.pad.in_use, "held": held, "left": s.left, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 703541c5b..73edbaca6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1571,6 +1571,7 @@ impl Game<'_> { let mut player = PlayerMotion::new(self.motion, position)?; player.velocity = delta; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.eye = 1.62; self.previous_eye = 1.62; diff --git a/crates/horizon-client/src/game/totem.rs b/crates/horizon-client/src/game/totem.rs index 257c65db2..805360c8d 100644 --- a/crates/horizon-client/src/game/totem.rs +++ b/crates/horizon-client/src/game/totem.rs @@ -71,5 +71,6 @@ impl Game<'_> { height, 30, ); + self.pad_rumble(horizon_client::gamepad::Rumble::Totem); } } diff --git a/crates/horizon-client/src/gamepad.rs b/crates/horizon-client/src/gamepad.rs index 5dcab6f5a..6ec425c82 100644 --- a/crates/horizon-client/src/gamepad.rs +++ b/crates/horizon-client/src/gamepad.rs @@ -589,6 +589,92 @@ pub fn nearest(at: (f32, f32), targets: &[(f32, f32)], radius: f32) -> Option, +} +impl HealthWatch { + /// The health now (`None` without a player); returns the damage taken + /// since the last call. + pub fn observe(&mut self, health: Option) -> Option { + let before = std::mem::replace(&mut self.last, health); + match (before, health) { + (Some(before), Some(now)) if now < before => Some(before - now), + _ => None, + } + } + pub fn forget(&mut self) { + self.last = None; + } +} + +/// What makes the pad vibrate (Bedrock-like: short, light pulses). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Rumble { + /// The player lost this much health. + Hurt(f32), + BlockBroken, + /// An explosion this far away (blocks) with this power. + Explosion { + distance: f64, + radius: f32, + }, + Totem, +} +/// A vibration: the heavy (low-frequency) and light motors, 0..1, and how +/// long it lasts. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pulse { + pub strong: f32, + pub weak: f32, + pub millis: u32, +} +impl Rumble { + pub fn name(self) -> &'static str { + match self { + Rumble::Hurt(_) => "hurt", + Rumble::BlockBroken => "block", + Rumble::Explosion { .. } => "explosion", + Rumble::Totem => "totem", + } + } + /// The pulse, or `None` when it is too faint to feel. + pub fn pulse(self) -> Option { + match self { + Rumble::Hurt(amount) if amount > 0.0 => Some(Pulse { + strong: (0.2 + 0.06 * amount).min(0.8), + weak: 0.3, + millis: (150.0 + 20.0 * amount).min(400.0) as u32, + }), + Rumble::Hurt(_) => None, + Rumble::BlockBroken => Some(Pulse { + strong: 0.0, + weak: 0.25, + millis: 60, + }), + Rumble::Explosion { distance, radius } => { + // Felt up to four times the blast radius, fading with distance. + let reach = f64::from(radius.max(1.0)) * 4.0; + let near = (1.0 - distance / reach) as f32; + (near > 0.05).then_some(Pulse { + strong: 0.9 * near, + weak: 0.6 * near, + millis: 350, + }) + } + Rumble::Totem => Some(Pulse { + strong: 0.7, + weak: 0.7, + millis: 500, + }), + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -758,6 +844,52 @@ mod tests { assert_eq!(action_caption("key.jump"), "key.jump"); } + #[test] + fn health_watch_only_counts_damage_in_one_life() { + let mut w = HealthWatch::default(); + assert_eq!(w.observe(Some(20.0)), None); + assert_eq!(w.observe(Some(15.0)), Some(5.0)); + assert_eq!(w.observe(Some(18.0)), None, "healing"); + // A new player entity (world, respawn, server, dimension). + w.forget(); + assert_eq!(w.observe(Some(6.0)), None); + // No player in between (title, loading) forgets too. + assert_eq!(w.observe(None), None); + assert_eq!(w.observe(Some(2.0)), None); + assert_eq!(w.observe(Some(1.0)), Some(1.0)); + } + + #[test] + fn rumble_pulses() { + let small = Rumble::Hurt(1.0).pulse().unwrap(); + let big = Rumble::Hurt(10.0).pulse().unwrap(); + assert!(big.strong > small.strong && big.millis > small.millis); + assert!(Rumble::Hurt(100.0).pulse().unwrap().strong <= 0.8); + assert_eq!(Rumble::Hurt(0.0).pulse(), None); + let near = Rumble::Explosion { + distance: 2.0, + radius: 4.0, + } + .pulse() + .unwrap(); + let far = Rumble::Explosion { + distance: 12.0, + radius: 4.0, + } + .pulse() + .unwrap(); + assert!(near.strong > far.strong); + assert_eq!( + Rumble::Explosion { + distance: 20.0, + radius: 4.0 + } + .pulse(), + None + ); + assert_eq!(Rumble::BlockBroken.pulse().unwrap().strong, 0.0); + } + #[test] fn hotbar_wraps_and_glyphs_follow_the_vendor() { assert_eq!(hotbar_step(8, true), 0);