ferravex_render/input/
player.rs

1use super::{
2    platform::{MAX_EVENTS, PlatformEvent},
3    storage, *,
4};
5use ferravex_play::input::touch::{self, TouchSurface};
6mod editor;
7pub use editor::{VisibleHintError, VisibleTouchLabel};
8#[cfg(test)]
9mod tests;
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum ControlsStatus {
12    Defaults,
13    Transient,
14    Loaded { unknown: usize },
15    Saved,
16    Invalid(InputError),
17    Storage(StorageError),
18}
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum CaptureDevice {
21    KeyboardMouse,
22    Gamepad,
23}
24/// Device family used to select binding hints. Keyboard and mouse share a
25/// family because a player commonly uses both together. Controller and touch
26/// labels use the host's channel numbers, not guessed hardware glyphs.
27///
28/// ```
29/// use ferravex_render::input::PlayerInput;
30/// let input = PlayerInput::transient("hint-device");
31/// let device = input.current_device();
32/// assert_eq!(format!("{device:?}"), "KeyboardMouse");
33/// ```
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum HintDevice {
36    KeyboardMouse,
37    Gamepad,
38    Touch,
39}
40impl HintDevice {
41    fn for_code(code: InputCode) -> Self {
42        match code {
43            InputCode::PadAxis(_) | InputCode::PadButton(_) => Self::Gamepad,
44            InputCode::Touch(_) | InputCode::TouchDelta(_) => Self::Touch,
45            _ => Self::KeyboardMouse,
46        }
47    }
48}
49
50/// A hint cannot be formatted. Both errors leave the caller's buffer unchanged.
51///
52/// ```
53/// use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput};
54/// let mut input = PlayerInput::transient("hint-error");
55/// input.action("jump", "Jump", ActionKind::Button,
56///     vec![Binding::digital(InputCode::Key(32))]).unwrap();
57/// let mut short = [b'?'; 4];
58/// let error = input.format_hint("jump", &mut short).unwrap_err();
59/// assert_eq!(error.to_string(), "hint buffer requires 5 bytes");
60/// assert_eq!(&short, b"????");
61/// ```
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum HintError {
64    /// An unknown action name produces [`InputError::InvalidHandle`].
65    Input(InputError),
66    /// Required UTF-8 bytes, without a trailing NUL. No partial label is written.
67    BufferTooSmall { required: usize },
68}
69impl std::fmt::Display for HintError {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Self::Input(error) => write!(f, "{error}"),
73            Self::BufferTooSmall { required } => write!(f, "hint buffer requires {required} bytes"),
74        }
75    }
76}
77impl std::error::Error for HintError {}
78
79struct ActionInfo {
80    id: usize,
81    name: String,
82    label: String,
83    defaults: Box<[Binding]>,
84    global: bool,
85    kind: ActionKind,
86}
87#[derive(Clone, Copy)]
88struct Capture {
89    action: usize,
90    device: CaptureDevice,
91}
92pub struct PlayerInput {
93    owner: String,
94    map: ActionMap,
95    gameplay: ContextId,
96    actions: Vec<ActionInfo>,
97    settings: ControlSettings,
98    loaded: bool,
99    persistent: bool,
100    preferences: Option<crate::preferences::Session>,
101    surface: TouchSurface,
102    raw_touch: Vec<touch::Control>,
103    touch_settings: touch::TouchLayoutSettings,
104    touch_store: Option<crate::storage::Slot<touch::TouchLayoutSettings>>,
105    touch_save_failed: bool,
106    last_frame: Option<u64>,
107    focus_epoch: u64,
108    focused: bool,
109    enabled: bool,
110    touch_seen: bool,
111    hint_device: HintDevice,
112    non_pad_hint_device: HintDevice,
113    mouse_look_button: Option<u8>,
114    selected_pad: usize,
115    pad_epoch: u32,
116    pad_axes: [f32; 16],
117    pad_axes_suppressed: u16,
118    pad_buttons_suppressed: u32,
119    open: bool,
120    paused: bool,
121    prior_cursor: (bool, bool),
122    capture: Option<Capture>,
123    status: ControlsStatus,
124    pointer: Vec2,
125    cursor: Option<Vec2>,
126    cursor_physical: Vec2,
127    cursor_virtual: bool,
128    ui_click: bool,
129    ui_taps: [Vec2; 16],
130    ui_tap_len: usize,
131    ui_block: bool,
132    external_details: bool,
133    devices_tab: bool,
134    page: usize,
135    ui_focus: usize,
136    ui_up: bool,
137    ui_down: bool,
138    ui_accept: bool,
139}
140impl PlayerInput {
141    /// Build a named profile, register actions, then sample once per render frame.
142    /// Configuration is loaded lazily after registration on the first sample.
143    pub fn new(owner: &str) -> Self {
144        assert!(crate::storage::valid_name(owner), "valid controls owner");
145        let mut map = ActionMap::default();
146        let gameplay = map.create_context("gameplay").unwrap();
147        map.set_context(Some(gameplay)).unwrap();
148        crate::edit(|s| s.input_enabled = true);
149        Self {
150            owner: owner.into(),
151            map,
152            gameplay,
153            actions: Vec::new(),
154            settings: ControlSettings::default(),
155            loaded: false,
156            persistent: true,
157            preferences: None,
158            surface: TouchSurface::default(),
159            raw_touch: Vec::with_capacity(16),
160            touch_settings: touch::TouchLayoutSettings::default(),
161            touch_store: None,
162            touch_save_failed: false,
163            last_frame: None,
164            focus_epoch: 0,
165            focused: true,
166            enabled: true,
167            touch_seen: false,
168            hint_device: HintDevice::KeyboardMouse,
169            non_pad_hint_device: HintDevice::KeyboardMouse,
170            mouse_look_button: None,
171            selected_pad: usize::MAX,
172            pad_epoch: 0,
173            pad_axes: [0.; 16],
174            pad_axes_suppressed: 0,
175            pad_buttons_suppressed: 0,
176            open: false,
177            paused: false,
178            prior_cursor: (false, true),
179            capture: None,
180            status: ControlsStatus::Defaults,
181            pointer: Vec2::ZERO,
182            cursor: None,
183            cursor_physical: Vec2::ZERO,
184            cursor_virtual: false,
185            ui_click: false,
186            ui_taps: [Vec2::ZERO; 16],
187            ui_tap_len: 0,
188            ui_block: false,
189            external_details: false,
190            devices_tab: false,
191            page: 0,
192            ui_focus: 0,
193            ui_up: false,
194            ui_down: false,
195            ui_accept: false,
196        }
197    }
198    /// Session-only profile for tests, tools and hosts that own their storage.
199    pub fn transient(owner: &str) -> Self {
200        let mut input = Self::new(owner);
201        input.persistent = false;
202        input.loaded = true;
203        input.status = ControlsStatus::Transient;
204        input
205    }
206    pub fn action(
207        &mut self,
208        name: &str,
209        label: &str,
210        kind: ActionKind,
211        bindings: Vec<Binding>,
212    ) -> Result<usize, InputError> {
213        self.register(name, label, kind, bindings, false)
214    }
215    pub fn global_action(
216        &mut self,
217        name: &str,
218        label: &str,
219        kind: ActionKind,
220        bindings: Vec<Binding>,
221    ) -> Result<usize, InputError> {
222        self.register(name, label, kind, bindings, true)
223    }
224    fn register(
225        &mut self,
226        name: &str,
227        label: &str,
228        kind: ActionKind,
229        bindings: Vec<Binding>,
230        global: bool,
231    ) -> Result<usize, InputError> {
232        if bindings.iter().any(|b| reserved(b.code)) {
233            return Err(InputError::InvalidBinding);
234        }
235        if label.len() > 96 {
236            return Err(InputError::InvalidName);
237        }
238        let id = self.map.named_action(
239            name,
240            kind,
241            if global {
242                ContextId::GLOBAL
243            } else {
244                self.gameplay
245            },
246            bindings.clone(),
247        )?;
248        self.actions.push(ActionInfo {
249            id,
250            name: name.into(),
251            label: label.into(),
252            defaults: bindings.into_boxed_slice(),
253            global,
254            kind,
255        });
256        Ok(id)
257    }
258    /// Restrict relative mouse look to dragging a button, leaving touch/stick look
259    /// independent. None is suitable for pointer-locked first-person games.
260    pub fn set_mouse_look_button(&mut self, button: Option<u8>) -> Result<(), InputError> {
261        if button.is_some_and(|b| !(1..=5).contains(&b)) {
262            return Err(InputError::InvalidBinding);
263        }
264        self.mouse_look_button = button;
265        Ok(())
266    }
267    pub fn bindings(&self, name: &str) -> Option<&[Binding]> {
268        self.map
269            .action_id(name)
270            .and_then(|id| self.map.bindings(id))
271    }
272    /// Extend an authored profile before its first sample. The binding also
273    /// becomes part of Reset defaults; saved mappings load after registration.
274    pub fn add_default_binding(&mut self, name: &str, binding: Binding) -> Result<(), InputError> {
275        let index = self
276            .actions
277            .iter()
278            .position(|a| a.name == name)
279            .ok_or(InputError::InvalidHandle)?;
280        let mut bindings = self.actions[index].defaults.to_vec();
281        bindings.push(binding);
282        self.set_default_bindings(name, bindings)
283    }
284    /// Replace authored defaults before the first sample (for a custom profile).
285    pub fn set_default_bindings(
286        &mut self,
287        name: &str,
288        bindings: Vec<Binding>,
289    ) -> Result<(), InputError> {
290        let index = self
291            .actions
292            .iter()
293            .position(|a| a.name == name)
294            .ok_or(InputError::InvalidHandle)?;
295        self.rebind(name, bindings.clone())?;
296        self.actions[index].defaults = bindings.into_boxed_slice();
297        Ok(())
298    }
299    pub fn preferences(&self) -> crate::preferences::Preferences {
300        self.preferences
301            .as_ref()
302            .map_or_else(Default::default, |p| p.current())
303    }
304    pub fn preferences_error(&self) -> Option<crate::storage::StorageError> {
305        self.preferences.as_ref().and_then(|p| p.error())
306    }
307    pub fn set_preferences(
308        &mut self,
309        next: crate::preferences::Preferences,
310    ) -> Result<(), crate::storage::StorageError> {
311        self.preferences
312            .get_or_insert_with(|| crate::preferences::Session::new(&self.owner, !self.persistent))
313            .set(next)
314    }
315    pub fn save_preferences(&mut self) -> Result<(), crate::storage::StorageError> {
316        self.preferences
317            .get_or_insert_with(|| crate::preferences::Session::new(&self.owner, !self.persistent))
318            .save()
319    }
320    pub fn reset_preferences(&mut self) -> Result<(), crate::storage::StorageError> {
321        self.preferences
322            .get_or_insert_with(|| crate::preferences::Session::new(&self.owner, !self.persistent))
323            .reset()
324    }
325    pub fn settings(&self) -> ControlSettings {
326        self.settings
327    }
328    pub fn set_settings(&mut self, settings: ControlSettings) -> Result<(), InputError> {
329        if !settings.valid() {
330            return Err(InputError::InvalidConfig);
331        }
332        self.settings = settings;
333        Ok(())
334    }
335    pub fn status(&self) -> ControlsStatus {
336        self.status
337    }
338    /// Single-player convenience: a global `pause` action toggles simulation.
339    /// Repeated calls in a render frame cannot replay the pause edge. Network
340    /// clients should call [`Self::sample`] directly and continue their clocks.
341    pub fn sample_play(&mut self) {
342        self.sample(!self.paused);
343        if self.pressed("pause") {
344            self.set_paused(!self.paused);
345            self.sample(!self.paused);
346        }
347    }
348    /// Set the single-player pause state immediately, discarding pending gameplay
349    /// edges/motion and touch gestures. Held buttons must release before firing.
350    /// [`Self::sample_play`] preserves this state; an explicit [`Self::sample`]
351    /// call still controls its own gameplay enablement (for example, networking).
352    pub fn set_paused(&mut self, paused: bool) {
353        if self.paused != paused {
354            self.paused = paused;
355            self.set_enabled(!paused);
356            self.map.suppress_held();
357            self.surface.clear(&mut self.map);
358        }
359    }
360    pub fn paused(&self) -> bool {
361        self.paused
362    }
363    pub fn controls_open(&self) -> bool {
364        self.open
365    }
366    pub fn gameplay_active(&self) -> bool {
367        self.enabled && self.focused && !self.open
368    }
369    pub fn touch_active(&self) -> bool {
370        self.surface.active() != 0
371    }
372    pub fn touch_seen(&self) -> bool {
373        self.touch_seen
374    }
375    /// Last device family observed by [`Self::sample`], initially keyboard/mouse.
376    /// Fresh key/button presses, nonzero mouse motion/wheel and touch starts/moves
377    /// select their family, including in menus. Only the selected controller
378    /// counts, after reconnect/focus suppression has cleared. Stick activity
379    /// must cross `max(0.25, pad_deadzone)` or change sign above that threshold;
380    /// drift, releases and unchanged holds do not steal the hints.
381    ///
382    /// A controller slot/connection epoch change or focus/overflow reset restores
383    /// the last non-controller family on the next new render-frame sample.
384    /// Discarded events are ignored. This is a presentation preference, not a
385    /// device-availability or action-enabled query; it never consumes input.
386    ///
387    /// ```
388    /// use ferravex_render::input::PlayerInput;
389    /// let mut input = PlayerInput::transient("current-device");
390    /// let initial = input.current_device();
391    /// input.sample(false); // Menus can sample without advancing gameplay.
392    /// assert_eq!(input.current_device(), initial);
393    /// ```
394    pub fn current_device(&self) -> HintDevice {
395        self.hint_device
396    }
397    fn note_hint_device(&mut self, device: HintDevice) {
398        self.hint_device = device;
399        if device != HintDevice::Gamepad {
400            self.non_pad_hint_device = device;
401        }
402    }
403    pub fn simulation_dt(&self, dt: f32) -> f32 {
404        if self.gameplay_active() && dt.is_finite() {
405            dt.clamp(0., 0.1)
406        } else {
407            0.
408        }
409    }
410    pub fn set_touch_layout(&mut self, layout: &[touch::Control]) -> Result<(), InputError> {
411        self.ensure_touch_settings();
412        if layout.len() > 16 {
413            return Err(InputError::TouchCapacity);
414        }
415        let mut controls = [touch::Control {
416            region: touch::Region::Rect(Rect::new(0., 0., 1., 1.)),
417            output: touch::Output::Button(0),
418        }; 16];
419        for (i, c) in layout.iter().enumerate() {
420            controls[i] = self.touch_settings.apply(
421                *c,
422                i,
423                vec2(screen_width().max(64.), screen_height().max(64.)),
424            )?;
425        }
426        self.surface
427            .set_layout(&controls[..layout.len()], &mut self.map)?;
428        self.raw_touch.clear();
429        self.raw_touch.extend_from_slice(layout);
430        Ok(())
431    }
432    fn ensure_touch_settings(&mut self) {
433        if self.touch_store.is_some() {
434            return;
435        }
436        let backend = if self.persistent {
437            crate::storage::PlatformStore::new()
438        } else {
439            crate::storage::PlatformStore::transient()
440        };
441        let slot = crate::storage::Slot::with_backend(
442            &self.owner,
443            "touch-layout",
444            touch::TouchLayoutSettings::default(),
445            backend,
446        )
447        .unwrap();
448        self.touch_save_failed = matches!(slot.status(), crate::storage::LoadStatus::Rejected(_));
449        self.touch_settings = *slot.value();
450        self.touch_store = Some(slot);
451    }
452    pub fn touch_customized(&self) -> bool {
453        self.touch_settings != touch::TouchLayoutSettings::default()
454    }
455    pub fn touch_settings(&self) -> touch::TouchLayoutSettings {
456        self.touch_settings
457    }
458    pub fn set_touch_settings(
459        &mut self,
460        next: touch::TouchLayoutSettings,
461    ) -> Result<(), crate::storage::StorageError> {
462        if !next.valid() {
463            return Err(crate::storage::StorageError::Invalid(
464                ferravex_play::persistence::SaveError::InvalidData,
465            ));
466        }
467        self.ensure_touch_settings();
468        self.touch_settings = next;
469        self.surface.clear(&mut self.map);
470        let count = self.raw_touch.len();
471        let mut layout = [touch::Control {
472            region: touch::Region::Rect(Rect::new(0., 0., 1., 1.)),
473            output: touch::Output::Button(0),
474        }; 16];
475        layout[..count].copy_from_slice(&self.raw_touch);
476        self.set_touch_layout(&layout[..count]).map_err(|_| {
477            crate::storage::StorageError::Invalid(
478                ferravex_play::persistence::SaveError::InvalidData,
479            )
480        })?;
481        let result = self.touch_store.as_mut().unwrap().commit(next);
482        self.touch_save_failed = result.is_err();
483        result
484    }
485    pub fn touch_stick(&self, x: u8, y: u8) -> Option<(Vec2, Vec2)> {
486        self.surface.stick(x, y)
487    }
488    pub fn value(&self, name: &str) -> f32 {
489        if self.open || !self.focused {
490            0.
491        } else {
492            self.map
493                .action_id(name)
494                .map_or(0., |id| self.map.peek(id).value)
495        }
496    }
497    pub fn held(&self, name: &str) -> bool {
498        self.value(name).abs() > 0.001
499    }
500    /// Digital edges remain pending across zero-tick render frames until taken.
501    pub fn take(&mut self, name: &str) -> Action {
502        if self.open || !self.focused {
503            return Action::default();
504        }
505        self.map
506            .action_id(name)
507            .map_or(Action::default(), |id| self.map.consume_tick(id))
508    }
509    pub fn pressed(&mut self, name: &str) -> bool {
510        self.take(name).pressed
511    }
512    /// Capture the requested actions for one simulation tick without allocating.
513    /// Share the returned array between systems: reading it does not consume
514    /// anything further. Duplicate names receive the same snapshot, and unknown
515    /// names are neutral. Only the named actions are consumed.
516    ///
517    /// Call [`Self::sample`] once per render frame, then call this once **inside**
518    /// each fixed-tick iteration. Held values persist for catch-up ticks; pending
519    /// presses, releases and relative motion appear only in the first snapshot.
520    /// Zero-tick frames retain gameplay edges. Global actions still expire at the
521    /// next sampled render frame and should usually be handled before ticking.
522    /// Like [`Self::take`], this does not poll the host or advance time. Multiple
523    /// taps before a tick coalesce into `pressed`/`released` flags, not a count.
524    ///
525    /// ```
526    /// use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput};
527    /// let mut input = PlayerInput::transient("tick-example");
528    /// input.action("jump", "Jump", ActionKind::Button,
529    ///     vec![Binding::digital(InputCode::Key(32))]).unwrap();
530    /// // In the render loop, sample even on frames with no simulation ticks.
531    /// input.sample(true);
532    /// let fixed_steps = 3;
533    /// for _ in 0..fixed_steps {
534    ///     let [jump] = input.take_tick(["jump"]);
535    ///     // Pass this same `jump` to physics, animation, and gameplay this tick.
536    ///     if jump.pressed { /* start jumping */ }
537    /// }
538    /// ```
539    pub fn take_tick<const N: usize>(&mut self, names: [&str; N]) -> [Action; N] {
540        let mut snapshot = [Action::default(); N];
541        for (i, name) in names.iter().enumerate() {
542            snapshot[i] = if let Some(prior) = names[..i].iter().position(|other| other == name) {
543                snapshot[prior]
544            } else {
545                self.take(name)
546            };
547        }
548        snapshot
549    }
550    /// Mouse/touch position with a movement-stick cursor for pointing games.
551    /// Real pointer movement takes over immediately; no synthetic mouse action
552    /// is generated. Call once per render frame using logical pixels/second.
553    pub fn cursor(&mut self, dt: f32, speed: f32) -> Vec2 {
554        let size = vec2(screen_width(), screen_height());
555        let physical = self.pointer;
556        let mut cursor = self.cursor.unwrap_or_else(|| {
557            if physical == Vec2::ZERO {
558                size * 0.5
559            } else {
560                physical
561            }
562        });
563        if physical != self.cursor_physical {
564            cursor = physical;
565            self.cursor_virtual = false;
566        }
567        self.cursor_physical = physical;
568        let movement = self.movement();
569        if dt.is_finite() && speed.is_finite() && speed >= 0. {
570            if movement.length_squared() > 0.001 && dt > 0. && speed > 0. {
571                self.cursor_virtual = true;
572            }
573            cursor += vec2(movement.x, -movement.y).clamp_length_max(1.)
574                * dt.clamp(0., 0.1)
575                * speed.min(10000.);
576        }
577        cursor = cursor.clamp(Vec2::ZERO, size);
578        self.cursor = Some(cursor);
579        cursor
580    }
581    pub fn cursor_is_virtual(&self) -> bool {
582        self.cursor_virtual
583    }
584    pub fn movement(&self) -> Vec2 {
585        vec2(
586            self.value("move_x") + self.value("move_right") - self.value("move_left"),
587            -self.value("move_y") + self.value("move_forward") - self.value("move_back"),
588        )
589        .clamp(Vec2::splat(-1.), Vec2::ONE)
590    }
591    /// Local right/down look radians. Call once per render frame before building
592    /// fixed-tick commands; the simulation receives the resulting absolute aim.
593    pub fn look(&mut self, dt: f32) -> Vec2 {
594        let dt = if dt.is_finite() {
595            dt.clamp(0., 0.25)
596        } else {
597            0.
598        };
599        let mut value = vec2(
600            self.take("look_x").value + self.value("look_rate_x") * self.settings.pad_look.x * dt,
601            self.take("look_y").value + self.value("look_rate_y") * self.settings.pad_look.y * dt,
602        );
603        if self.settings.invert_y {
604            value.y = -value.y;
605        }
606        value
607    }
608    pub fn rebind(&mut self, name: &str, bindings: Vec<Binding>) -> Result<(), InputError> {
609        let id = self.map.action_id(name).ok_or(InputError::InvalidHandle)?;
610        if bindings.iter().any(|b| reserved(b.code)) {
611            return Err(InputError::InvalidBinding);
612        }
613        self.map.try_rebind(id, bindings)
614    }
615    pub fn export_config(&self) -> Result<Vec<u8>, InputError> {
616        self.map.encode_config(self.settings)
617    }
618    pub fn import_config(&mut self, bytes: &[u8]) -> Result<AppliedConfig, InputError> {
619        // Reserved host controls must remain reachable after importing a profile.
620        let config = decode_config(bytes)?;
621        if config
622            .actions
623            .iter()
624            .any(|a| a.bindings.iter().any(|b| reserved(b.code)))
625        {
626            return Err(InputError::InvalidBinding);
627        }
628        let applied = self.map.apply_config(bytes)?;
629        self.settings = applied.settings;
630        self.map.suppress_held();
631        self.status = ControlsStatus::Loaded {
632            unknown: applied.unknown,
633        };
634        Ok(applied)
635    }
636    pub fn save(&mut self) -> bool {
637        if !self.persistent {
638            self.status = ControlsStatus::Transient;
639            return false;
640        }
641        match self.export_config() {
642            Err(e) => {
643                self.status = ControlsStatus::Invalid(e);
644                false
645            }
646            Ok(bytes) => match storage::save(&self.owner, &bytes) {
647                Ok(()) => {
648                    self.status = ControlsStatus::Saved;
649                    true
650                }
651                Err(e) => {
652                    self.status = ControlsStatus::Storage(e);
653                    false
654                }
655            },
656        }
657    }
658    pub fn load(&mut self) {
659        if !self.persistent {
660            self.loaded = true;
661            self.status = ControlsStatus::Transient;
662            return;
663        }
664        self.loaded = true;
665        match storage::load(&self.owner) {
666            Ok(Some(bytes)) => {
667                if let Err(e) = self.import_config(&bytes) {
668                    self.status = ControlsStatus::Invalid(e);
669                }
670            }
671            Ok(None) => self.status = ControlsStatus::Defaults,
672            Err(e) => self.status = ControlsStatus::Storage(e),
673        }
674    }
675    pub fn reset_defaults(&mut self) {
676        for info in &self.actions {
677            self.map
678                .try_rebind(info.id, info.defaults.to_vec())
679                .expect("validated defaults");
680        }
681        self.settings = ControlSettings::default();
682        self.map.suppress_held();
683        self.save();
684    }
685    pub fn set_controls_open(&mut self, open: bool) {
686        // A browser modal owns the pause until it closes, including for pads/F2.
687        if self.external_details && !open {
688            return;
689        }
690        if self.open == open {
691            return;
692        }
693        self.open = open;
694        self.capture = None;
695        self.map.suppress_held();
696        self.surface.clear(&mut self.map);
697        if open {
698            crate::audio::suspend();
699            self.prior_cursor = crate::read(|s| (s.grab, s.visible));
700            crate::set_cursor_grab(false);
701            crate::show_mouse(true);
702        } else {
703            crate::set_cursor_grab(self.prior_cursor.0);
704            crate::show_mouse(self.prior_cursor.1);
705        }
706        crate::edit(|s| s.controls_open = open);
707    }
708    pub fn begin_capture(&mut self, name: &str, device: CaptureDevice) -> Result<(), InputError> {
709        let action = self
710            .actions
711            .iter()
712            .position(|a| a.name == name)
713            .ok_or(InputError::InvalidHandle)?;
714        if self.actions[action].kind == ActionKind::Delta && device == CaptureDevice::Gamepad {
715            return Err(InputError::InvalidBinding);
716        }
717        self.capture = Some(Capture { action, device });
718        Ok(())
719    }
720    fn capture_value(&mut self, code: InputCode, value: f32) -> bool {
721        let Some(capture) = self.capture else {
722            return false;
723        };
724        let info = &self.actions[capture.action];
725        let device = match code {
726            InputCode::PadAxis(_) | InputCode::PadButton(_) => CaptureDevice::Gamepad,
727            InputCode::Touch(_) | InputCode::TouchDelta(_) => return false,
728            _ => CaptureDevice::KeyboardMouse,
729        };
730        if device != capture.device || code.is_delta() != (info.kind == ActionKind::Delta) {
731            return false;
732        }
733        if reserved(code) || code == InputCode::Key(0xff1b) {
734            return false;
735        }
736        if code.is_delta() {
737            if value.abs() < 0.0001 || self.map.physical_value(InputCode::Mouse(1)) != 0. {
738                return false;
739            }
740        } else if value.abs() < 0.65 || self.map.physical_value(code).abs() >= 0.5 {
741            return false;
742        }
743        let mut bindings: Vec<_> = self
744            .map
745            .bindings(info.id)
746            .unwrap()
747            .iter()
748            .copied()
749            .filter(|b| match capture.device {
750                CaptureDevice::Gamepad => {
751                    !matches!(b.code, InputCode::PadAxis(_) | InputCode::PadButton(_))
752                }
753                CaptureDevice::KeyboardMouse => !matches!(
754                    b.code,
755                    InputCode::Key(_)
756                        | InputCode::Mouse(_)
757                        | InputCode::MouseDelta(_)
758                        | InputCode::Wheel(_)
759                ),
760            })
761            .collect();
762        bindings.push(Binding {
763            code,
764            scale: value.signum(),
765            deadzone: 0.,
766        });
767        match self.map.try_rebind(info.id, bindings) {
768            Ok(()) => {
769                self.capture = None;
770                self.ui_block = true;
771                true
772            }
773            Err(e) => {
774                self.status = ControlsStatus::Invalid(e);
775                false
776            }
777        }
778    }
779    fn axis_value(&mut self, axis: usize, value: f32) {
780        if self.pad_axes_suppressed & (1 << axis) != 0 {
781            if value.abs() <= 0.25 {
782                self.pad_axes_suppressed &= !(1 << axis);
783            } else {
784                self.pad_axes[axis] = 0.;
785                return;
786            }
787        }
788        self.pad_axes[axis] = value;
789    }
790    fn feed_axes(&mut self) {
791        let left = self
792            .settings
793            .stick(vec2(self.pad_axes[0], self.pad_axes[1]));
794        let right = self
795            .settings
796            .stick(vec2(self.pad_axes[2], self.pad_axes[3]));
797        for (axis, value) in [left.x, left.y, right.x, right.y].into_iter().enumerate() {
798            self.map.feed(InputCode::PadAxis(axis as u8), value);
799        }
800        for axis in 4..16 {
801            self.map
802                .feed(InputCode::PadAxis(axis as u8), self.pad_axes[axis]);
803        }
804    }
805    fn set_enabled(&mut self, enabled: bool) {
806        if self.enabled != enabled {
807            self.enabled = enabled;
808            // A gesture begun before or during a pause must not resume a drag.
809            self.surface.clear(&mut self.map);
810        }
811        self.map
812            .set_context(self.gameplay_active().then_some(self.gameplay))
813            .unwrap();
814    }
815    /// Sample the host event journal at most once per render frame. Repeated
816    /// calls may change gameplay enablement, and observe focus/modal changes,
817    /// but never replay the frame's events. Call after the host pumps events.
818    ///
819    /// `false` disables gameplay actions while leaving global menu actions
820    /// available. Disabling clears queued gameplay input and touch gestures;
821    /// buttons held during the pause must release before firing on resume.
822    /// Consume gameplay edges with [`Self::take_tick`] only when a tick runs.
823    pub fn sample(&mut self, enabled: bool) {
824        crate::edit(|s| s.input_enabled = true);
825        if !self.loaded {
826            self.load();
827        }
828        self.ensure_touch_settings();
829        let (frame, epoch, focused, overflow, pads, requested, size, pointer) = crate::read(|s| {
830            (
831                s.frame,
832                s.input.focus_epoch,
833                s.input.focused,
834                s.input.overflow,
835                s.input.pads,
836                s.input.settings_requested,
837                vec2(s.w as f32, s.h as f32),
838                s.mouse,
839            )
840        });
841        // Lifecycle changes take effect even after this frame was sampled. In
842        // particular a blur must not leave cached movement or button edges live.
843        if epoch != self.focus_epoch || !focused || overflow {
844            self.map.lose_focus();
845            self.surface.clear(&mut self.map);
846            self.pad_epoch = u32::MAX;
847        }
848        self.focus_epoch = epoch;
849        self.focused = focused && !overflow;
850        let external = crate::read(|s| s.details_open);
851        if external != self.external_details {
852            self.external_details = external;
853            self.set_controls_open(external);
854        }
855        self.set_enabled(enabled);
856        if self.last_frame == Some(frame) {
857            return;
858        }
859        self.last_frame = Some(frame);
860        let mut events = [PlatformEvent::None; MAX_EVENTS];
861        crate::read(|s| {
862            let values = s.input.events();
863            events[..values.len()].copy_from_slice(values);
864        });
865        if self.preferences.is_none() {
866            self.preferences = Some(crate::preferences::Session::new(
867                &self.owner,
868                !self.persistent,
869            ));
870        }
871        if self.persistent {
872            self.preferences.as_mut().unwrap().sync_audio();
873        }
874        if let Some(pending) = crate::edit(|s| s.pending_presentation.take()) {
875            let current = self.preferences();
876            let next = crate::preferences::Preferences {
877                quality: pending.quality,
878                look: pending.look,
879                resolution: pending.resolution,
880                shadows: pending.shadows,
881                lights: pending.lights,
882                adaptive: pending.adaptive,
883                ..current
884            };
885            let failed = self.set_preferences(next).is_err();
886            crate::edit(|s| s.details_error = failed);
887        }
888        crate::edit(|s| s.details_error = self.preferences_error().is_some());
889        self.ui_click = false;
890        self.ui_tap_len = 0;
891        self.ui_block = false;
892        self.ui_up = false;
893        self.ui_down = false;
894        self.ui_accept = false;
895        self.pointer = pointer;
896        // Global menu actions are render-frame edges. Gameplay edges remain
897        // buffered until a fixed simulation tick explicitly consumes them.
898        for info in &self.actions {
899            if info.global {
900                self.map.consume_tick(info.id);
901            }
902        }
903        if requested {
904            self.set_controls_open(!self.open);
905        }
906        self.map
907            .set_context(self.gameplay_active().then_some(self.gameplay))
908            .unwrap();
909        let selected = self.settings.gamepad as usize;
910        let pad = pads[selected];
911        let fresh = selected != self.selected_pad || pad.epoch != self.pad_epoch;
912        if fresh {
913            if self.hint_device == HintDevice::Gamepad {
914                self.hint_device = self.non_pad_hint_device;
915            }
916            self.selected_pad = selected;
917            self.pad_epoch = pad.epoch;
918            self.pad_axes = [0.; 16];
919            self.pad_axes_suppressed = 0;
920            self.pad_buttons_suppressed = 0;
921            for (i, &v) in pad.axes.iter().enumerate() {
922                if v.abs() > 0.25 {
923                    self.pad_axes_suppressed |= 1 << i;
924                }
925                self.map.feed(InputCode::PadAxis(i as u8), 0.);
926            }
927            for (i, &v) in pad.buttons.iter().enumerate() {
928                if v >= 0.5 {
929                    self.pad_buttons_suppressed |= 1 << i;
930                }
931                self.map.feed(InputCode::PadButton(i as u8), 0.);
932            }
933        }
934        let mut changed = false;
935        for event in events {
936            if event == PlatformEvent::None {
937                break;
938            }
939            if !self.focused {
940                continue;
941            }
942            match event {
943                PlatformEvent::Value(InputCode::Key(key), value)
944                    if value >= 0.5 && (key == 0xffbf || self.open && key == 0xff1b) =>
945                {
946                    let code = InputCode::Key(key);
947                    let pressed = self.map.physical_value(code) < 0.5;
948                    self.map.feed(code, value);
949                    if !pressed {
950                        continue;
951                    }
952                    self.note_hint_device(HintDevice::KeyboardMouse);
953                    if key == 0xff1b && self.capture.is_some() {
954                        self.capture = None;
955                        self.ui_block = true;
956                    } else {
957                        self.set_controls_open(!self.open);
958                    }
959                    self.map
960                        .set_context(self.gameplay_active().then_some(self.gameplay))
961                        .unwrap();
962                }
963                PlatformEvent::Value(code, value) => {
964                    let pressed = value >= 0.5 && self.map.physical_value(code) < 0.5;
965                    if code.valid()
966                        && HintDevice::for_code(code) == HintDevice::KeyboardMouse
967                        && value.is_finite()
968                        && (pressed || code.is_delta() && value != 0.)
969                    {
970                        self.note_hint_device(HintDevice::for_code(code));
971                    }
972                    changed |= self.open && self.capture_value(code, value);
973                    if self.open && self.capture.is_none() && pressed {
974                        match code {
975                            InputCode::Key(0xff52) if value > 0.5 => self.ui_up = true,
976                            InputCode::Key(0xff54) if value > 0.5 => self.ui_down = true,
977                            InputCode::Key(0xff09) if value > 0.5 => {
978                                if self.map.physical_value(InputCode::Key(0xffe1)) > 0.5
979                                    || self.map.physical_value(InputCode::Key(0xffe2)) > 0.5
980                                {
981                                    self.ui_up = true;
982                                } else {
983                                    self.ui_down = true;
984                                }
985                            }
986                            InputCode::Key(0xff0d) if value > 0.5 => self.ui_accept = true,
987                            _ => {}
988                        }
989                    }
990                    if code == InputCode::Mouse(1) && pressed {
991                        self.ui_click = true;
992                    }
993                    self.map.feed(code, value);
994                }
995                PlatformEvent::MouseMotion(delta) => {
996                    if delta.is_finite() && delta != Vec2::ZERO {
997                        self.note_hint_device(HintDevice::KeyboardMouse);
998                    }
999                    if !self.open
1000                        && self
1001                            .mouse_look_button
1002                            .is_some_and(|b| self.map.physical_value(InputCode::Mouse(b)) < 0.5)
1003                    {
1004                        continue;
1005                    }
1006                    let delta = delta / size * self.settings.mouse_sensitivity;
1007                    changed |= self.open
1008                        && (self.capture_value(InputCode::MouseDelta(0), delta.x)
1009                            || self.capture_value(InputCode::MouseDelta(1), delta.y));
1010                    self.map.feed_delta(InputCode::MouseDelta(0), delta.x);
1011                    self.map.feed_delta(InputCode::MouseDelta(1), delta.y);
1012                }
1013                PlatformEvent::Touch(event) => {
1014                    self.touch_seen = true;
1015                    if matches!(event.phase, touch::Phase::Start | touch::Phase::Move)
1016                        && event.position.is_finite()
1017                        && event.position.abs().max_element() <= 1e6
1018                    {
1019                        self.note_hint_device(HintDevice::Touch);
1020                    }
1021                    if event.phase == touch::Phase::Start && self.ui_tap_len < self.ui_taps.len() {
1022                        self.ui_taps[self.ui_tap_len] = event.position;
1023                        self.ui_tap_len += 1;
1024                    }
1025                    if !self.open
1026                        && let Err(e) = self.surface.handle_scaled(
1027                            event,
1028                            &mut self.map,
1029                            Vec2::splat(self.settings.touch_sensitivity),
1030                        )
1031                    {
1032                        self.surface.clear(&mut self.map);
1033                        self.status = ControlsStatus::Invalid(e);
1034                    }
1035                }
1036                PlatformEvent::Pad { index, code, value }
1037                    if index as usize == selected && pad.connected && !fresh =>
1038                {
1039                    match code {
1040                        InputCode::PadAxis(axis) => {
1041                            let previous = self.pad_axes[axis as usize];
1042                            self.axis_value(axis as usize, value);
1043                            let threshold = self.settings.pad_deadzone.max(0.25);
1044                            if self.pad_axes_suppressed & (1 << axis) == 0
1045                                && value.abs() > threshold
1046                                && (previous.abs() <= threshold
1047                                    || previous.signum() != value.signum())
1048                            {
1049                                self.note_hint_device(HintDevice::Gamepad);
1050                            }
1051                            changed |= self.open
1052                                && self.pad_axes_suppressed & (1 << axis) == 0
1053                                && self.capture_value(code, self.pad_axes[axis as usize]);
1054                            self.feed_axes();
1055                        }
1056                        InputCode::PadButton(button) => {
1057                            if value < 0.5 {
1058                                self.pad_buttons_suppressed &= !(1 << button);
1059                            }
1060                            if self.pad_buttons_suppressed & (1 << button) != 0 {
1061                                continue;
1062                            }
1063                            if value >= 0.5 && self.map.physical_value(code) < 0.5 {
1064                                self.note_hint_device(HintDevice::Gamepad);
1065                            }
1066                            if button == 16
1067                                && value >= 0.5
1068                                && !fresh
1069                                && self.map.physical_value(code) < 0.5
1070                            {
1071                                self.map.feed(code, value);
1072                                self.set_controls_open(!self.open);
1073                                self.map
1074                                    .set_context(self.gameplay_active().then_some(self.gameplay))
1075                                    .unwrap();
1076                                continue;
1077                            }
1078                            changed |= self.open && self.capture_value(code, value);
1079                            if self.open
1080                                && self.capture.is_none()
1081                                && value > 0.5
1082                                && self.map.physical_value(code) < 0.5
1083                            {
1084                                match button {
1085                                    12 => self.ui_up = true,
1086                                    13 => self.ui_down = true,
1087                                    0 => self.ui_accept = true,
1088                                    _ => {}
1089                                }
1090                            }
1091                            self.map.feed(code, value);
1092                        }
1093                        _ => {}
1094                    }
1095                }
1096                _ => {}
1097            }
1098        }
1099        if self.focused && pad.connected {
1100            for (i, &v) in pad.axes.iter().enumerate() {
1101                self.axis_value(i, v);
1102            }
1103            self.feed_axes();
1104            for (i, &v) in pad.buttons.iter().enumerate() {
1105                if v < 0.5 {
1106                    self.pad_buttons_suppressed &= !(1 << i);
1107                }
1108                self.map.feed(
1109                    InputCode::PadButton(i as u8),
1110                    if self.pad_buttons_suppressed & (1 << i) != 0 {
1111                        0.
1112                    } else {
1113                        v
1114                    },
1115                );
1116            }
1117        }
1118        if changed {
1119            self.save();
1120        }
1121    }
1122}
1123
1124fn reserved(code: InputCode) -> bool {
1125    matches!(code, InputCode::Key(0xffbf) | InputCode::PadButton(16))
1126}