ferravex_render/input/
calibration.rs

1//! Opt-in checked calibration for normalized embedding-host samples.
2//!
3//! This module has no device reader, hardware discovery, persistence or automatic
4//! browser adoption. Linux polling and the existing browser ABI remain unchanged.
5//! A custom host owns one [`CalibratedGamepad`] per slot and submits **raw**
6//! [`PadState`] samples through it instead of also calling [`super::gamepad_sample`].
7//! Never feed the output of [`CalibrationProfile::apply`] back into the adapter.
8//! Buttons (including analog triggers and hats) are copied, never inferred from
9//! calibrated axes. Unselected axes keep their channel meanings.
10//!
11//! Profiles have no hardware identity. Selection belongs to this adapter's current
12//! connection only: disconnect or a changed host-supplied `PadState::epoch` clears
13//! it. A host replacing a device without an observed disconnect **must** call
14//! [`CalibratedGamepad::disconnect`] first, or change its supplied epoch. The
15//! platform journal owns its own epoch; the supplied epoch is not forwarded as an
16//! ABI or hardware ID. Use the adapter and its slot on one host thread, with no
17//! competing sample producer; dropping it does not submit a disconnect.
18//!
19//! A headless embedding-host recipe using the real journal and PlayerInput:
20//!
21//! ```rust,check
22//! use ferravex_core::session::GameSession;
23//! use ferravex_render::input::{
24//!     self, ActionKind, Binding, InputCode, PadState, PlayerInput,
25//!     calibration::{AxisCalibration, CalibrationProfile, CalibratedGamepad, RadialStick},
26//! };
27//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
28//! let mut session = GameSession::try_new(64., 4, true)?;
29//! let mut player = PlayerInput::transient("calibration-recipe");
30//! player.action("move_x", "Move", ActionKind::Axis,
31//!     vec![Binding::digital(InputCode::PadAxis(0))])?;
32//! player.action("jump", "Jump", ActionKind::Button,
33//!     vec![Binding::digital(InputCode::PadButton(0))])?;
34//! // Calibration supplies the radial response. Avoid applying a second deadzone
35//! // in PlayerInput; its default response otherwise still applies independently.
36//! let mut settings = player.settings();
37//! settings.pad_deadzone = 0.;
38//! settings.pad_curve = 1.;
39//! player.set_settings(settings)?;
40//! let mut pad = CalibratedGamepad::new(0)?;
41//! let mut raw = PadState { connected: true, ..PadState::default() };
42//! raw.axes[0] = 0.125; // supplied normalized drift, not a learned hardware value
43//! pad.submit(raw)?;
44//! input::host_frame(0., 640, 480, || player.sample(true)); // connection baseline
45//! pad.select_profile(CalibrationProfile::try_new(
46//!     &[(0, AxisCalibration { min: -0.75, center: 0.125, max: 0.875 })],
47//!     &[RadialStick { axes: [0, 1], deadzone: 0.125 }],
48//! )?)?;
49//! raw.axes[0] = 0.875;
50//! raw.buttons[0] = 1.;
51//! pad.submit(raw)?;
52//! raw.buttons[0] = 0.;
53//! pad.submit(raw)?; // quick tap within the same render frame
54//! input::host_frame(0., 640, 480, || {
55//!     player.sample(true);
56//!     assert_eq!(session.advance(0.).steps, 0); // leave gameplay edges pending
57//! });
58//! input::host_frame(2. / 64., 640, 480, || {
59//!     player.sample(true);
60//!     assert_eq!(player.value("move_x"), 1.);
61//!     let ticks = session.advance(2. / 64.);
62//!     assert_eq!(ticks.steps, 2);
63//!     for tick in 0..ticks.steps {
64//!         // Consume only on an actual simulation tick; share this snapshot.
65//!         let [jump] = player.take_tick(["jump"]);
66//!         assert_eq!(jump.pressed, tick == 0);
67//!         assert_eq!(jump.released, tick == 0);
68//!         assert_eq!(jump.value, 0.);
69//!     }
70//! });
71//! pad.reset(); // immediately resubmits the last raw sample with default axes
72//! pad.disconnect(); // neutral journal state and no retained profile
73//! # Ok(())
74//! # }
75//! ```
76
77use super::PadState;
78
79/// Number of slots accepted by the existing embedding boundary.
80pub const GAMEPAD_SLOTS: usize = 4;
81/// Axis count in [`PadState`]. Profiles are not restricted to Linux's six axes.
82pub const CALIBRATION_AXES: usize = 16;
83/// At most eight disjoint two-axis sticks fit in a sample.
84pub const CALIBRATION_STICKS: usize = CALIBRATION_AXES / 2;
85
86/// A signed axis maps `min` to -1, `center` to 0 and `max` to 1, piecewise
87/// linearly. Require finite `-1 <= min < center < max <= 1`. Author the values in
88/// the host's normalized units, before any application deadzone. For a trigger,
89/// opt in only if this signed response is desired; its button value is unchanged.
90#[derive(Clone, Copy, Debug, PartialEq)]
91pub struct AxisCalibration {
92    pub min: f32,
93    pub center: f32,
94    pub max: f32,
95}
96
97/// An explicit pair, processed after per-axis calibration. Radius <= deadzone
98/// becomes zero; (deadzone, 1) maps linearly to (0, 1); radius >= 1 becomes a unit
99/// vector. Direction is preserved. Require finite `0 <= deadzone < 1` and two
100/// distinct in-range axes which occur in no other pair. Zero still bounds
101/// diagonals to the unit disk; omit the pair to preserve square fullscale.
102#[derive(Clone, Copy, Debug, PartialEq)]
103pub struct RadialStick {
104    pub axes: [usize; 2],
105    pub deadzone: f32,
106}
107
108/// Validation errors never partially update a profile, adapter or journal.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum CalibrationError {
112    InvalidSlot { slot: usize },
113    TooManyAxes,
114    TooManySticks,
115    InvalidAxis { axis: usize },
116    DuplicateAxis { axis: usize },
117    InvalidRange { axis: usize },
118    InvalidDeadzone { stick: usize },
119    OverlappingStick { axis: usize },
120    NonFiniteAxis { axis: usize },
121    NonFiniteButton { button: usize },
122    Disconnected,
123}
124impl std::fmt::Display for CalibrationError {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "gamepad calibration: {self:?}")
127    }
128}
129impl std::error::Error for CalibrationError {}
130
131/// Immutable, checked, fixed-storage configuration. [`Default`] has no axis
132/// corrections or radial pairs. Configuration is caller-owned and not serialized.
133#[derive(Clone, Copy, Debug, Default, PartialEq)]
134pub struct CalibrationProfile {
135    axes: [Option<AxisCalibration>; CALIBRATION_AXES],
136    sticks: [Option<RadialStick>; CALIBRATION_STICKS],
137}
138impl CalibrationProfile {
139    /// Validate the entire bounded description before returning a profile.
140    /// Duplicate axis corrections and overlapping stick pairs are rejected.
141    /// An axis correction may also occur in one radial pair (correction first).
142    /// See the module recipe for construction, selection and reset.
143    pub fn try_new(
144        axes: &[(usize, AxisCalibration)],
145        sticks: &[RadialStick],
146    ) -> Result<Self, CalibrationError> {
147        if axes.len() > CALIBRATION_AXES {
148            return Err(CalibrationError::TooManyAxes);
149        }
150        if sticks.len() > CALIBRATION_STICKS {
151            return Err(CalibrationError::TooManySticks);
152        }
153        let mut result = Self::default();
154        for &(axis, range) in axes {
155            if axis >= CALIBRATION_AXES {
156                return Err(CalibrationError::InvalidAxis { axis });
157            }
158            if result.axes[axis].is_some() {
159                return Err(CalibrationError::DuplicateAxis { axis });
160            }
161            if !range.min.is_finite()
162                || !range.center.is_finite()
163                || !range.max.is_finite()
164                || range.min < -1.
165                || range.max > 1.
166                || range.min >= range.center
167                || range.center >= range.max
168            {
169                return Err(CalibrationError::InvalidRange { axis });
170            }
171            result.axes[axis] = Some(range);
172        }
173        let mut paired = [false; CALIBRATION_AXES];
174        for (stick, &pair) in sticks.iter().enumerate() {
175            if !pair.deadzone.is_finite() || !(0. ..1.).contains(&pair.deadzone) {
176                return Err(CalibrationError::InvalidDeadzone { stick });
177            }
178            for axis in pair.axes {
179                if axis >= CALIBRATION_AXES {
180                    return Err(CalibrationError::InvalidAxis { axis });
181                }
182                if paired[axis] {
183                    return Err(CalibrationError::OverlappingStick { axis });
184                }
185                paired[axis] = true;
186            }
187            result.sticks[stick] = Some(pair);
188        }
189        Ok(result)
190    }
191
192    /// Inspect every axis correction; `None` preserves that normalized channel.
193    pub fn axes(&self) -> &[Option<AxisCalibration>; CALIBRATION_AXES] {
194        &self.axes
195    }
196
197    /// Inspect pairs in authored order, followed by unused `None` entries.
198    pub fn sticks(&self) -> &[Option<RadialStick>; CALIBRATION_STICKS] {
199        &self.sticks
200    }
201
202    /// Pure transformation; never feeds the journal or mutates the supplied sample.
203    /// Validate **all** connected axes/buttons for finiteness before calculating.
204    /// Finite axis extremes clamp to [-1, 1]; buttons are copied bit-for-bit and
205    /// retain the existing platform button clamping at submission. f64 arithmetic
206    /// avoids overflow/underflow for finite f32 samples and narrow valid ranges.
207    /// Disconnected samples ignore even invalid stale values and return neutral
208    /// axes/buttons, retaining only the caller's epoch. No history or learning.
209    pub fn apply(&self, raw: PadState) -> Result<PadState, CalibrationError> {
210        if !raw.connected {
211            return Ok(PadState {
212                epoch: raw.epoch,
213                ..PadState::default()
214            });
215        }
216        for (axis, value) in raw.axes.iter().enumerate() {
217            if !value.is_finite() {
218                return Err(CalibrationError::NonFiniteAxis { axis });
219            }
220        }
221        for (button, value) in raw.buttons.iter().enumerate() {
222            if !value.is_finite() {
223                return Err(CalibrationError::NonFiniteButton { button });
224            }
225        }
226        let mut result = raw;
227        for (axis, value) in result.axes.iter_mut().enumerate() {
228            *value = match self.axes[axis] {
229                None => value.clamp(-1., 1.),
230                Some(range) => {
231                    let v = f64::from(*value);
232                    let center = f64::from(range.center);
233                    let distance = v - center;
234                    let span = if distance < 0. {
235                        center - f64::from(range.min)
236                    } else {
237                        f64::from(range.max) - center
238                    };
239                    (distance / span).clamp(-1., 1.) as f32
240                }
241            };
242        }
243        for pair in self.sticks.iter().flatten() {
244            let [a, b] = pair.axes;
245            let x = f64::from(result.axes[a]);
246            let y = f64::from(result.axes[b]);
247            let radius = (x * x + y * y).sqrt();
248            let deadzone = f64::from(pair.deadzone);
249            let scale = if radius <= deadzone {
250                0.
251            } else {
252                (radius.min(1.) - deadzone) / ((1. - deadzone) * radius)
253            };
254            result.axes[a] = (x * scale) as f32;
255            result.axes[b] = (y * scale) as f32;
256        }
257        Ok(result)
258    }
259}
260
261/// Explicit embedding-host adapter for one slot. No automatic device association,
262/// global selection, hidden native polling, allocations or button synthesis.
263/// It retains one last-good **raw** sample for immediate profile changes/reset.
264/// Errors preserve that sample, selection and existing journal state. Like
265/// [`super::gamepad_sample`], success means accepted submission, not consumption;
266/// normal journal capacity/focus rules and PlayerInput held suppression still apply.
267#[derive(Debug)]
268pub struct CalibratedGamepad {
269    slot: usize,
270    profile: Option<CalibrationProfile>,
271    last_raw: PadState,
272}
273impl CalibratedGamepad {
274    /// Create a disconnected adapter with no profile. Does not touch the host.
275    pub fn new(slot: usize) -> Result<Self, CalibrationError> {
276        if slot >= GAMEPAD_SLOTS {
277            return Err(CalibrationError::InvalidSlot { slot });
278        }
279        Ok(Self {
280            slot,
281            profile: None,
282            last_raw: PadState::default(),
283        })
284    }
285
286    /// The fixed journal slot. Host ownership is explicit, not a hardware ID.
287    pub fn slot(&self) -> usize {
288        self.slot
289    }
290
291    /// Selected connection-local profile, or `None` for existing defaults.
292    pub fn profile(&self) -> Option<&CalibrationProfile> {
293        self.profile.as_ref()
294    }
295
296    /// Last accepted uncalibrated sample, neutral when disconnected.
297    pub fn last_raw(&self) -> &PadState {
298        &self.last_raw
299    }
300
301    /// Calibrate exactly once and submit through [`super::gamepad_sample`].
302    /// A disconnect or changed supplied epoch clears selection; a changed epoch
303    /// also submits a disconnect/reconnect so existing PlayerInput held suppression
304    /// applies. A new connection starts with defaults until explicitly selected
305    /// again. Invalid connected samples do not clear selection, even when their
306    /// epoch changed: no part of
307    /// an invalid sample is accepted. A disconnected sample always succeeds.
308    pub fn submit(&mut self, raw: PadState) -> Result<(), CalibrationError> {
309        let profile =
310            if raw.connected && self.last_raw.connected && raw.epoch == self.last_raw.epoch {
311                self.profile
312            } else {
313                None
314            };
315        let output = profile.unwrap_or_default().apply(raw)?;
316        // The slot was checked at construction. The complete output has been
317        // validated before the existing boundary invokes any individual feed.
318        if self.last_raw.connected && raw.connected && raw.epoch != self.last_raw.epoch {
319            super::gamepad_sample(self.slot, PadState::default());
320        }
321        super::gamepad_sample(self.slot, output);
322        self.profile = profile;
323        self.last_raw = if raw.connected { raw } else { output };
324        Ok(())
325    }
326
327    /// Select for the current connection and immediately reapply the last raw
328    /// sample, including neutral axes. Replacing pairs cannot leave old axes
329    /// stuck, and unchanged buttons generate no new journal edges. Fails while
330    /// disconnected; profiles cannot silently wait for an unknown next device.
331    pub fn select_profile(&mut self, profile: CalibrationProfile) -> Result<(), CalibrationError> {
332        if !self.last_raw.connected {
333            return Err(CalibrationError::Disconnected);
334        }
335        let output = profile.apply(self.last_raw)?;
336        super::gamepad_sample(self.slot, output);
337        self.profile = Some(profile);
338        Ok(())
339    }
340
341    /// Clear selection and immediately resubmit the last raw sample using default
342    /// clamping. Does not disconnect, erase held buttons, or consume tick edges.
343    pub fn reset(&mut self) {
344        // Last raw is already validated (or disconnected), so this cannot fail.
345        let output = CalibrationProfile::default()
346            .apply(self.last_raw)
347            .expect("accepted calibration sample remains finite");
348        super::gamepad_sample(self.slot, output);
349        self.profile = None;
350    }
351
352    /// Explicitly end this device's slot ownership: neutralize the journal and
353    /// forget both profile and last raw sample. Repeated calls are harmless.
354    /// Call before replacing hardware when no physical disconnect was observed.
355    pub fn disconnect(&mut self) {
356        self.submit(PadState::default())
357            .expect("disconnected samples are always accepted");
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use crate::input::{InputCode, PlatformEvent};
365
366    #[test]
367    fn journey400_293_actual_button_journal_is_unchanged_by_profiles_and_reset() {
368        fn run(calibrated: bool) -> Vec<PlatformEvent> {
369            crate::edit(|s| *s = crate::State::default());
370            let mut adapter = CalibratedGamepad::new(0).unwrap();
371            let mut raw = PadState {
372                connected: true,
373                ..Default::default()
374            };
375            if calibrated {
376                adapter.submit(raw).unwrap();
377                adapter
378                    .select_profile(
379                        CalibrationProfile::try_new(
380                            &[(
381                                4,
382                                AxisCalibration {
383                                    min: -1.,
384                                    center: 0.25,
385                                    max: 1.,
386                                },
387                            )],
388                            &[RadialStick {
389                                axes: [0, 1],
390                                deadzone: 0.2,
391                            }],
392                        )
393                        .unwrap(),
394                    )
395                    .unwrap();
396            }
397            for (button, value) in [(0, 1.), (0, 0.), (6, 0.6), (7, 0.9), (14, 1.), (16, 0.7)] {
398                raw.buttons[button] = value;
399                raw.axes[0] = 0.1;
400                raw.axes[4] = 0.8;
401                if calibrated {
402                    adapter.submit(raw).unwrap();
403                    adapter.reset();
404                    adapter
405                        .select_profile(CalibrationProfile::default())
406                        .unwrap();
407                } else {
408                    super::super::gamepad_sample(0, raw);
409                }
410            }
411            crate::read(|s| {
412                s.input
413                    .events()
414                    .iter()
415                    .copied()
416                    .filter(|event| {
417                        matches!(
418                            event,
419                            PlatformEvent::Pad {
420                                code: InputCode::PadButton(_),
421                                ..
422                            }
423                        )
424                    })
425                    .collect()
426            })
427        }
428        let direct = run(false);
429        assert_eq!(direct.len(), 6);
430        assert_eq!(run(true), direct);
431    }
432
433    #[test]
434    fn journey400_293_rejected_final_axis_or_button_feeds_nothing() {
435        crate::edit(|s| *s = crate::State::default());
436        let mut adapter = CalibratedGamepad::new(0).unwrap();
437        let mut raw = PadState {
438            connected: true,
439            ..Default::default()
440        };
441        adapter.submit(raw).unwrap();
442        let before = crate::read(|s| (s.input.pads, s.input.events().to_vec()));
443        raw.axes[0] = 0.9;
444        raw.axes[15] = f32::NAN;
445        assert_eq!(
446            adapter.submit(raw),
447            Err(CalibrationError::NonFiniteAxis { axis: 15 })
448        );
449        raw.axes[15] = 0.;
450        raw.buttons[31] = f32::INFINITY;
451        assert_eq!(
452            adapter.submit(raw),
453            Err(CalibrationError::NonFiniteButton { button: 31 })
454        );
455        assert_eq!(
456            crate::read(|s| (s.input.pads, s.input.events().to_vec())),
457            before
458        );
459        assert_eq!(adapter.last_raw().axes, [0.; 16]);
460    }
461
462    #[test]
463    fn journey400_293_default_adapter_matches_full_direct_journal() {
464        fn run(adapted: bool) -> (PadState, Vec<PlatformEvent>) {
465            crate::edit(|s| *s = crate::State::default());
466            let mut adapter = CalibratedGamepad::new(0).unwrap();
467            let mut raw = PadState {
468                connected: true,
469                axes: std::array::from_fn(|i| (i as f32 - 8.) / 4.),
470                buttons: std::array::from_fn(|i| (i as f32 - 1.) / 16.),
471                ..Default::default()
472            };
473            for value in [1., 0., 0.8] {
474                raw.buttons[0] = value;
475                if adapted {
476                    adapter.submit(raw).unwrap();
477                } else {
478                    super::super::gamepad_sample(0, raw);
479                }
480            }
481            crate::read(|s| (s.input.pads[0], s.input.events().to_vec()))
482        }
483        let expected = run(false);
484        assert!(!expected.1.is_empty());
485        assert_eq!(run(true), expected);
486    }
487}