Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rumble support to bevy_gilrs #3868

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,10 @@ path = "examples/input/gamepad_input.rs"
name = "gamepad_input_events"
path = "examples/input/gamepad_input_events.rs"

[[example]]
name = "gamepad_rumble"
path = "examples/input/gamepad_rumble.rs"

[[example]]
name = "keyboard_input"
path = "examples/input/keyboard_input.rs"
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_gilrs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ keywords = ["bevy"]
[dependencies]
# bevy
bevy_app = { path = "../bevy_app", version = "0.6.0" }
bevy_core = { path = "../bevy_core", version = "0.6.0" }
bevy_ecs = { path = "../bevy_ecs", version = "0.6.0" }
bevy_input = { path = "../bevy_input", version = "0.6.0" }
bevy_log = { path = "../bevy_log", version = "0.6.0" }
bevy_utils = { path = "../bevy_utils", version = "0.6.0" }

# other
Expand Down
6 changes: 6 additions & 0 deletions crates/bevy_gilrs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
mod converter;
mod gilrs_system;
mod rumble;

use bevy_app::{App, CoreStage, Plugin, StartupStage};
use bevy_ecs::schedule::ParallelSystemDescriptorCoercion;
use bevy_input::InputSystem;
use bevy_utils::tracing::error;
pub use gilrs::ff;
use gilrs::GilrsBuilder;
use gilrs_system::{gilrs_event_startup_system, gilrs_event_system};
pub use rumble::{RumbleIntensity, RumbleRequest};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub use rumble::{RumbleIntensity, RumbleRequest};
pub use rumble::{gilrs_rumble_system, RumbleIntensity, RumblesManager, RumbleRequest};


#[derive(Default)]
pub struct GilrsPlugin;
Expand All @@ -20,10 +23,13 @@ impl Plugin for GilrsPlugin {
{
Ok(gilrs) => {
app.insert_non_send_resource(gilrs)
.add_event::<RumbleRequest>()
.init_non_send_resource::<rumble::RumblesManager>()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.init_non_send_resource::<rumble::RumblesManager>()
.init_non_send_resource::<RumblesManager>()

This should just be imported.

.add_startup_system_to_stage(
StartupStage::PreStartup,
gilrs_event_startup_system,
)
.add_system_to_stage(CoreStage::PostUpdate, rumble::gilrs_rumble_system)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.add_system_to_stage(CoreStage::PostUpdate, rumble::gilrs_rumble_system)
.add_system_to_stage(CoreStage::PostUpdate, gilrs_rumble_system)

.add_system_to_stage(
CoreStage::PreUpdate,
gilrs_event_system.before(InputSystem),
Expand Down
160 changes: 160 additions & 0 deletions crates/bevy_gilrs/src/rumble.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
//! Handle user specified Rumble request events.
use crate::converter::convert_gamepad_id;
use bevy_app::EventReader;
use bevy_core::Time;
use bevy_ecs::{prelude::Res, system::NonSendMut};
use bevy_input::gamepad::Gamepad;
use bevy_log as log;
use bevy_utils::HashMap;
use gilrs::{ff, GamepadId, Gilrs};

pub enum RumbleIntensity {
Strong,
Medium,
Weak,
}
impl RumbleIntensity {
fn effect_type(&self) -> ff::BaseEffectType {
use RumbleIntensity::*;
match self {
Strong => ff::BaseEffectType::Strong { magnitude: 63_000 },
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These values seem super arbitrary and hard-coded.

Medium => ff::BaseEffectType::Strong { magnitude: 40_000 },
Weak => ff::BaseEffectType::Weak { magnitude: 40_000 },
Comment on lines +21 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This magnitudes shouldn't be the same.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the gilrs example They use the same magnitude with a different BaseEffectType (you'll notice here we use Strong for Medium and Weak for Weak) to demonstrate a periodic change in force feedback intensity. Testing it myself with two different controllers, I find all different RumbleIntensity to be distinct enough.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't notice the different Types here. Then everything is fine here

}
}
}

/// Request `pad` rumble in `gilrs_effect` pattern for `duration_seconds`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The phrasing here is a little unclear.

///
/// # Notes
///
/// * Does nothing if `pad` does not support rumble
/// * If a new `RumbleRequest` is sent while another one is still executing, it
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this is always the correct behavior. Could we have an overwriting field perhaps?

/// replaces the old one.
///
/// # Example
///
/// ```
/// # use bevy_gilrs::{RumbleRequest, RumbleIntensity};
/// # use bevy_input::gamepad::Gamepad;
/// # use bevy_app::EventWriter;
/// fn rumble_pad_system(mut rumble_requests: EventWriter<RumbleRequest>) {
/// let request = RumbleRequest::with_intensity(
/// RumbleIntensity::Strong,
/// 10.0,
/// Gamepad(0),
/// );
/// rumble_requests.send(request);
/// }
/// ```
#[derive(Clone)]
pub struct RumbleRequest {
/// The duration in seconds of the rumble
pub duration_seconds: f32,
/// The gilrs descriptor, use [`RumbleRequest::with_intensity`] if you want
/// a simpler API.
pub gilrs_effect: ff::EffectBuilder,
/// The gamepad to rumble
pub pad: Gamepad,
}
impl RumbleRequest {
/// Causes `pad` to rumble for `duration_seconds` at given `intensity`.
pub fn with_intensity(intensity: RumbleIntensity, duration_seconds: f32, pad: Gamepad) -> Self {
let kind = intensity.effect_type();
let effect = ff::BaseEffect {
kind,
..Default::default()
};
let mut gilrs_effect = ff::EffectBuilder::new();
gilrs_effect.add_effect(effect);
RumbleRequest {
duration_seconds,
gilrs_effect,
pad,
}
}
/// Stops provided `pad` rumbling.
pub fn stop(pad: Gamepad) -> Self {
RumbleRequest {
duration_seconds: 0.0,
gilrs_effect: ff::EffectBuilder::new(),
pad,
}
}
}

struct RunningRumble {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs docs; I'm not immediately sure what it does.

deadline: f32,
// We use `effect.drop()` to interact with this, but rustc can't know
// gilrs uses Drop as an API feature.
#[allow(dead_code)]
effect: ff::Effect,
}

enum RumbleError {
GamepadNotFound,
GilrsError(ff::Error),
}
impl From<ff::Error> for RumbleError {
fn from(err: ff::Error) -> Self {
RumbleError::GilrsError(err)
}
}

#[derive(Default)]
pub(crate) struct RumblesManager {
rumbles: HashMap<GamepadId, RunningRumble>,
}

fn add_rumble(
manager: &mut RumblesManager,
gilrs: &mut Gilrs,
mut rumble: RumbleRequest,
current_time: f32,
) -> Result<(), RumbleError> {
let (pad_id, _) = gilrs
.gamepads()
.find(|(pad_id, _)| convert_gamepad_id(*pad_id) == rumble.pad)
.ok_or(RumbleError::GamepadNotFound)?;
let deadline = current_time + rumble.duration_seconds;
let effect = rumble.gilrs_effect.gamepads(&[pad_id]).finish(gilrs)?;
effect.play()?;
manager
.rumbles
.insert(pad_id, RunningRumble { deadline, effect });
Ok(())
}
pub(crate) fn gilrs_rumble_system(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub(crate) fn gilrs_rumble_system(
pub(crate) fn play_gilrs_rumble(

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this should be pub?

time: Res<Time>,
mut gilrs: NonSendMut<Gilrs>,
mut requests: EventReader<RumbleRequest>,
mut manager: NonSendMut<RumblesManager>,
) {
let current_time = time.seconds_since_startup() as f32;
// Remove outdated rumble effects.
if !manager.rumbles.is_empty() {
let mut to_remove = Vec::new();
for (id, RunningRumble { deadline, .. }) in manager.rumbles.iter() {
if *deadline < current_time {
to_remove.push(*id);
}
}
for id in &to_remove {
// `ff::Effect` uses RAII, dropping = deactivating
manager.rumbles.remove(id);
}
}
// Add new effects.
for rumble in requests.iter().cloned() {
let pad = rumble.pad;
match add_rumble(&mut manager, &mut gilrs, rumble, current_time) {
Ok(()) => {}
Err(RumbleError::GilrsError(err)) => {
log::debug!("Tried to rumble {pad:?} but an error occurred: {err}")
}
Err(RumbleError::GamepadNotFound) => {
log::error!("Tried to rumble {pad:?} but it doesn't exist!")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
log::error!("Tried to rumble {pad:?} but it doesn't exist!")
log::warn!("Tried to rumble {pad:?} but it doesn't exist!")

}
};
}
}
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ Example | File | Description
`char_input_events` | [`input/char_input_events.rs`](./input/char_input_events.rs) | Prints out all chars as they are inputted.
`gamepad_input` | [`input/gamepad_input.rs`](./input/gamepad_input.rs) | Shows handling of gamepad input, connections, and disconnections
`gamepad_input_events` | [`input/gamepad_input_events.rs`](./input/gamepad_input_events.rs) | Iterates and prints gamepad input and connection events
`gamepad_rumble` | [`input/gamepad_rumble.rs`](./input/gamepad_rumble.rs) | Make a controller rumble
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`gamepad_rumble` | [`input/gamepad_rumble.rs`](./input/gamepad_rumble.rs) | Make a controller rumble
`gamepad_rumble` | [`input/gamepad_rumble.rs`](./input/gamepad_rumble.rs) | Makes a controller vibrate for force-feedback purposes

Keyword stuffing!

`keyboard_input` | [`input/keyboard_input.rs`](./input/keyboard_input.rs) | Demonstrates handling a key press/release
`keyboard_input_events` | [`input/keyboard_input_events.rs`](./input/keyboard_input_events.rs) | Prints out all keyboard events
`keyboard_modifiers` | [`input/keyboard_modifiers.rs`](./input/keyboard_modifiers.rs) | Demonstrates using key modifiers (ctrl, shift)
Expand Down
70 changes: 70 additions & 0 deletions examples/input/gamepad_rumble.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use bevy::{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs a module-style doc comment explaining what the example does.

gilrs::{ff, RumbleIntensity, RumbleRequest},
prelude::*,
};

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_system(gamepad_system)
.run();
}

fn gamepad_system(
gamepads: Res<Gamepads>,
button_inputs: Res<Input<GamepadButton>>,
mut rumble_requests: EventWriter<RumbleRequest>,
) {
for gamepad in gamepads.iter().cloned() {
let button_pressed = |button| button_inputs.just_pressed(GamepadButton(gamepad, button));
if button_pressed(GamepadButtonType::South) {
info!("(S) South face button: weak rumble for 3 second");
// Use the simplified API provided by bevy
rumble_requests.send(RumbleRequest::with_intensity(
RumbleIntensity::Weak,
3.0,
gamepad,
));
} else if button_pressed(GamepadButtonType::West) {
info!("(W) West face button: strong rumble for 10 second");
rumble_requests.send(RumbleRequest::with_intensity(
RumbleIntensity::Strong,
10.0,
gamepad,
));
} else if button_pressed(GamepadButtonType::East) {
info!("(E) East face button: alternating for 5 seconds");
// Use the gilrs::ff more complex but feature-complete effect
let duration = ff::Ticks::from_ms(800);
let mut effect = ff::EffectBuilder::new();
effect
.add_effect(ff::BaseEffect {
kind: ff::BaseEffectType::Strong { magnitude: 60_000 },
scheduling: ff::Replay {
play_for: duration,
with_delay: duration * 3,
..Default::default()
},
envelope: Default::default(),
})
.add_effect(ff::BaseEffect {
kind: ff::BaseEffectType::Weak { magnitude: 60_000 },
scheduling: ff::Replay {
after: duration * 2,
play_for: duration,
with_delay: duration * 3,
},
..Default::default()
});
let request = RumbleRequest {
pad: gamepad,
gilrs_effect: effect,
duration_seconds: 5.0,
};
rumble_requests.send(request);
} else if button_pressed(GamepadButtonType::North) {
info!("(N) North face button: Interupt the current rumble");
rumble_requests.send(RumbleRequest::stop(gamepad));
}
}
}