From 32a5308b595811b5fc0ca32997cb42f95719e3ca Mon Sep 17 00:00:00 2001 From: Josh Gao Date: Tue, 6 Aug 2019 22:35:29 -0700 Subject: [PATCH] Add support for custom deadzones. --- dhc/src/config.rs | 14 +++++++++++++- dhc/src/input/mod.rs | 1 + dhc/src/lib.rs | 25 +++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/dhc/src/config.rs b/dhc/src/config.rs index 0e50b1a..e8a0102 100644 --- a/dhc/src/config.rs +++ b/dhc/src/config.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use crate::logger; -#[derive(Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug)] pub struct Config { #[serde(default = "default_console")] pub console: bool, @@ -20,6 +20,14 @@ pub struct Config { #[serde(default = "default_xinput_enabled")] pub xinput_enabled: bool, + + pub deadzone: Option, +} + +#[derive(Clone, Serialize, Deserialize, Debug)] +pub struct DeadzoneConfig { + pub enabled: bool, + pub threshold: f32, } fn default_console() -> bool { @@ -45,6 +53,10 @@ impl Default for Config { log_level: default_log_level(), device_count: default_device_count(), xinput_enabled: default_xinput_enabled(), + deadzone: Some(DeadzoneConfig { + enabled: false, + threshold: 0.5, + }), } } } diff --git a/dhc/src/input/mod.rs b/dhc/src/input/mod.rs index 9c96c13..9ac52a5 100644 --- a/dhc/src/input/mod.rs +++ b/dhc/src/input/mod.rs @@ -136,6 +136,7 @@ impl RawInputDeviceState { } } + crate::mangle_inputs(&mut inputs); self.buffer.write(inputs); } } diff --git a/dhc/src/lib.rs b/dhc/src/lib.rs index 21ea62e..af12c9b 100644 --- a/dhc/src/lib.rs +++ b/dhc/src/lib.rs @@ -262,3 +262,28 @@ impl Context { state.update(); } } + +pub(crate) fn mangle_inputs(inputs: &mut DeviceInputs) { + if let Some(deadzone_config) = &CONFIG.deadzone { + if deadzone_config.enabled { + for ref mut axis in &mut [&mut inputs.axis_left_stick_x, &mut inputs.axis_left_stick_y] { + let value = axis.get(); + // For convenience, interpolate from [0, 1] to [-1, 1], perform the + // deadzone operations, and then interpolate back. + let (sign, magnitude) = if value > 0.5 { + (1.0, (value - 0.5) * 2.0) + } else { + (-1.0, (0.5 - value) * 2.0) + }; + + let magnitude = if magnitude > deadzone_config.threshold { + 1.0 + } else { + 0.0 + }; + + axis.set_value(0.5 + 0.5 * sign * magnitude); + } + } + } +}