rich_sdl2_rust/haptic/
playing.rs

1//! Playing the effect on the haptic device.
2
3use crate::{bind, Result, Sdl, SdlError};
4
5use super::{effect::HapticEffect, Haptic};
6
7/// An haptic effect but pending to play.
8#[derive(Debug)]
9pub struct PendingEffect<'haptic> {
10    id: i32,
11    haptic: &'haptic Haptic,
12}
13
14impl<'haptic> PendingEffect<'haptic> {
15    pub(super) fn new(id: i32, haptic: &'haptic Haptic) -> Self {
16        Self { id, haptic }
17    }
18
19    /// Updates the effect with a new effect.
20    ///
21    /// # Errors
22    ///
23    /// Returns `Err` if failed to update the properties.
24    pub fn update(&self, effect: &HapticEffect) -> Result<()> {
25        let mut raw = effect.clone().into_raw();
26        let ret =
27            unsafe { bind::SDL_HapticUpdateEffect(self.haptic.ptr.as_ptr(), self.id, &mut raw) };
28        if ret < 0 {
29            Err(SdlError::Others { msg: Sdl::error() })
30        } else {
31            Ok(())
32        }
33    }
34
35    /// Starts to run the effect. If `iterations` is `None`, the effect repeats over and over indefinitely.
36    ///
37    /// # Errors
38    ///
39    /// Returns `Err` if failed to run the effect on the device.
40    pub fn run(self, iterations: Option<u32>) -> Result<PlayingEffect<'haptic>> {
41        let ret = unsafe {
42            bind::SDL_HapticRunEffect(
43                self.haptic.ptr.as_ptr(),
44                self.id,
45                iterations.unwrap_or(bind::SDL_HAPTIC_INFINITY),
46            )
47        };
48        if ret < 0 {
49            Err(SdlError::Others { msg: Sdl::error() })
50        } else {
51            Ok(PlayingEffect {
52                id: self.id,
53                haptic: self.haptic,
54            })
55        }
56    }
57
58    /// Drops the effect manually.
59    pub fn destroy(self) {
60        unsafe { bind::SDL_HapticDestroyEffect(self.haptic.ptr.as_ptr(), self.id) }
61    }
62}
63
64/// A playing haptic effect.
65#[derive(Debug)]
66pub struct PlayingEffect<'haptic> {
67    id: i32,
68    haptic: &'haptic Haptic,
69}
70
71impl<'haptic> PlayingEffect<'haptic> {
72    /// Stops playing the effect.
73    ///
74    /// # Errors
75    ///
76    /// Returns `Err` if failed to stop the effect on the device.
77    pub fn stop(self) -> Result<PendingEffect<'haptic>> {
78        let ret = unsafe { bind::SDL_HapticStopEffect(self.haptic.ptr.as_ptr(), self.id) };
79        if ret < 0 {
80            Err(SdlError::Others { msg: Sdl::error() })
81        } else {
82            Ok(PendingEffect {
83                id: self.id,
84                haptic: self.haptic,
85            })
86        }
87    }
88
89    /// Drops the effect manually.
90    pub fn destroy(self) {
91        unsafe { bind::SDL_HapticDestroyEffect(self.haptic.ptr.as_ptr(), self.id) }
92    }
93}