sdl2/
haptic.rs

1//! Haptic Functions
2use crate::sys;
3
4use crate::common::{validate_int, IntegerOrSdlError};
5use crate::get_error;
6use crate::HapticSubsystem;
7
8impl HapticSubsystem {
9    /// Attempt to open the joystick at index `joystick_index` and return its haptic device.
10    #[doc(alias = "SDL_JoystickOpen")]
11    pub fn open_from_joystick_id(&self, joystick_index: u32) -> Result<Haptic, IntegerOrSdlError> {
12        use crate::common::IntegerOrSdlError::*;
13        let joystick_index = validate_int(joystick_index, "joystick_index")?;
14
15        let haptic = unsafe {
16            let joystick = sys::SDL_JoystickOpen(joystick_index);
17            sys::SDL_HapticOpenFromJoystick(joystick)
18        };
19
20        if haptic.is_null() {
21            Err(SdlError(get_error()))
22        } else {
23            unsafe { sys::SDL_HapticRumbleInit(haptic) };
24            Ok(Haptic {
25                subsystem: self.clone(),
26                raw: haptic,
27            })
28        }
29    }
30}
31
32/// Wrapper around the `SDL_Haptic` object
33pub struct Haptic {
34    subsystem: HapticSubsystem,
35    raw: *mut sys::SDL_Haptic,
36}
37
38impl Haptic {
39    #[inline]
40    #[doc(alias = "SDL_HapticRumblePlay")]
41    pub fn subsystem(&self) -> &HapticSubsystem {
42        &self.subsystem
43    }
44
45    /// Run a simple rumble effect on the haptic device.
46    pub fn rumble_play(&mut self, strength: f32, duration: u32) {
47        unsafe { sys::SDL_HapticRumblePlay(self.raw, strength, duration) };
48    }
49
50    /// Stop the simple rumble on the haptic device.
51    #[doc(alias = "SDL_HapticRumbleStop")]
52    pub fn rumble_stop(&mut self) {
53        unsafe { sys::SDL_HapticRumbleStop(self.raw) };
54    }
55}
56
57impl Drop for Haptic {
58    #[doc(alias = "SDL_HapticClose")]
59    fn drop(&mut self) {
60        unsafe { sys::SDL_HapticClose(self.raw) }
61    }
62}