leafwing_input_manager/input_processing/single_axis/
custom.rs

1use std::any::Any;
2use std::fmt::Debug;
3use std::sync::{LazyLock, RwLock};
4
5use bevy::app::App;
6use bevy::prelude::{FromReflect, Reflect, ReflectDeserialize, ReflectSerialize, TypePath};
7use bevy::reflect::utility::{GenericTypePathCell, NonGenericTypeInfoCell};
8use bevy::reflect::{
9    erased_serde, FromType, GetTypeRegistration, OpaqueInfo, PartialReflect, ReflectFromPtr,
10    ReflectKind, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypeRegistration, Typed,
11};
12use dyn_clone::DynClone;
13use dyn_eq::DynEq;
14use dyn_hash::DynHash;
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16use serde_flexitos::ser::require_erased_serialize_impl;
17use serde_flexitos::{serialize_trait_object, Registry};
18
19use crate::input_processing::AxisProcessor;
20use crate::typetag::{InfallibleMapRegistry, RegisterTypeTag};
21
22/// A trait for creating custom processor that handles single-axis input values,
23/// accepting a `f32` input and producing a `f32` output.
24///
25/// # Examples
26///
27/// ```rust
28/// use std::hash::{Hash, Hasher};
29/// use bevy::prelude::*;
30/// use bevy::math::FloatOrd;
31/// use serde::{Deserialize, Serialize};
32/// use leafwing_input_manager::prelude::*;
33///
34/// /// Doubles the input, takes the absolute value,
35/// /// and discards results that meet the specified condition.
36/// // If your processor includes fields not implemented Eq and Hash,
37/// // implementation is necessary as shown below.
38/// // Otherwise, you can derive Eq and Hash directly.
39/// #[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
40/// pub struct DoubleAbsoluteValueThenIgnored(pub f32);
41///
42/// // Add this attribute for ensuring proper serialization and deserialization.
43/// #[serde_typetag]
44/// impl CustomAxisProcessor for DoubleAbsoluteValueThenIgnored {
45///     fn process(&self, input_value: f32) -> f32 {
46///         // Implement the logic just like you would in a normal function.
47///
48///         // You can use other processors within this function.
49///         let value = AxisProcessor::Sensitivity(2.0).process(input_value);
50///
51///         let value = value.abs();
52///         if value == self.0 {
53///             0.0
54///         } else {
55///             value
56///         }
57///     }
58/// }
59///
60/// // Unfortunately, manual implementation is required due to the float field.
61/// impl Eq for DoubleAbsoluteValueThenIgnored {}
62/// impl Hash for DoubleAbsoluteValueThenIgnored {
63///     fn hash<H: Hasher>(&self, state: &mut H) {
64///         // Encapsulate the float field for hashing.
65///         FloatOrd(self.0).hash(state);
66///     }
67/// }
68///
69/// // Remember to register your processor - it will ensure everything works smoothly!
70/// let mut app = App::new();
71/// app.register_axis_processor::<DoubleAbsoluteValueThenIgnored>();
72///
73/// // Now you can use it!
74/// let processor = DoubleAbsoluteValueThenIgnored(4.0);
75///
76/// // Rejected!
77/// assert_eq!(processor.process(2.0), 0.0);
78/// assert_eq!(processor.process(-2.0), 0.0);
79///
80/// // Others are just doubled absolute value.
81/// assert_eq!(processor.process(6.0), 12.0);
82/// assert_eq!(processor.process(4.0), 8.0);
83/// assert_eq!(processor.process(0.0), 0.0);
84/// assert_eq!(processor.process(-4.0), 8.0);
85/// assert_eq!(processor.process(-6.0), 12.0);
86///
87/// // The ways to create an AxisProcessor.
88/// let axis_processor = AxisProcessor::Custom(Box::new(processor));
89/// assert_eq!(axis_processor, AxisProcessor::from(processor));
90/// ```
91pub trait CustomAxisProcessor:
92    Send + Sync + Debug + DynClone + DynEq + DynHash + Reflect + erased_serde::Serialize
93{
94    /// Computes the result by processing the `input_value`.
95    fn process(&self, input_value: f32) -> f32;
96}
97
98impl<P: CustomAxisProcessor> From<P> for AxisProcessor {
99    fn from(value: P) -> Self {
100        Self::Custom(Box::new(value))
101    }
102}
103
104dyn_clone::clone_trait_object!(CustomAxisProcessor);
105dyn_eq::eq_trait_object!(CustomAxisProcessor);
106dyn_hash::hash_trait_object!(CustomAxisProcessor);
107
108impl PartialReflect for Box<dyn CustomAxisProcessor> {
109    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
110        Some(Self::type_info())
111    }
112
113    fn reflect_kind(&self) -> ReflectKind {
114        ReflectKind::Opaque
115    }
116
117    fn reflect_ref(&self) -> ReflectRef<'_> {
118        ReflectRef::Opaque(self)
119    }
120
121    fn reflect_mut(&mut self) -> ReflectMut<'_> {
122        ReflectMut::Opaque(self)
123    }
124
125    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
126        ReflectOwned::Opaque(self)
127    }
128
129    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), bevy::reflect::ApplyError> {
130        if let Some(value) = value.try_downcast_ref::<Self>() {
131            *self = value.clone();
132            Ok(())
133        } else {
134            Err(bevy::reflect::ApplyError::MismatchedTypes {
135                from_type: self
136                    .reflect_type_ident()
137                    .unwrap_or_default()
138                    .to_string()
139                    .into_boxed_str(),
140                to_type: self
141                    .reflect_type_ident()
142                    .unwrap_or_default()
143                    .to_string()
144                    .into_boxed_str(),
145            })
146        }
147    }
148
149    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
150        self
151    }
152
153    fn as_partial_reflect(&self) -> &dyn PartialReflect {
154        self
155    }
156
157    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
158        self
159    }
160
161    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
162        Ok(self)
163    }
164
165    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
166        Some(self)
167    }
168
169    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
170        Some(self)
171    }
172}
173
174impl Reflect for Box<dyn CustomAxisProcessor> {
175    fn into_any(self: Box<Self>) -> Box<dyn Any> {
176        self
177    }
178
179    fn as_any(&self) -> &dyn Any {
180        self
181    }
182
183    fn as_any_mut(&mut self) -> &mut dyn Any {
184        self
185    }
186
187    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
188        self
189    }
190
191    fn as_reflect(&self) -> &dyn Reflect {
192        self
193    }
194
195    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
196        self
197    }
198
199    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
200        *self = value.take()?;
201        Ok(())
202    }
203}
204
205impl Typed for Box<dyn CustomAxisProcessor> {
206    fn type_info() -> &'static TypeInfo {
207        static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
208        CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
209    }
210}
211
212impl TypePath for Box<dyn CustomAxisProcessor> {
213    fn type_path() -> &'static str {
214        static CELL: GenericTypePathCell = GenericTypePathCell::new();
215        CELL.get_or_insert::<Self, _>(|| {
216            {
217                format!(
218                    "std::boxed::Box<dyn {}::CustomAxisProcessor>",
219                    module_path!()
220                )
221            }
222        })
223    }
224
225    fn short_type_path() -> &'static str {
226        static CELL: GenericTypePathCell = GenericTypePathCell::new();
227        CELL.get_or_insert::<Self, _>(|| "Box<dyn CustomAxisProcessor>".to_string())
228    }
229
230    fn type_ident() -> Option<&'static str> {
231        Some("Box<dyn CustomAxisProcessor>")
232    }
233
234    fn crate_name() -> Option<&'static str> {
235        Some(module_path!().split(':').next().unwrap())
236    }
237
238    fn module_path() -> Option<&'static str> {
239        Some(module_path!())
240    }
241}
242
243impl GetTypeRegistration for Box<dyn CustomAxisProcessor> {
244    fn get_type_registration() -> TypeRegistration {
245        let mut registration = TypeRegistration::of::<Self>();
246        registration.insert::<ReflectDeserialize>(FromType::<Self>::from_type());
247        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
248        registration.insert::<ReflectSerialize>(FromType::<Self>::from_type());
249        registration
250    }
251}
252
253impl FromReflect for Box<dyn CustomAxisProcessor> {
254    fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
255        Some(reflect.try_downcast_ref::<Self>()?.clone())
256    }
257}
258
259impl Serialize for dyn CustomAxisProcessor + '_ {
260    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
261    where
262        S: Serializer,
263    {
264        // Check that `CustomAxisProcessor` has `erased_serde::Serialize` as a super trait,
265        // prmessageing infinite recursion at runtime.
266        const fn __check_erased_serialize_super_trait<T: ?Sized + CustomAxisProcessor>() {
267            require_erased_serialize_impl::<T>();
268        }
269        serialize_trait_object(serializer, self.reflect_short_type_path(), self)
270    }
271}
272
273impl<'de> Deserialize<'de> for Box<dyn CustomAxisProcessor> {
274    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
275    where
276        D: Deserializer<'de>,
277    {
278        let registry = PROCESSOR_REGISTRY.read().unwrap();
279        registry.deserialize_trait_object(deserializer)
280    }
281}
282
283/// Registry of deserializers for [`CustomAxisProcessor`]s.
284static PROCESSOR_REGISTRY: LazyLock<RwLock<InfallibleMapRegistry<dyn CustomAxisProcessor>>> =
285    LazyLock::new(|| RwLock::new(InfallibleMapRegistry::new("CustomAxisProcessor")));
286
287/// A trait for registering a specific [`CustomAxisProcessor`].
288pub trait RegisterCustomAxisProcessorExt {
289    /// Registers the specified [`CustomAxisProcessor`].
290    fn register_axis_processor<'de, T>(&mut self) -> &mut Self
291    where
292        T: RegisterTypeTag<'de, dyn CustomAxisProcessor> + GetTypeRegistration;
293}
294
295impl RegisterCustomAxisProcessorExt for App {
296    fn register_axis_processor<'de, T>(&mut self) -> &mut Self
297    where
298        T: RegisterTypeTag<'de, dyn CustomAxisProcessor> + GetTypeRegistration,
299    {
300        let mut registry = PROCESSOR_REGISTRY.write().unwrap();
301        T::register_typetag(&mut registry);
302        self.register_type::<T>();
303        self
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate as leafwing_input_manager;
311    use leafwing_input_manager_macros::serde_typetag;
312    use serde_test::{assert_tokens, Token};
313
314    #[test]
315    fn test_custom_axis_processor() {
316        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
317        struct CustomAxisInverted;
318
319        #[serde_typetag]
320        impl CustomAxisProcessor for CustomAxisInverted {
321            fn process(&self, input_value: f32) -> f32 {
322                -input_value
323            }
324        }
325
326        let mut app = App::new();
327        app.register_axis_processor::<CustomAxisInverted>();
328
329        let custom: Box<dyn CustomAxisProcessor> = Box::new(CustomAxisInverted);
330        assert_tokens(
331            &custom,
332            &[
333                Token::Map { len: Some(1) },
334                Token::BorrowedStr("CustomAxisInverted"),
335                Token::UnitStruct {
336                    name: "CustomAxisInverted",
337                },
338                Token::MapEnd,
339            ],
340        );
341
342        let processor = AxisProcessor::Custom(custom);
343        assert_eq!(AxisProcessor::from(CustomAxisInverted), processor);
344
345        for value in -300..300 {
346            let value = value as f32 * 0.01;
347
348            assert_eq!(processor.process(value), -value);
349            assert_eq!(CustomAxisInverted.process(value), -value);
350        }
351    }
352}