Skip to content

Add sensor API implementation #1131

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

Merged
merged 10 commits into from
Oct 10, 2021
Merged
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
10 changes: 4 additions & 6 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ jobs:
build-linux:
name: build linux pkg-config
runs-on: ubuntu-20.04
strategy:
fail-fast: false
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install dependencies
Expand All @@ -76,6 +74,6 @@ jobs:
set -xeuo pipefail
rustc --version
cargo --version
cargo build --features "${CI_BUILD_FEATURES}"
cargo build --examples --features "${CI_BUILD_FEATURES}"
cargo test --features "${CI_BUILD_FEATURES}"
# SDL 2.0.10 so no hidapi
cargo build --no-default-features --features "${CI_BUILD_FEATURES}"
cargo test --no-default-features --features "${CI_BUILD_FEATURES}"
9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ authors = [ "Tony Aldridge <[email protected]>", "Cobrand <[email protected]
keywords = ["SDL", "windowing", "graphics", "api", "engine"]
categories = ["rendering","api-bindings","game-engines","multimedia"]
readme = "README.md"
resolver = "2"

[lib]
name = "sdl2"
Expand Down Expand Up @@ -40,11 +41,13 @@ optional = true

[features]
unsafe_textures = []
default = []
#default = ["hidapi"]
gfx = ["c_vec", "sdl2-sys/gfx"]
mixer = ["sdl2-sys/mixer"]
image = ["sdl2-sys/image"]
ttf = ["sdl2-sys/ttf"]
# Use hidapi support in SDL. Only 2.0.12 and after
hidapi = []

use-bindgen = ["sdl2-sys/use-bindgen"]
use-pkgconfig = ["sdl2-sys/use-pkgconfig"]
Expand Down Expand Up @@ -140,6 +143,10 @@ name = "renderer-yuv"
required-features = ["ttf", "image"]
name = "resource-manager"

[[example]]
required-features = ["hidapi"]
name = "sensors"

[[example]]
required-features = ["ttf"]
name = "ttf-demo"
Expand Down
89 changes: 89 additions & 0 deletions examples/sensors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use std::time::{Duration, Instant};

use sdl2::{event::Event, sensor::SensorType};

extern crate sdl2;

fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let game_controller_subsystem = sdl_context.game_controller()?;

let available = game_controller_subsystem
.num_joysticks()
.map_err(|e| format!("can't enumerate joysticks: {}", e))?;

println!("{} joysticks available", available);

// Iterate over all available joysticks and look for game controllers.
let controller = (0..available)
.find_map(|id| {
if !game_controller_subsystem.is_game_controller(id) {
println!("{} is not a game controller", id);
return None;
}

println!("Attempting to open controller {}", id);

match game_controller_subsystem.open(id) {
Ok(c) => {
// We managed to find and open a game controller,
// exit the loop
println!("Success: opened \"{}\"", c.name());
Some(c)
}
Err(e) => {
println!("failed: {:?}", e);
None
}
}
})
.expect("Couldn't open any controller");

if !controller.has_sensor(SensorType::Accelerometer) {
return Err(format!(
"{} doesn't support the accelerometer",
controller.name()
));
}
if !controller.has_sensor(SensorType::Gyroscope) {
return Err(format!(
"{} doesn't support the gyroscope",
controller.name()
));
}

controller
.sensor_set_enabled(SensorType::Accelerometer, true)
.map_err(|e| format!("error enabling accelerometer: {}", e))?;
controller
.sensor_set_enabled(SensorType::Gyroscope, true)
.map_err(|e| format!("error enabling gyroscope: {}", e))?;
let mut now = Instant::now();
for event in sdl_context.event_pump()?.wait_iter() {
if false && now.elapsed() > Duration::from_secs(1) {
now = Instant::now();

let mut gyro_data = [0f32; 3];
let mut accel_data = [0f32; 3];

controller
.sensor_get_data(SensorType::Gyroscope, &mut gyro_data)
.map_err(|e| format!("error getting gyro data: {}", e))?;
controller
.sensor_get_data(SensorType::Accelerometer, &mut accel_data)
.map_err(|e| format!("error getting accel data: {}", e))?;

println!("gyro: {:?}, accel: {:?}", gyro_data, accel_data);
}

if let Event::ControllerSensorUpdated { .. } = event {
println!("{:?}", event);
}

if let Event::Quit { .. } = event {
break;
}
}

Ok(())
}
80 changes: 80 additions & 0 deletions src/sdl2/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ use std::fmt;
use std::io;
use std::path::Path;

#[cfg(feature = "hidapi")]
use crate::sensor::SensorType;
#[cfg(feature = "hidapi")]
use std::convert::TryInto;

use crate::common::{validate_int, IntegerOrSdlError};
use crate::get_error;
use crate::joystick;
Expand Down Expand Up @@ -486,6 +491,81 @@ impl GameController {
}
}

#[cfg(feature = "hidapi")]
impl GameController {
#[doc(alias = "SDL_GameControllerHasSensor")]
pub fn has_sensor(&self, sensor_type: crate::sensor::SensorType) -> bool {
let result = unsafe { sys::SDL_GameControllerHasSensor(self.raw, sensor_type.into()) };

match result {
sys::SDL_bool::SDL_FALSE => false,
sys::SDL_bool::SDL_TRUE => true,
}
}

#[doc(alias = "SDL_GameControllerIsSensorEnabled")]
pub fn sensor_enabled(&self, sensor_type: crate::sensor::SensorType) -> bool {
let result =
unsafe { sys::SDL_GameControllerIsSensorEnabled(self.raw, sensor_type.into()) };

match result {
sys::SDL_bool::SDL_FALSE => false,
sys::SDL_bool::SDL_TRUE => true,
}
}

#[doc(alias = "SDL_GameControllerHasSensor")]
pub fn sensor_set_enabled(
&self,
sensor_type: crate::sensor::SensorType,
enabled: bool,
) -> Result<(), IntegerOrSdlError> {
let result = unsafe {
sys::SDL_GameControllerSetSensorEnabled(
self.raw,
sensor_type.into(),
if enabled {
sys::SDL_bool::SDL_TRUE
} else {
sys::SDL_bool::SDL_FALSE
},
)
};

if result != 0 {
Err(IntegerOrSdlError::SdlError(get_error()))
} else {
Ok(())
}
}

/// Get data from a sensor.
///
/// The number of data points depends on the sensor. Both Gyroscope and
/// Accelerometer return 3 values, one for each axis.
#[doc(alias = "SDL_GameControllerGetSensorData")]
pub fn sensor_get_data(
&self,
sensor_type: SensorType,
data: &mut [f32],
) -> Result<(), IntegerOrSdlError> {
let result = unsafe {
sys::SDL_GameControllerGetSensorData(
self.raw,
sensor_type.into(),
data.as_mut_ptr(),
data.len().try_into().unwrap(),
)
};

if result != 0 {
Err(IntegerOrSdlError::SdlError(get_error()))
} else {
Ok(())
}
}
}

impl Drop for GameController {
#[doc(alias = "SDL_GameControllerClose")]
fn drop(&mut self) {
Expand Down
30 changes: 30 additions & 0 deletions src/sdl2/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,8 @@ pub enum EventType {
ControllerDeviceAdded = SDL_EventType::SDL_CONTROLLERDEVICEADDED as u32,
ControllerDeviceRemoved = SDL_EventType::SDL_CONTROLLERDEVICEREMOVED as u32,
ControllerDeviceRemapped = SDL_EventType::SDL_CONTROLLERDEVICEREMAPPED as u32,
#[cfg(feature = "hidapi")]
ControllerSensorUpdated = SDL_EventType::SDL_CONTROLLERSENSORUPDATE as u32,

FingerDown = SDL_EventType::SDL_FINGERDOWN as u32,
FingerUp = SDL_EventType::SDL_FINGERUP as u32,
Expand Down Expand Up @@ -366,6 +368,8 @@ impl TryFrom<u32> for EventType {
SDL_CONTROLLERDEVICEADDED => ControllerDeviceAdded,
SDL_CONTROLLERDEVICEREMOVED => ControllerDeviceRemoved,
SDL_CONTROLLERDEVICEREMAPPED => ControllerDeviceRemapped,
#[cfg(feature = "hidapi")]
SDL_CONTROLLERSENSORUPDATE => ControllerSensorUpdated,

SDL_FINGERDOWN => FingerDown,
SDL_FINGERUP => FingerUp,
Expand Down Expand Up @@ -674,6 +678,18 @@ pub enum Event {
which: u32,
},

/// Triggered when the gyroscope or accelerometer is updated
#[cfg(feature = "hidapi")]
ControllerSensorUpdated {
timestamp: u32,
which: u32,
sensor: crate::sensor::SensorType,
/// Data from the sensor.
///
/// See the `sensor` module for more information.
data: [f32; 3],
},

FingerDown {
timestamp: u32,
touch_id: i64,
Expand Down Expand Up @@ -1612,6 +1628,16 @@ impl Event {
which: event.which as u32,
}
}
#[cfg(feature = "hidapi")]
EventType::ControllerSensorUpdated => {
let event = raw.csensor;
Event::ControllerSensorUpdated {
timestamp: event.timestamp,
which: event.which as u32,
sensor: crate::sensor::SensorType::from_ll(event.sensor),
data: event.data,
}
}

EventType::FingerDown => {
let event = raw.tfinger;
Expand Down Expand Up @@ -1898,6 +1924,8 @@ impl Event {
| (Self::RenderDeviceReset { .. }, Self::RenderDeviceReset { .. })
| (Self::User { .. }, Self::User { .. })
| (Self::Unknown { .. }, Self::Unknown { .. }) => true,
#[cfg(feature = "hidapi")]
(Self::ControllerSensorUpdated { .. }, Self::ControllerSensorUpdated { .. }) => true,
_ => false,
}
}
Expand Down Expand Up @@ -1947,6 +1975,8 @@ impl Event {
Self::ControllerDeviceAdded { timestamp, .. } => timestamp,
Self::ControllerDeviceRemoved { timestamp, .. } => timestamp,
Self::ControllerDeviceRemapped { timestamp, .. } => timestamp,
#[cfg(feature = "hidapi")]
Self::ControllerSensorUpdated { timestamp, .. } => timestamp,
Self::FingerDown { timestamp, .. } => timestamp,
Self::FingerUp { timestamp, .. } => timestamp,
Self::FingerMotion { timestamp, .. } => timestamp,
Expand Down
2 changes: 2 additions & 0 deletions src/sdl2/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ pub mod rect;
pub mod render;
pub mod rwops;
mod sdl;
#[cfg(feature = "hidapi")]
pub mod sensor;
pub mod surface;
pub mod timer;
pub mod touch;
Expand Down
7 changes: 7 additions & 0 deletions src/sdl2/sdl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ impl Sdl {
GameControllerSubsystem::new(self)
}

/// Initializes the game controller subsystem.
#[inline]
pub fn sensor(&self) -> Result<SensorSubsystem, String> {
SensorSubsystem::new(self)
}

/// Initializes the timer subsystem.
#[inline]
pub fn timer(&self) -> Result<TimerSubsystem, String> {
Expand Down Expand Up @@ -278,6 +284,7 @@ subsystem!(VideoSubsystem, sys::SDL_INIT_VIDEO, nosync);
subsystem!(TimerSubsystem, sys::SDL_INIT_TIMER, sync);
// The event queue can be read from other threads.
subsystem!(EventSubsystem, sys::SDL_INIT_EVENTS, sync);
subsystem!(SensorSubsystem, sys::SDL_INIT_SENSOR, sync);

static mut IS_EVENT_PUMP_ALIVE: bool = false;

Expand Down
Loading