Skip to main content

sim_logic/application/
input.rs

1//! Typed, platform-independent keyboard and pointer input.
2
3#[path = "input/control.rs"]
4mod control;
5use control::cancelled_controls;
6pub use control::{InputCancellationReason, InputControl};
7
8#[path = "input/pointer.rs"]
9mod pointer;
10
11use pointer::{ALL_MOUSE_BUTTONS, mouse_button_index};
12pub use pointer::{DuplicateMouseBinding, MouseButton, PointerSample, PointerSampleError};
13
14#[path = "input/motion.rs"]
15mod motion;
16pub use motion::{RelativePointerMotion, RelativePointerMotionError};
17#[path = "input/scroll.rs"]
18mod scroll;
19pub use scroll::{FrameInputEvent, PointerScrollEvent, ScrollDelta, ScrollDeltaError, ScrollUnit};
20#[path = "input/capture.rs"]
21mod capture;
22pub use capture::{PointerCapture, PointerCaptureStatus};
23
24#[cfg(test)]
25#[path = "input/cancellation_tests.rs"]
26mod cancellation_tests;
27#[cfg(test)]
28#[path = "input/pointer_tests.rs"]
29mod pointer_tests;
30#[cfg(test)]
31#[path = "input/scroll_tests.rs"]
32mod scroll_tests;
33
34use std::{
35    collections::{HashMap, HashSet},
36    error::Error,
37    fmt,
38    hash::Hash,
39};
40
41use bevy_ecs::{
42    prelude::{Res, Resource},
43    system::SystemParam,
44};
45use sim_engine::Vec2;
46
47use crate::identity::{ApplicationId, TransitionIntentToken, WorldGeneration};
48
49/// Default maximum number of physical input events accepted in one frame and
50/// logical edges generated per frame or retained for the next FixedUpdate delivery.
51/// Frame-only wheel storage has the same limit; wheel events also count toward
52/// the physical event count, including zero displacements.
53pub const DEFAULT_INPUT_EVENT_LIMIT: usize = 1_024;
54
55/// Marker contract for values used as logical input actions.
56///
57/// Actions are copied into immutable frame and fixed-update snapshots. Equality
58/// and hashing are used only for lookup; iteration order is never part of the
59/// input contract.
60pub trait Action: Copy + Eq + Hash + Send + Sync + 'static {}
61
62impl<T> Action for T where T: Copy + Eq + Hash + Send + Sync + 'static {}
63
64/// Four logical actions sampled as a digital two-dimensional axis.
65///
66/// The descriptor contains no input state and is independent from physical
67/// key bindings. Reusing one action in several slots is allowed: each slot is
68/// sampled independently and opposite slots cancel through subtraction.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub struct DigitalAxis2d<A: Action> {
71    negative_x: A,
72    positive_x: A,
73    negative_y: A,
74    positive_y: A,
75}
76
77impl<A: Action> DigitalAxis2d<A> {
78    /// Creates a descriptor in negative-x, positive-x, negative-y,
79    /// positive-y order.
80    ///
81    /// For conventional world movement this normally receives left, right,
82    /// down, and up actions. The mapping is infallible and may contain the same
83    /// action more than once.
84    pub const fn new(negative_x: A, positive_x: A, negative_y: A, positive_y: A) -> Self {
85        Self {
86            negative_x,
87            positive_x,
88            negative_y,
89            positive_y,
90        }
91    }
92
93    /// Returns the action contributing `-1.0` to the x component while held.
94    pub const fn negative_x(self) -> A {
95        self.negative_x
96    }
97
98    /// Returns the action contributing `1.0` to the x component while held.
99    pub const fn positive_x(self) -> A {
100        self.positive_x
101    }
102
103    /// Returns the action contributing `-1.0` to the y component while held.
104    pub const fn negative_y(self) -> A {
105        self.negative_y
106    }
107
108    /// Returns the action contributing `1.0` to the y component while held.
109    pub const fn positive_y(self) -> A {
110        self.positive_y
111    }
112}
113
114#[path = "input/keyboard.rs"]
115mod keyboard;
116pub use keyboard::PhysicalKeyCode;
117pub(crate) use keyboard::{ALL_PHYSICAL_KEYS, SUPPORTED_PHYSICAL_KEY_COUNT, physical_key_index};
118
119/// The state carried by a physical button event.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121pub enum ButtonState {
122    /// The key or mouse button transitioned from up to down.
123    Pressed,
124    /// The key or mouse button transitioned from down to up.
125    Released,
126}
127
128/// One platform-independent physical input event.
129///
130/// Repeated presses of an already-held key or mouse button, and repeated
131/// releases of one already up, do not create logical edges. Motion updates
132/// continuous state without creating edges. Event order determines the pointer
133/// sample captured by each mouse edge.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135pub enum InputEvent {
136    /// A physical keyboard state change.
137    Key {
138        /// The physical location of the key.
139        key: PhysicalKeyCode,
140        /// The reported button state.
141        state: ButtonState,
142    },
143    /// Updates the continuous pointer without generating a logical action edge.
144    PointerMoved {
145        /// Finite logical coordinates and the viewport at this point in event order.
146        sample: PointerSample,
147    },
148    /// Adds raw displacement to this frame's relative motion without changing
149    /// the absolute pointer or generating action edges. Not retained for fixed
150    /// ticks. FocusLost clears motion and ignores later motion in the same batch.
151    RelativePointerMotion {
152        /// Validated raw device displacement, independent of the viewport/DPI.
153        motion: RelativePointerMotion,
154    },
155    /// One wheel occurrence with explicit line or logical-pixel units. Captures
156    /// the latest pointer in event order; no binding, fixed replay, or token.
157    /// FocusLost discards all wheel events in the same accepted batch.
158    MouseWheel {
159        /// Finite per-event displacement; separate occurrences are not combined.
160        delta: ScrollDelta,
161    },
162    /// A physical mouse-button state change, using the latest pointer sample.
163    MouseButton {
164        /// The physical mouse button.
165        button: MouseButton,
166        /// The reported button state.
167        state: ButtonState,
168    },
169    /// Clears the pointer and releases held mouse buttons in Left/Right/Middle
170    /// order. Synthesized releases have no pointer sample. Keyboard state is
171    /// unchanged. The generated releases have a PointerLeft cancellation reason.
172    PointerLeft,
173    /// Clears the pointer and cancels held mapped keyboard controls in the
174    /// supported key catalog order, then mouse controls in Left/Right/Middle
175    /// order. Generated releases have a FocusLost reason and no pointer sample.
176    ///
177    /// One event can create many logical edges; all normal frame and retained
178    /// limits apply atomically. Later events in the same batch are still read.
179    /// This is not a persistent focus-state flag or an input-routing layer.
180    FocusLost,
181}
182
183impl InputEvent {
184    /// Creates a physical keyboard event for the headless or desktop adapter.
185    pub const fn key(key: PhysicalKeyCode, state: ButtonState) -> Self {
186        Self::Key { key, state }
187    }
188
189    /// Creates an ordered pointer-position update, independent of bindings.
190    pub const fn pointer_moved(sample: PointerSample) -> Self {
191        Self::PointerMoved { sample }
192    }
193
194    /// Supplies validated raw displacement; headless injection needs no OS capture.
195    pub const fn relative_pointer_motion(motion: RelativePointerMotion) -> Self {
196        Self::RelativePointerMotion { motion }
197    }
198
199    /// Supplies a validated, ordered wheel event for frame-update consumers.
200    pub const fn mouse_wheel(delta: ScrollDelta) -> Self {
201        Self::MouseWheel { delta }
202    }
203
204    /// Creates a mouse-button event. Its logical edge captures the latest
205    /// preceding pointer sample, or None when no position is known.
206    pub const fn mouse_button(button: MouseButton, state: ButtonState) -> Self {
207        Self::MouseButton { button, state }
208    }
209}
210
211/// Rejection returned when one physical key is bound more than once.
212///
213/// Several different keys may intentionally map to the same action. A single
214/// physical key has exactly one action in the first vertical slice.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct DuplicateKeyBinding {
217    key: PhysicalKeyCode,
218}
219
220impl DuplicateKeyBinding {
221    /// Returns the physical key whose existing binding was preserved.
222    pub const fn key(self) -> PhysicalKeyCode {
223        self.key
224    }
225}
226
227impl fmt::Display for DuplicateKeyBinding {
228    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
229        write!(formatter, "physical key {:?} is already bound", self.key)
230    }
231}
232
233impl Error for DuplicateKeyBinding {}
234
235#[derive(Debug, Clone)]
236pub(crate) struct ActionBindings<A: Action> {
237    by_key: [Option<A>; SUPPORTED_PHYSICAL_KEY_COUNT],
238    by_mouse: [Option<A>; ALL_MOUSE_BUTTONS.len()],
239}
240
241impl<A: Action> Default for ActionBindings<A> {
242    fn default() -> Self {
243        Self {
244            by_key: [None; SUPPORTED_PHYSICAL_KEY_COUNT],
245            by_mouse: [None; ALL_MOUSE_BUTTONS.len()],
246        }
247    }
248}
249
250impl<A: Action> ActionBindings<A> {
251    pub(crate) fn new() -> Self {
252        Self::default()
253    }
254
255    pub(crate) fn bind_mouse_button(
256        &mut self,
257        button: MouseButton,
258        action: A,
259    ) -> Result<&mut Self, DuplicateMouseBinding> {
260        let slot = &mut self.by_mouse[mouse_button_index(button)];
261        if slot.is_some() {
262            return Err(DuplicateMouseBinding { button });
263        }
264        *slot = Some(action);
265        Ok(self)
266    }
267
268    fn mouse_action_for(&self, button: MouseButton) -> Option<A> {
269        self.by_mouse[mouse_button_index(button)]
270    }
271
272    fn control_action_for(&self, control: InputControl) -> Option<A> {
273        match control {
274            InputControl::Key(key) => self.action_for(key),
275            InputControl::MouseButton(button) => self.mouse_action_for(button),
276        }
277    }
278
279    /// Binds one physical key without replacing an existing binding.
280    ///
281    /// On failure the binding table is unchanged.
282    pub(crate) fn bind(
283        &mut self,
284        key: PhysicalKeyCode,
285        action: A,
286    ) -> Result<&mut Self, DuplicateKeyBinding> {
287        self.bind_all([(key, action)])
288    }
289
290    /// Atomically binds W/A/S/D to the matching slots of one logical axis.
291    pub(crate) fn bind_wasd(
292        &mut self,
293        axis: DigitalAxis2d<A>,
294    ) -> Result<&mut Self, DuplicateKeyBinding> {
295        self.bind_all([
296            (PhysicalKeyCode::KeyW, axis.positive_y()),
297            (PhysicalKeyCode::KeyA, axis.negative_x()),
298            (PhysicalKeyCode::KeyS, axis.negative_y()),
299            (PhysicalKeyCode::KeyD, axis.positive_x()),
300        ])
301    }
302
303    /// Atomically binds the arrow keys to the matching slots of one axis.
304    pub(crate) fn bind_arrows(
305        &mut self,
306        axis: DigitalAxis2d<A>,
307    ) -> Result<&mut Self, DuplicateKeyBinding> {
308        self.bind_all([
309            (PhysicalKeyCode::ArrowLeft, axis.negative_x()),
310            (PhysicalKeyCode::ArrowRight, axis.positive_x()),
311            (PhysicalKeyCode::ArrowDown, axis.negative_y()),
312            (PhysicalKeyCode::ArrowUp, axis.positive_y()),
313        ])
314    }
315
316    /// Atomically binds both W/A/S/D and the arrow keys to one axis.
317    pub(crate) fn bind_wasd_and_arrows(
318        &mut self,
319        axis: DigitalAxis2d<A>,
320    ) -> Result<&mut Self, DuplicateKeyBinding> {
321        self.bind_all([
322            (PhysicalKeyCode::KeyW, axis.positive_y()),
323            (PhysicalKeyCode::KeyA, axis.negative_x()),
324            (PhysicalKeyCode::KeyS, axis.negative_y()),
325            (PhysicalKeyCode::KeyD, axis.positive_x()),
326            (PhysicalKeyCode::ArrowLeft, axis.negative_x()),
327            (PhysicalKeyCode::ArrowRight, axis.positive_x()),
328            (PhysicalKeyCode::ArrowDown, axis.negative_y()),
329            (PhysicalKeyCode::ArrowUp, axis.positive_y()),
330        ])
331    }
332
333    fn bind_all<const N: usize>(
334        &mut self,
335        bindings: [(PhysicalKeyCode, A); N],
336    ) -> Result<&mut Self, DuplicateKeyBinding> {
337        for (key, _) in &bindings {
338            if self.action_for(*key).is_some() {
339                return Err(DuplicateKeyBinding { key: *key });
340            }
341        }
342        for (key, action) in bindings {
343            self.by_key[physical_key_index(key)] = Some(action);
344        }
345        Ok(self)
346    }
347
348    fn action_for(&self, key: PhysicalKeyCode) -> Option<A> {
349        self.by_key[physical_key_index(key)]
350    }
351}
352
353/// Failure to configure or collect application input.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum InputCollectionError {
356    /// Summing relative pointer events would exceed their numeric frame limit.
357    RelativeMotion(RelativePointerMotionError),
358    /// The shared physical-event, generated-edge, and retained-edge limit is zero.
359    ZeroEventLimit,
360    /// The runtime could not reserve the bounded input storage required by the
361    /// configured limit.
362    StorageAllocationFailed {
363        /// Configured physical-event, generated-edge, and retained-edge limit.
364        limit: usize,
365    },
366    /// The supplied frame exceeds its physical event budget.
367    EventLimitExceeded {
368        /// Maximum accepted event count.
369        limit: usize,
370        /// Event count supplied for the rejected frame.
371        received: usize,
372    },
373    /// This frame would generate too many logical edges, including releases
374    /// synthesized by PointerLeft or FocusLost. Checked even when fixed updates
375    /// are paused.
376    FrameEdgeLimitExceeded {
377        /// Maximum generated frame-input edge count.
378        limit: usize,
379        /// New logical edges produced by the rejected frame.
380        incoming: usize,
381    },
382    /// Retaining this frame's logical edges for FixedUpdate would exceed the
383    /// shared input event limit.
384    RetainedFixedEdgeLimitExceeded {
385        /// Maximum retained fixed-input edge count.
386        limit: usize,
387        /// Edges already waiting for their first FixedUpdate delivery.
388        retained: usize,
389        /// New logical edges produced by the rejected frame.
390        incoming: usize,
391    },
392    /// The runtime cannot issue enough never-reused occurrence numbers.
393    OccurrenceIdentityExhausted,
394}
395
396impl fmt::Display for InputCollectionError {
397    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
398        match self {
399            Self::RelativeMotion(error) => {
400                write!(formatter, "relative input collection failed: {error}")
401            }
402            Self::ZeroEventLimit => {
403                formatter.write_str("the input event and retained-edge limit must be positive")
404            }
405            Self::StorageAllocationFailed { limit } => write!(
406                formatter,
407                "failed to reserve bounded input storage for the configured limit of {limit}"
408            ),
409            Self::EventLimitExceeded { limit, received } => write!(
410                formatter,
411                "input frame contains {received} physical events, exceeding the limit of {limit}"
412            ),
413            Self::FrameEdgeLimitExceeded { limit, incoming } => write!(
414                formatter,
415                "input frame generates {incoming} logical edges, exceeding the limit of {limit}"
416            ),
417            Self::RetainedFixedEdgeLimitExceeded {
418                limit,
419                retained,
420                incoming,
421            } => write!(
422                formatter,
423                "fixed input retains {retained} edges and cannot accept {incoming} more without exceeding the limit of {limit}"
424            ),
425            Self::OccurrenceIdentityExhausted => {
426                formatter.write_str("input occurrence identity space is exhausted")
427            }
428        }
429    }
430}
431
432impl Error for InputCollectionError {}
433
434/// One logical action edge and its causal transition token.
435///
436/// An edge belongs to one physical occurrence. Different keys or mouse buttons
437/// mapped to the same action remain separate entries in physical event order.
438/// Pointer leave synthesizes releases in Left/Right/Middle order. Focus loss
439/// releases keys in portable catalog order, then mouse buttons in that order.
440#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
441pub struct ActionEdge<A: Action> {
442    action: A,
443    state: ButtonState,
444    intent: TransitionIntentToken,
445    pointer: Option<PointerSample>,
446    control: InputControl,
447    cancellation: Option<InputCancellationReason>,
448    ordinal: usize,
449}
450
451impl<A: Action> ActionEdge<A> {
452    /// Returns the physical control associated with this occurrence, even if
453    /// several controls share its action or its pointer position is unknown.
454    /// The original value is preserved across frame and delayed fixed delivery.
455    pub const fn control(self) -> InputControl {
456        self.control
457    }
458
459    /// Returns why this release was synthesized, or None for ordinary input.
460    /// Presses always return None. A mouse release without a known pointer is
461    /// not necessarily cancelled; use this method rather than guessing from
462    /// pointer absence. Cancellation does not erase an earlier press occurrence.
463    pub const fn cancellation_reason(self) -> Option<InputCancellationReason> {
464        self.cancellation
465    }
466
467    /// Returns whether this is a cancellation release rather than an ordinary
468    /// physical release. Commit-on-release interactions should normally ignore
469    /// cancelled releases while still clearing their own held/drag state.
470    pub const fn is_cancelled(self) -> bool {
471        self.cancellation.is_some()
472    }
473
474    /// Returns this mouse occurrence's event-time pointer sample. Keyboard
475    /// edges, cancellation releases, and mouse edges without a known
476    /// position return None. Later movement does not change this value.
477    pub const fn pointer(self) -> Option<PointerSample> {
478        self.pointer
479    }
480    /// Returns the logical action associated with this occurrence.
481    pub const fn action(self) -> A {
482        self.action
483    }
484
485    /// Returns whether this occurrence pressed or released its physical control.
486    pub const fn state(self) -> ButtonState {
487        self.state
488    }
489
490    /// Returns the runtime-issued token shared by frame and fixed delivery.
491    ///
492    /// The token is valid only while the underlying occurrence remains live in
493    /// one of those delivery queues.
494    pub const fn intent(self) -> TransitionIntentToken {
495        self.intent
496    }
497}
498
499/// Read-only logical input exposed to FrameUpdate systems.
500///
501/// Its edges contain only physical occurrences collected for the current
502/// application frame. Held state reflects the final state after all accepted
503/// events in that frame were processed.
504#[derive(Debug, Clone, Resource)]
505pub(crate) struct FrameInputState<A: Action> {
506    held: HashSet<A>,
507    edges: Vec<ActionEdge<A>>,
508    scrolls: Vec<PointerScrollEvent>,
509    pointer: Option<PointerSample>,
510    relative_motion: RelativePointerMotion,
511    focus_lost: bool,
512}
513
514impl<A: Action> FrameInputState<A> {
515    /// Returns whether at least one bound key or mouse button for `action` is held.
516    pub fn held(&self, action: A) -> bool {
517        self.held.contains(&action)
518    }
519
520    fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
521        sample_digital_axis(axis, |action| self.held(action))
522    }
523
524    /// Iterates over every press occurrence for `action` in event order.
525    pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
526        self.edges
527            .iter()
528            .copied()
529            .filter(move |edge| edge.action == action && edge.state == ButtonState::Pressed)
530    }
531
532    /// Iterates over every release occurrence for `action` in event order.
533    pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
534        self.edges
535            .iter()
536            .copied()
537            .filter(move |edge| edge.action == action && edge.state == ButtonState::Released)
538    }
539
540    pub(crate) fn empty() -> Self {
541        Self {
542            held: HashSet::new(),
543            edges: Vec::new(),
544            scrolls: Vec::new(),
545            pointer: None,
546            relative_motion: RelativePointerMotion::ZERO,
547            focus_lost: false,
548        }
549    }
550
551    pub(crate) fn clear_reusing_storage(&mut self) {
552        self.held.clear();
553        self.edges.clear();
554        self.scrolls.clear();
555        self.pointer = None;
556        self.relative_motion = RelativePointerMotion::ZERO;
557        self.focus_lost = false;
558    }
559
560    fn replace_from(&mut self, held_action_counts: &HashMap<A, usize>, edges: &[ActionEdge<A>]) {
561        replace_snapshot(&mut self.held, &mut self.edges, held_action_counts, edges);
562    }
563}
564
565/// Read-only logical input for the current FrameUpdate delivery.
566///
567/// This custom System parameter deliberately exposes no `ResMut` path to the
568/// runtime-owned snapshot.
569#[derive(SystemParam)]
570pub struct FrameInput<'w, A: Action> {
571    state: Res<'w, FrameInputState<A>>,
572}
573
574impl<A: Action> FrameInput<'_, A> {
575    /// Iterates over wheel events in physical order, retaining fractional line
576    /// or logical-pixel units and event-time pointers. Events are frame-only,
577    /// even while paused, and a focus-loss frame has no wheel events.
578    pub fn scroll_events(&self) -> impl Iterator<Item = PointerScrollEvent> + '_ {
579        self.state.scrolls.iter().copied()
580    }
581
582    /// Interleaves action edges and wheel occurrences in physical event order.
583    /// Use this when a wheel changes the camera used to interpret nearby clicks.
584    /// Synthesized cancellation releases retain their normal ordering. Each
585    /// queue has the input event limit; the merged view allocates no storage.
586    pub fn events(&self) -> impl Iterator<Item = FrameInputEvent<A>> + '_ {
587        scroll::ordered_events(&self.state.edges, &self.state.scrolls)
588    }
589
590    /// Returns this frame's raw displacement. Apply sensitivity once, without
591    /// delta-time scaling. No fixed-tick delivery or transition replay occurs.
592    pub fn relative_motion(&self) -> RelativePointerMotion {
593        self.state.relative_motion
594    }
595
596    /// Reports a focus-loss boundary even when no mapped control was held.
597    /// All relative motion and wheel events in that accepted batch are discarded.
598    pub fn focus_lost(&self) -> bool {
599        self.state.focus_lost
600    }
601
602    /// Returns the latest accepted pointer sample, or None before motion or
603    /// after leaving. Inactive-stage snapshots are empty. Use an action edge's
604    /// [`ActionEdge::pointer`] for the position of a particular click.
605    pub fn pointer(&self) -> Option<PointerSample> {
606        self.state.pointer
607    }
608
609    /// Returns whether at least one bound key or mouse button for `action` is held.
610    pub fn held(&self, action: A) -> bool {
611        self.state.held(action)
612    }
613
614    /// Returns whether this frame contains at least one press occurrence.
615    ///
616    /// This does not consume the occurrence and is independent from aggregate
617    /// [`Self::held`] state: another physical key for the same action may
618    /// already be held, and one frame may contain both press and release
619    /// occurrences. Use [`Self::pressed`] when occurrence count, order, or
620    /// intent tokens are needed.
621    pub fn has_press_occurrence(&self, action: A) -> bool {
622        self.pressed(action).next().is_some()
623    }
624
625    /// Returns whether this frame contains at least one release occurrence.
626    ///
627    /// This does not consume the occurrence. It can return `true` while
628    /// [`Self::held`] also returns `true` when another physical key remains
629    /// bound to and held for the same action. Use [`Self::released`] when
630    /// occurrence count, order, or intent tokens are needed.
631    pub fn has_release_occurrence(&self, action: A) -> bool {
632        self.released(action).next().is_some()
633    }
634
635    /// Samples four held actions as a raw digital axis.
636    ///
637    /// Each component is exactly `-1.0`, `0.0`, or `1.0`; opposite directions
638    /// cancel. This performs four held-state lookups without allocation and
639    /// does not read or consume action edges. Use
640    /// [`Self::normalized_digital_axis`] when diagonal movement should retain
641    /// cardinal speed.
642    pub fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
643        self.state.digital_axis(axis)
644    }
645
646    /// Samples four held actions as a constant-speed digital direction.
647    ///
648    /// This is exactly equivalent to `self.digital_axis(axis).normalized()`:
649    /// no input or mutually cancelled directions produce [`Vec2::ZERO`],
650    /// cardinal directions stay unchanged, and non-zero diagonals have unit
651    /// length. It performs no allocation and neither reads nor consumes action
652    /// edges. Use [`Self::digital_axis`] when raw diagonal magnitude or grid
653    /// semantics are wanted.
654    pub fn normalized_digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
655        self.digital_axis(axis).normalized()
656    }
657
658    /// Iterates over every press occurrence for `action` in event order.
659    pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
660        self.state.pressed(action)
661    }
662
663    /// Iterates over all action edges in physical event order.
664    ///
665    /// Use this for gestures whose presses and releases can both arrive in
666    /// one display frame. Each mouse edge keeps its own event-time pointer;
667    /// the latest pointer is not necessarily the release endpoint.
668    pub fn edges(&self) -> impl Iterator<Item = ActionEdge<A>> + '_ {
669        self.state.edges.iter().copied()
670    }
671
672    /// Iterates over every release occurrence for `action` in event order.
673    pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
674        self.state.released(action)
675    }
676}
677
678/// Read-only logical input exposed to FixedUpdate systems.
679///
680/// Fixed edges persist across application frames until the first fixed tick
681/// that can receive them. All systems in that tick see the same snapshot;
682/// later catch-up ticks do not see those edges again.
683#[derive(Debug, Clone, Resource)]
684pub(crate) struct FixedInputState<A: Action> {
685    held: HashSet<A>,
686    edges: Vec<ActionEdge<A>>,
687    pointer: Option<PointerSample>,
688    focus_lost: bool,
689}
690
691impl<A: Action> FixedInputState<A> {
692    /// Returns whether at least one bound key or mouse button for `action` is held.
693    pub fn held(&self, action: A) -> bool {
694        self.held.contains(&action)
695    }
696
697    fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
698        sample_digital_axis(axis, |action| self.held(action))
699    }
700
701    /// Iterates over every queued press occurrence for `action` in event order.
702    pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
703        self.edges
704            .iter()
705            .copied()
706            .filter(move |edge| edge.action == action && edge.state == ButtonState::Pressed)
707    }
708
709    /// Iterates over every queued release occurrence for `action` in event order.
710    pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
711        self.edges
712            .iter()
713            .copied()
714            .filter(move |edge| edge.action == action && edge.state == ButtonState::Released)
715    }
716
717    pub(crate) fn empty() -> Self {
718        Self {
719            held: HashSet::new(),
720            edges: Vec::new(),
721            pointer: None,
722            focus_lost: false,
723        }
724    }
725
726    pub(crate) fn clear_reusing_storage(&mut self) {
727        self.held.clear();
728        self.edges.clear();
729        self.pointer = None;
730        self.focus_lost = false;
731    }
732
733    fn replace_from(&mut self, held_action_counts: &HashMap<A, usize>, edges: &[ActionEdge<A>]) {
734        replace_snapshot(&mut self.held, &mut self.edges, held_action_counts, edges);
735    }
736}
737
738/// Read-only logical input for the current FixedUpdate delivery.
739///
740/// Fixed edges survive frames with no fixed tick and are delivered to every
741/// system in the first later tick, without exposing mutable snapshot access.
742/// Their total retained count is bounded by the application's input event
743/// limit; a frame that would exceed it is rejected before input state changes.
744#[derive(SystemParam)]
745pub struct FixedInput<'w, A: Action> {
746    state: Res<'w, FixedInputState<A>>,
747}
748
749impl<A: Action> FixedInput<'_, A> {
750    /// Reports focus loss in this application frame, even with no held control.
751    /// True for every catch-up tick in that frame, so cached movement can stop
752    /// before FrameUpdate. Unlike edges, this boundary is not retained into a
753    /// later frame with a fixed tick. False outside FixedUpdate.
754    pub fn focus_lost(&self) -> bool {
755        self.state.focus_lost
756    }
757
758    /// Returns the latest accepted pointer sample for this tick. Retained
759    /// click edges keep their own earlier samples; later catch-up ticks retain
760    /// the continuous pointer but do not replay those edges. During FrameUpdate
761    /// this snapshot returns None. Input resources are not present in Startup.
762    pub fn pointer(&self) -> Option<PointerSample> {
763        self.state.pointer
764    }
765
766    /// Returns whether at least one bound key or mouse button for `action` is held.
767    pub fn held(&self, action: A) -> bool {
768        self.state.held(action)
769    }
770
771    /// Returns whether this fixed tick contains at least one press occurrence.
772    ///
773    /// Press occurrences survive frames with no fixed tick, appear in the
774    /// first later tick, and do not appear in its later catch-up ticks. This
775    /// method does not consume them and is independent from aggregate
776    /// [`Self::held`] state. Use [`Self::pressed`] when occurrence count,
777    /// order, or intent tokens are needed.
778    pub fn has_press_occurrence(&self, action: A) -> bool {
779        self.pressed(action).next().is_some()
780    }
781
782    /// Returns whether this fixed tick contains at least one release occurrence.
783    ///
784    /// Release occurrences follow the same retained first-tick delivery as
785    /// [`Self::has_press_occurrence`] and are not consumed by this call. It can
786    /// return `true` while [`Self::held`] also returns `true` when another
787    /// physical key remains bound to and held for the action. Use
788    /// [`Self::released`] when occurrence count, order, or intent tokens are
789    /// needed.
790    pub fn has_release_occurrence(&self, action: A) -> bool {
791        self.released(action).next().is_some()
792    }
793
794    /// Samples four held actions as a raw digital axis.
795    ///
796    /// Each component is exactly `-1.0`, `0.0`, or `1.0`; opposite directions
797    /// cancel. This performs four held-state lookups without allocation and
798    /// does not read or consume action edges. Use
799    /// [`Self::normalized_digital_axis`] when diagonal movement should retain
800    /// cardinal speed.
801    pub fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
802        self.state.digital_axis(axis)
803    }
804
805    /// Samples four held actions as a constant-speed digital direction.
806    ///
807    /// This is exactly equivalent to `self.digital_axis(axis).normalized()`:
808    /// no input or mutually cancelled directions produce [`Vec2::ZERO`],
809    /// cardinal directions stay unchanged, and non-zero diagonals have unit
810    /// length. It performs no allocation and neither reads nor consumes action
811    /// edges. Use [`Self::digital_axis`] when raw diagonal magnitude or grid
812    /// semantics are wanted.
813    pub fn normalized_digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
814        self.digital_axis(axis).normalized()
815    }
816
817    /// Iterates over every queued press occurrence for `action` in event order.
818    pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
819        self.state.pressed(action)
820    }
821
822    /// Iterates over every queued release occurrence for `action` in event order.
823    pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
824        self.state.released(action)
825    }
826}
827
828#[derive(Debug, Clone, Copy, PartialEq, Eq)]
829pub(crate) struct InputCollectionReport {
830    pub(crate) physical_events: usize,
831    pub(crate) logical_edges: usize,
832    pub(crate) suppressed_repeats: usize,
833    pub(crate) unmapped_events: usize,
834}
835
836#[derive(Clone, Copy)]
837struct EdgeDelivery {
838    paused: bool,
839    application: ApplicationId,
840    origin: WorldGeneration,
841    frame: u64,
842    ordinal: usize,
843}
844
845#[derive(Debug)]
846pub(crate) struct InputState<A: Action> {
847    bindings: ActionBindings<A>,
848    event_limit: usize,
849    held_keys: [bool; SUPPORTED_PHYSICAL_KEY_COUNT],
850    held_mouse: [bool; ALL_MOUSE_BUTTONS.len()],
851    pointer: Option<PointerSample>,
852    relative_motion: RelativePointerMotion,
853    focus_lost: bool,
854    held_action_counts: HashMap<A, usize>,
855    frame_edges: Vec<ActionEdge<A>>,
856    frame_scrolls: Vec<PointerScrollEvent>,
857    fixed_edges: Vec<ActionEdge<A>>,
858    next_occurrence: u64,
859}
860
861impl<A: Action> InputState<A> {
862    pub(crate) fn new(
863        bindings: ActionBindings<A>,
864        event_limit: usize,
865    ) -> Result<Self, InputCollectionError> {
866        if event_limit == 0 {
867            return Err(InputCollectionError::ZeroEventLimit);
868        }
869
870        let mut held_action_counts = HashMap::new();
871        let mut frame_edges = Vec::new();
872        let mut frame_scrolls = Vec::new();
873        let mut fixed_edges = Vec::new();
874        let held_capacity = SUPPORTED_PHYSICAL_KEY_COUNT + ALL_MOUSE_BUTTONS.len();
875        held_action_counts
876            .try_reserve(held_capacity)
877            .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
878        frame_edges
879            .try_reserve(event_limit)
880            .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
881        frame_scrolls
882            .try_reserve(event_limit)
883            .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
884        fixed_edges
885            .try_reserve(event_limit)
886            .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
887
888        Ok(Self {
889            bindings,
890            event_limit,
891            held_keys: [false; SUPPORTED_PHYSICAL_KEY_COUNT],
892            held_mouse: [false; ALL_MOUSE_BUTTONS.len()],
893            pointer: None,
894            relative_motion: RelativePointerMotion::ZERO,
895            focus_lost: false,
896            held_action_counts,
897            frame_edges,
898            frame_scrolls,
899            fixed_edges,
900            next_occurrence: 0,
901        })
902    }
903
904    pub(crate) fn collect_frame(
905        &mut self,
906        events: &[InputEvent],
907        paused: bool,
908        application: ApplicationId,
909        origin: WorldGeneration,
910        frame: u64,
911    ) -> Result<InputCollectionReport, InputCollectionError> {
912        if events.len() > self.event_limit {
913            return Err(InputCollectionError::EventLimitExceeded {
914                limit: self.event_limit,
915                received: events.len(),
916            });
917        }
918
919        let (relative_motion, focus_lost) =
920            motion::frame_motion(events).map_err(InputCollectionError::RelativeMotion)?;
921        let report = self.preflight_frame(events, paused)?;
922        let logical_edge_count = u64::try_from(report.logical_edges)
923            .map_err(|_| InputCollectionError::OccurrenceIdentityExhausted)?;
924        if self
925            .next_occurrence
926            .checked_add(logical_edge_count)
927            .is_none()
928        {
929            return Err(InputCollectionError::OccurrenceIdentityExhausted);
930        }
931
932        self.frame_edges.clear();
933        self.frame_scrolls.clear();
934        self.relative_motion = relative_motion;
935        self.focus_lost = focus_lost;
936        let mut delivery = EdgeDelivery {
937            paused,
938            application,
939            origin,
940            frame,
941            ordinal: 0,
942        };
943
944        for (ordinal, event) in events.iter().enumerate() {
945            delivery.ordinal = ordinal;
946            match *event {
947                InputEvent::Key { key, state } => {
948                    self.record_edge(InputControl::Key(key), state, None, delivery);
949                }
950                InputEvent::MouseButton { button, state } => {
951                    self.record_edge(InputControl::MouseButton(button), state, None, delivery);
952                }
953                InputEvent::PointerMoved { sample } => self.pointer = Some(sample),
954                InputEvent::RelativePointerMotion { .. } => {}
955                InputEvent::MouseWheel { delta } => {
956                    if !focus_lost {
957                        self.frame_scrolls.push(PointerScrollEvent {
958                            delta,
959                            pointer: self.pointer,
960                            ordinal,
961                        });
962                    }
963                }
964                InputEvent::PointerLeft | InputEvent::FocusLost => {
965                    let reason = cancellation_reason(*event);
966                    self.pointer = None;
967                    for control in cancelled_controls(reason) {
968                        self.record_edge(control, ButtonState::Released, Some(reason), delivery);
969                    }
970                }
971            }
972        }
973
974        Ok(report)
975    }
976
977    fn preflight_frame(
978        &self,
979        events: &[InputEvent],
980        paused: bool,
981    ) -> Result<InputCollectionReport, InputCollectionError> {
982        let mut held_keys = self.held_keys;
983        let mut held_mouse = self.held_mouse;
984        let mut report = InputCollectionReport {
985            physical_events: events.len(),
986            logical_edges: 0,
987            suppressed_repeats: 0,
988            unmapped_events: 0,
989        };
990
991        for event in events {
992            match *event {
993                InputEvent::Key { key, state } => {
994                    preflight_button(
995                        self.bindings.action_for(key),
996                        &mut held_keys[physical_key_index(key)],
997                        state,
998                        &mut report,
999                    );
1000                }
1001                InputEvent::MouseButton { button, state } => {
1002                    preflight_button(
1003                        self.bindings.mouse_action_for(button),
1004                        &mut held_mouse[mouse_button_index(button)],
1005                        state,
1006                        &mut report,
1007                    );
1008                }
1009                InputEvent::PointerMoved { .. }
1010                | InputEvent::RelativePointerMotion { .. }
1011                | InputEvent::MouseWheel { .. } => {}
1012                InputEvent::PointerLeft | InputEvent::FocusLost => {
1013                    for control in cancelled_controls(cancellation_reason(*event)) {
1014                        // Synthetic no-op releases are not physical repeats
1015                        // or unmapped events; only actual held buttons count.
1016                        let held = match control {
1017                            InputControl::Key(key) => &mut held_keys[physical_key_index(key)],
1018                            InputControl::MouseButton(button) => {
1019                                &mut held_mouse[mouse_button_index(button)]
1020                            }
1021                        };
1022                        if self.bindings.control_action_for(control).is_some()
1023                            && change_button(held, ButtonState::Released)
1024                        {
1025                            report.logical_edges += 1;
1026                        }
1027                    }
1028                }
1029            }
1030        }
1031
1032        if report.logical_edges > self.event_limit {
1033            return Err(InputCollectionError::FrameEdgeLimitExceeded {
1034                limit: self.event_limit,
1035                incoming: report.logical_edges,
1036            });
1037        }
1038
1039        if !paused && report.logical_edges > self.event_limit.saturating_sub(self.fixed_edges.len())
1040        {
1041            return Err(InputCollectionError::RetainedFixedEdgeLimitExceeded {
1042                limit: self.event_limit,
1043                retained: self.fixed_edges.len(),
1044                incoming: report.logical_edges,
1045            });
1046        }
1047
1048        Ok(report)
1049    }
1050
1051    #[cfg(test)]
1052    pub(crate) fn frame_input(&self) -> FrameInputState<A> {
1053        let mut snapshot = FrameInputState::empty();
1054        self.copy_frame_snapshot_into(&mut snapshot);
1055        snapshot
1056    }
1057
1058    #[cfg(test)]
1059    pub(crate) fn fixed_input(&self) -> FixedInputState<A> {
1060        let mut snapshot = FixedInputState::empty();
1061        self.copy_fixed_snapshot_into(&mut snapshot);
1062        snapshot
1063    }
1064
1065    pub(crate) fn copy_frame_snapshot_into(&self, target: &mut FrameInputState<A>) {
1066        target.replace_from(&self.held_action_counts, &self.frame_edges);
1067        target.scrolls.clear();
1068        target.scrolls.extend_from_slice(&self.frame_scrolls);
1069        target.pointer = self.pointer;
1070        target.relative_motion = self.relative_motion;
1071        target.focus_lost = self.focus_lost;
1072    }
1073
1074    pub(crate) fn copy_fixed_snapshot_into(&self, target: &mut FixedInputState<A>) {
1075        target.replace_from(&self.held_action_counts, &self.fixed_edges);
1076        target.pointer = self.pointer;
1077        target.focus_lost = self.focus_lost;
1078    }
1079
1080    pub(crate) fn consume_fixed_delivery(&mut self) {
1081        self.fixed_edges.clear();
1082    }
1083
1084    pub(crate) fn discard_fixed_edges(&mut self) {
1085        self.fixed_edges.clear();
1086    }
1087
1088    pub(crate) fn consume_token_occurrence(&mut self, token: TransitionIntentToken) -> bool {
1089        let was_live = self.token_is_live(token);
1090        self.frame_edges.retain(|edge| edge.intent != token);
1091        self.fixed_edges.retain(|edge| edge.intent != token);
1092        was_live
1093    }
1094
1095    pub(crate) fn token_is_live(&self, token: TransitionIntentToken) -> bool {
1096        self.frame_edges
1097            .iter()
1098            .chain(&self.fixed_edges)
1099            .any(|edge| edge.intent == token)
1100    }
1101
1102    pub(crate) fn token_is_live_in_frame(&self, token: TransitionIntentToken) -> bool {
1103        self.frame_edges.iter().any(|edge| edge.intent == token)
1104    }
1105
1106    pub(crate) fn token_is_live_in_fixed(&self, token: TransitionIntentToken) -> bool {
1107        self.fixed_edges.iter().any(|edge| edge.intent == token)
1108    }
1109
1110    pub(crate) fn clear_world_edges(&mut self) {
1111        self.frame_edges.clear();
1112        self.frame_scrolls.clear();
1113        self.fixed_edges.clear();
1114        self.relative_motion = RelativePointerMotion::ZERO;
1115        self.focus_lost = false;
1116    }
1117
1118    pub(crate) fn end_frame(&mut self) {
1119        self.frame_edges.clear();
1120        self.frame_scrolls.clear();
1121        self.relative_motion = RelativePointerMotion::ZERO;
1122        self.focus_lost = false;
1123    }
1124
1125    fn record_edge(
1126        &mut self,
1127        control: InputControl,
1128        state: ButtonState,
1129        cancellation: Option<InputCancellationReason>,
1130        delivery: EdgeDelivery,
1131    ) {
1132        let Some(action) = self.bindings.control_action_for(control) else {
1133            return;
1134        };
1135        let held = match control {
1136            InputControl::Key(key) => &mut self.held_keys[physical_key_index(key)],
1137            InputControl::MouseButton(button) => &mut self.held_mouse[mouse_button_index(button)],
1138        };
1139        if !change_button(held, state) {
1140            return;
1141        }
1142        let pointer = match (control, cancellation) {
1143            (InputControl::MouseButton(_), None) => self.pointer,
1144            _ => None,
1145        };
1146        self.update_held_action(action, state);
1147        let occurrence = self.next_occurrence;
1148        // Whole-frame preflight proved both queue bounds and never-reused
1149        // occurrence space, including every pointer-leave or focus-loss release.
1150        self.next_occurrence += 1;
1151        let edge = ActionEdge {
1152            action,
1153            state,
1154            pointer,
1155            control,
1156            cancellation,
1157            ordinal: delivery.ordinal,
1158            intent: TransitionIntentToken::input(
1159                delivery.application,
1160                delivery.origin,
1161                delivery.frame,
1162                occurrence,
1163            ),
1164        };
1165        self.frame_edges.push(edge);
1166        if !delivery.paused {
1167            self.fixed_edges.push(edge);
1168        }
1169    }
1170
1171    fn update_held_action(&mut self, action: A, state: ButtonState) {
1172        match state {
1173            ButtonState::Pressed => {
1174                let count = self.held_action_counts.entry(action).or_insert(0);
1175                *count += 1;
1176            }
1177            ButtonState::Released => {
1178                if let Some(count) = self.held_action_counts.get_mut(&action) {
1179                    *count -= 1;
1180                    if *count == 0 {
1181                        self.held_action_counts.remove(&action);
1182                    }
1183                }
1184            }
1185        }
1186    }
1187}
1188
1189fn cancellation_reason(event: InputEvent) -> InputCancellationReason {
1190    // Only the two explicit cancellation branches call this helper. Keep their
1191    // control enumeration identical between preflight and committed collection.
1192    if matches!(event, InputEvent::FocusLost) {
1193        InputCancellationReason::FocusLost
1194    } else {
1195        InputCancellationReason::PointerLeft
1196    }
1197}
1198
1199fn change_button(held: &mut bool, state: ButtonState) -> bool {
1200    let next = state == ButtonState::Pressed;
1201    let changed = *held != next;
1202    *held = next;
1203    changed
1204}
1205
1206fn preflight_button<A: Action>(
1207    action: Option<A>,
1208    held: &mut bool,
1209    state: ButtonState,
1210    report: &mut InputCollectionReport,
1211) {
1212    if action.is_none() {
1213        report.unmapped_events += 1;
1214    } else if change_button(held, state) {
1215        report.logical_edges += 1;
1216    } else {
1217        report.suppressed_repeats += 1;
1218    }
1219}
1220
1221fn replace_snapshot<A: Action>(
1222    target_held: &mut HashSet<A>,
1223    target_edges: &mut Vec<ActionEdge<A>>,
1224    held_action_counts: &HashMap<A, usize>,
1225    source_edges: &[ActionEdge<A>],
1226) {
1227    target_held.clear();
1228    target_held.extend(held_action_counts.keys().copied());
1229    target_edges.clear();
1230    target_edges.extend_from_slice(source_edges);
1231}
1232
1233fn sample_digital_axis<A: Action>(axis: DigitalAxis2d<A>, mut held: impl FnMut(A) -> bool) -> Vec2 {
1234    let x = f32::from(held(axis.positive_x)) - f32::from(held(axis.negative_x));
1235    let y = f32::from(held(axis.positive_y)) - f32::from(held(axis.negative_y));
1236    Vec2::new(x, y)
1237}
1238
1239#[cfg(test)]
1240mod tests {
1241    use super::*;
1242
1243    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1244    enum TestAction {
1245        Move,
1246        Enter,
1247        Fire,
1248        Left,
1249        Right,
1250        Down,
1251        Up,
1252    }
1253
1254    const TEST_AXIS: DigitalAxis2d<TestAction> = DigitalAxis2d::new(
1255        TestAction::Left,
1256        TestAction::Right,
1257        TestAction::Down,
1258        TestAction::Up,
1259    );
1260
1261    fn identity() -> (ApplicationId, WorldGeneration) {
1262        let application = ApplicationId::from_raw(7);
1263        (application, WorldGeneration::new(application, 3))
1264    }
1265
1266    fn bindings() -> ActionBindings<TestAction> {
1267        let mut bindings = ActionBindings::new();
1268        assert!(
1269            bindings
1270                .bind(PhysicalKeyCode::KeyW, TestAction::Move)
1271                .is_ok()
1272        );
1273        assert!(
1274            bindings
1275                .bind(PhysicalKeyCode::KeyA, TestAction::Move)
1276                .is_ok()
1277        );
1278        assert!(
1279            bindings
1280                .bind(PhysicalKeyCode::Enter, TestAction::Enter)
1281                .is_ok()
1282        );
1283        assert!(
1284            bindings
1285                .bind(PhysicalKeyCode::Space, TestAction::Fire)
1286                .is_ok()
1287        );
1288        bindings
1289    }
1290
1291    fn state(limit: usize) -> InputState<TestAction> {
1292        let result = InputState::new(bindings(), limit);
1293        let Ok(state) = result else {
1294            panic!("test input state should be valid");
1295        };
1296        state
1297    }
1298
1299    #[test]
1300    fn duplicate_physical_key_is_rejected_without_replacement() {
1301        let mut bindings = bindings();
1302        let duplicate = bindings.bind(PhysicalKeyCode::KeyW, TestAction::Enter);
1303
1304        assert_eq!(
1305            duplicate.map(|_| ()),
1306            Err(DuplicateKeyBinding {
1307                key: PhysicalKeyCode::KeyW,
1308            })
1309        );
1310        assert_eq!(
1311            bindings.action_for(PhysicalKeyCode::KeyW),
1312            Some(TestAction::Move)
1313        );
1314    }
1315
1316    #[test]
1317    fn physical_key_catalog_is_unique_and_round_trips_every_index() {
1318        assert_eq!(SUPPORTED_PHYSICAL_KEY_COUNT, 108);
1319        let mut unique = HashSet::new();
1320
1321        for (index, key) in ALL_PHYSICAL_KEYS.into_iter().enumerate() {
1322            assert!(unique.insert(key), "duplicate catalog key {key:?}");
1323            assert_eq!(physical_key_index(key), index);
1324            assert_eq!(ALL_PHYSICAL_KEYS[physical_key_index(key)], key);
1325        }
1326    }
1327
1328    #[test]
1329    fn wasd_binding_maps_axis_slots_and_remains_compatible_with_manual_keys() {
1330        let mut bindings = ActionBindings::new();
1331        assert!(
1332            bindings
1333                .bind(PhysicalKeyCode::Enter, TestAction::Enter)
1334                .is_ok()
1335        );
1336        assert!(bindings.bind_wasd(TEST_AXIS).is_ok());
1337        assert!(
1338            bindings
1339                .bind(PhysicalKeyCode::Space, TestAction::Fire)
1340                .is_ok()
1341        );
1342
1343        assert_eq!(
1344            bindings.action_for(PhysicalKeyCode::KeyW),
1345            Some(TestAction::Up)
1346        );
1347        assert_eq!(
1348            bindings.action_for(PhysicalKeyCode::KeyA),
1349            Some(TestAction::Left)
1350        );
1351        assert_eq!(
1352            bindings.action_for(PhysicalKeyCode::KeyS),
1353            Some(TestAction::Down)
1354        );
1355        assert_eq!(
1356            bindings.action_for(PhysicalKeyCode::KeyD),
1357            Some(TestAction::Right)
1358        );
1359        assert_eq!(
1360            bindings.action_for(PhysicalKeyCode::Enter),
1361            Some(TestAction::Enter)
1362        );
1363        assert_eq!(
1364            bindings.action_for(PhysicalKeyCode::Space),
1365            Some(TestAction::Fire)
1366        );
1367    }
1368
1369    #[test]
1370    fn wasd_binding_conflicts_are_atomic_for_every_key() {
1371        let preset_keys = [
1372            PhysicalKeyCode::KeyW,
1373            PhysicalKeyCode::KeyA,
1374            PhysicalKeyCode::KeyS,
1375            PhysicalKeyCode::KeyD,
1376        ];
1377
1378        for occupied in preset_keys {
1379            let mut bindings = ActionBindings::new();
1380            assert!(bindings.bind(occupied, TestAction::Move).is_ok());
1381
1382            assert_eq!(
1383                bindings.bind_wasd(TEST_AXIS).map(|_| ()),
1384                Err(DuplicateKeyBinding { key: occupied })
1385            );
1386            for key in preset_keys {
1387                let expected = (key == occupied).then_some(TestAction::Move);
1388                assert_eq!(bindings.action_for(key), expected, "occupied={occupied:?}");
1389            }
1390        }
1391    }
1392
1393    #[test]
1394    fn wasd_binding_uses_deterministic_conflict_order_and_allows_repeated_actions() {
1395        let mut conflicted = ActionBindings::new();
1396        assert!(
1397            conflicted
1398                .bind(PhysicalKeyCode::KeyS, TestAction::Fire)
1399                .is_ok()
1400        );
1401        assert!(
1402            conflicted
1403                .bind(PhysicalKeyCode::KeyW, TestAction::Move)
1404                .is_ok()
1405        );
1406        assert_eq!(
1407            conflicted.bind_wasd(TEST_AXIS).map(|_| ()),
1408            Err(DuplicateKeyBinding {
1409                key: PhysicalKeyCode::KeyW,
1410            })
1411        );
1412
1413        let repeated = DigitalAxis2d::new(
1414            TestAction::Move,
1415            TestAction::Move,
1416            TestAction::Move,
1417            TestAction::Move,
1418        );
1419        let mut bindings = ActionBindings::new();
1420        assert!(bindings.bind_wasd(repeated).is_ok());
1421        for key in [
1422            PhysicalKeyCode::KeyW,
1423            PhysicalKeyCode::KeyA,
1424            PhysicalKeyCode::KeyS,
1425            PhysicalKeyCode::KeyD,
1426        ] {
1427            assert_eq!(bindings.action_for(key), Some(TestAction::Move));
1428        }
1429    }
1430
1431    #[test]
1432    fn arrow_binding_maps_axis_slots_and_coexists_with_wasd_and_manual_escape() {
1433        let mut bindings = ActionBindings::new();
1434        assert!(bindings.bind_wasd(TEST_AXIS).is_ok());
1435        assert!(bindings.bind_arrows(TEST_AXIS).is_ok());
1436        assert!(
1437            bindings
1438                .bind(PhysicalKeyCode::Escape, TestAction::Enter)
1439                .is_ok()
1440        );
1441
1442        for (key, expected) in [
1443            (PhysicalKeyCode::ArrowLeft, TestAction::Left),
1444            (PhysicalKeyCode::ArrowRight, TestAction::Right),
1445            (PhysicalKeyCode::ArrowDown, TestAction::Down),
1446            (PhysicalKeyCode::ArrowUp, TestAction::Up),
1447        ] {
1448            assert_eq!(bindings.action_for(key), Some(expected));
1449        }
1450        assert_eq!(
1451            bindings.action_for(PhysicalKeyCode::Escape),
1452            Some(TestAction::Enter)
1453        );
1454    }
1455
1456    #[test]
1457    fn arrow_binding_conflicts_are_atomic_and_use_axis_slot_order() {
1458        let arrow_keys = [
1459            PhysicalKeyCode::ArrowLeft,
1460            PhysicalKeyCode::ArrowRight,
1461            PhysicalKeyCode::ArrowDown,
1462            PhysicalKeyCode::ArrowUp,
1463        ];
1464
1465        for occupied in arrow_keys {
1466            let mut bindings = ActionBindings::new();
1467            assert!(bindings.bind(occupied, TestAction::Move).is_ok());
1468
1469            assert_eq!(
1470                bindings.bind_arrows(TEST_AXIS).map(|_| ()),
1471                Err(DuplicateKeyBinding { key: occupied })
1472            );
1473            for key in arrow_keys {
1474                let expected = (key == occupied).then_some(TestAction::Move);
1475                assert_eq!(bindings.action_for(key), expected, "occupied={occupied:?}");
1476            }
1477        }
1478
1479        let mut two_conflicts = ActionBindings::new();
1480        assert!(
1481            two_conflicts
1482                .bind(PhysicalKeyCode::ArrowUp, TestAction::Fire)
1483                .is_ok()
1484        );
1485        assert!(
1486            two_conflicts
1487                .bind(PhysicalKeyCode::ArrowRight, TestAction::Move)
1488                .is_ok()
1489        );
1490        assert_eq!(
1491            two_conflicts.bind_arrows(TEST_AXIS).map(|_| ()),
1492            Err(DuplicateKeyBinding {
1493                key: PhysicalKeyCode::ArrowRight,
1494            })
1495        );
1496
1497        let repeated = DigitalAxis2d::new(
1498            TestAction::Move,
1499            TestAction::Move,
1500            TestAction::Move,
1501            TestAction::Move,
1502        );
1503        let mut bindings = ActionBindings::new();
1504        assert!(bindings.bind_arrows(repeated).is_ok());
1505        for key in arrow_keys {
1506            assert_eq!(bindings.action_for(key), Some(TestAction::Move));
1507        }
1508    }
1509
1510    #[test]
1511    fn combined_directional_binding_maps_every_slot_and_preserves_manual_keys() {
1512        let mut bindings = ActionBindings::new();
1513        assert!(
1514            bindings
1515                .bind(PhysicalKeyCode::Escape, TestAction::Enter)
1516                .is_ok()
1517        );
1518        assert!(bindings.bind_wasd_and_arrows(TEST_AXIS).is_ok());
1519
1520        for (key, expected) in [
1521            (PhysicalKeyCode::KeyW, TestAction::Up),
1522            (PhysicalKeyCode::KeyA, TestAction::Left),
1523            (PhysicalKeyCode::KeyS, TestAction::Down),
1524            (PhysicalKeyCode::KeyD, TestAction::Right),
1525            (PhysicalKeyCode::ArrowLeft, TestAction::Left),
1526            (PhysicalKeyCode::ArrowRight, TestAction::Right),
1527            (PhysicalKeyCode::ArrowDown, TestAction::Down),
1528            (PhysicalKeyCode::ArrowUp, TestAction::Up),
1529        ] {
1530            assert_eq!(bindings.action_for(key), Some(expected));
1531        }
1532        assert_eq!(
1533            bindings.action_for(PhysicalKeyCode::Escape),
1534            Some(TestAction::Enter)
1535        );
1536        assert_eq!(bindings.action_for(PhysicalKeyCode::Enter), None);
1537        assert_eq!(bindings.action_for(PhysicalKeyCode::Space), None);
1538        let before_repeat = ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key));
1539        assert_eq!(
1540            bindings.bind_wasd_and_arrows(TEST_AXIS).map(|_| ()),
1541            Err(DuplicateKeyBinding {
1542                key: PhysicalKeyCode::KeyW,
1543            })
1544        );
1545        assert_eq!(
1546            ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key)),
1547            before_repeat
1548        );
1549    }
1550
1551    #[test]
1552    fn combined_directional_binding_conflicts_are_atomic_for_every_key() {
1553        let preset_keys = [
1554            PhysicalKeyCode::KeyW,
1555            PhysicalKeyCode::KeyA,
1556            PhysicalKeyCode::KeyS,
1557            PhysicalKeyCode::KeyD,
1558            PhysicalKeyCode::ArrowLeft,
1559            PhysicalKeyCode::ArrowRight,
1560            PhysicalKeyCode::ArrowDown,
1561            PhysicalKeyCode::ArrowUp,
1562        ];
1563
1564        for occupied in preset_keys {
1565            let mut bindings = ActionBindings::new();
1566            assert!(bindings.bind(occupied, TestAction::Move).is_ok());
1567            assert!(
1568                bindings
1569                    .bind(PhysicalKeyCode::Enter, TestAction::Enter)
1570                    .is_ok()
1571            );
1572            let before = ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key));
1573
1574            assert_eq!(
1575                bindings.bind_wasd_and_arrows(TEST_AXIS).map(|_| ()),
1576                Err(DuplicateKeyBinding { key: occupied })
1577            );
1578            assert_eq!(
1579                ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key)),
1580                before,
1581                "occupied={occupied:?}"
1582            );
1583        }
1584    }
1585
1586    #[test]
1587    fn combined_directional_binding_uses_one_order_and_allows_repeated_actions() {
1588        let preset_keys = [
1589            PhysicalKeyCode::KeyW,
1590            PhysicalKeyCode::KeyA,
1591            PhysicalKeyCode::KeyS,
1592            PhysicalKeyCode::KeyD,
1593            PhysicalKeyCode::ArrowLeft,
1594            PhysicalKeyCode::ArrowRight,
1595            PhysicalKeyCode::ArrowDown,
1596            PhysicalKeyCode::ArrowUp,
1597        ];
1598        for first_index in 0..preset_keys.len() {
1599            for second_index in (first_index + 1)..preset_keys.len() {
1600                let mut conflicted = ActionBindings::new();
1601                assert!(
1602                    conflicted
1603                        .bind(preset_keys[second_index], TestAction::Fire)
1604                        .is_ok()
1605                );
1606                assert!(
1607                    conflicted
1608                        .bind(preset_keys[first_index], TestAction::Move)
1609                        .is_ok()
1610                );
1611                let before = ALL_PHYSICAL_KEYS.map(|key| conflicted.action_for(key));
1612                assert_eq!(
1613                    conflicted.bind_wasd_and_arrows(TEST_AXIS).map(|_| ()),
1614                    Err(DuplicateKeyBinding {
1615                        key: preset_keys[first_index],
1616                    })
1617                );
1618                assert_eq!(
1619                    ALL_PHYSICAL_KEYS.map(|key| conflicted.action_for(key)),
1620                    before
1621                );
1622            }
1623        }
1624
1625        let repeated = DigitalAxis2d::new(
1626            TestAction::Move,
1627            TestAction::Move,
1628            TestAction::Move,
1629            TestAction::Move,
1630        );
1631        let mut bindings = ActionBindings::new();
1632        assert!(bindings.bind_wasd_and_arrows(repeated).is_ok());
1633        for key in preset_keys {
1634            assert_eq!(bindings.action_for(key), Some(TestAction::Move));
1635        }
1636    }
1637
1638    #[test]
1639    fn digital_axis_descriptor_is_const_copy_and_preserves_slot_order() {
1640        const COPY: DigitalAxis2d<TestAction> = TEST_AXIS;
1641
1642        assert_eq!(COPY.negative_x(), TestAction::Left);
1643        assert_eq!(COPY.positive_x(), TestAction::Right);
1644        assert_eq!(COPY.negative_y(), TestAction::Down);
1645        assert_eq!(COPY.positive_y(), TestAction::Up);
1646    }
1647
1648    #[test]
1649    fn frame_and_fixed_digital_axes_cover_all_held_combinations() {
1650        let actions = [
1651            TestAction::Left,
1652            TestAction::Right,
1653            TestAction::Down,
1654            TestAction::Up,
1655        ];
1656
1657        for mask in 0_u8..16 {
1658            let held: HashSet<_> = actions
1659                .into_iter()
1660                .enumerate()
1661                .filter_map(|(index, action)| (mask & (1 << index) != 0).then_some(action))
1662                .collect();
1663            let frame = FrameInputState {
1664                held: held.clone(),
1665                ..FrameInputState::empty()
1666            };
1667            let fixed = FixedInputState {
1668                held,
1669                ..FixedInputState::empty()
1670            };
1671            let expected = Vec2::new(
1672                f32::from(mask & 0b0010 != 0) - f32::from(mask & 0b0001 != 0),
1673                f32::from(mask & 0b1000 != 0) - f32::from(mask & 0b0100 != 0),
1674            );
1675
1676            assert_eq!(frame.digital_axis(TEST_AXIS), expected, "mask {mask:04b}");
1677            assert_eq!(fixed.digital_axis(TEST_AXIS), expected, "mask {mask:04b}");
1678        }
1679
1680        let diagonal = FrameInputState {
1681            held: HashSet::from([TestAction::Right, TestAction::Up]),
1682            ..FrameInputState::empty()
1683        }
1684        .digital_axis(TEST_AXIS);
1685        assert_eq!(diagonal, Vec2::ONE);
1686        assert!((diagonal.normalized().length() - 1.0).abs() < 0.000_1);
1687    }
1688
1689    #[test]
1690    fn repeated_actions_follow_independent_slot_arithmetic() {
1691        let held = |action| action == TestAction::Move;
1692        let cancelled = DigitalAxis2d::new(
1693            TestAction::Move,
1694            TestAction::Move,
1695            TestAction::Enter,
1696            TestAction::Fire,
1697        );
1698        let diagonal = DigitalAxis2d::new(
1699            TestAction::Enter,
1700            TestAction::Move,
1701            TestAction::Fire,
1702            TestAction::Move,
1703        );
1704
1705        assert_eq!(sample_digital_axis(cancelled, held), Vec2::ZERO);
1706        assert_eq!(sample_digital_axis(diagonal, held), Vec2::ONE);
1707    }
1708
1709    #[test]
1710    fn digital_axis_does_not_consume_press_or_release_edges() {
1711        let (application, generation) = identity();
1712        let mut input = state(4);
1713        let events = [
1714            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
1715            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1716        ];
1717        assert!(
1718            input
1719                .collect_frame(&events, false, application, generation, 1)
1720                .is_ok()
1721        );
1722        let axis = DigitalAxis2d::new(
1723            TestAction::Enter,
1724            TestAction::Move,
1725            TestAction::Fire,
1726            TestAction::Fire,
1727        );
1728        let frame = input.frame_input();
1729        let fixed = input.fixed_input();
1730
1731        assert_eq!(frame.digital_axis(axis), Vec2::ZERO);
1732        assert_eq!(fixed.digital_axis(axis), Vec2::ZERO);
1733        assert_eq!(frame.pressed(TestAction::Move).count(), 1);
1734        assert_eq!(frame.released(TestAction::Move).count(), 1);
1735        assert_eq!(fixed.pressed(TestAction::Move).count(), 1);
1736        assert_eq!(fixed.released(TestAction::Move).count(), 1);
1737        assert_eq!(frame.digital_axis(axis), Vec2::ZERO);
1738        assert_eq!(fixed.digital_axis(axis), Vec2::ZERO);
1739    }
1740
1741    #[test]
1742    fn space_produces_typed_press_and_release_edges() {
1743        let (application, generation) = identity();
1744        let mut input = state(2);
1745
1746        assert!(
1747            input
1748                .collect_frame(
1749                    &[InputEvent::key(
1750                        PhysicalKeyCode::Space,
1751                        ButtonState::Pressed,
1752                    )],
1753                    false,
1754                    application,
1755                    generation,
1756                    1,
1757                )
1758                .is_ok()
1759        );
1760        assert!(input.frame_input().held(TestAction::Fire));
1761        assert_eq!(input.frame_input().pressed(TestAction::Fire).count(), 1);
1762
1763        input.end_frame();
1764        assert!(
1765            input
1766                .collect_frame(
1767                    &[InputEvent::key(
1768                        PhysicalKeyCode::Space,
1769                        ButtonState::Released,
1770                    )],
1771                    false,
1772                    application,
1773                    generation,
1774                    2,
1775                )
1776                .is_ok()
1777        );
1778        assert!(!input.frame_input().held(TestAction::Fire));
1779        assert_eq!(input.frame_input().released(TestAction::Fire).count(), 1);
1780    }
1781
1782    #[test]
1783    fn unreservable_input_limit_returns_a_typed_creation_error() {
1784        let result = InputState::new(bindings(), usize::MAX);
1785
1786        assert!(matches!(
1787            result,
1788            Err(InputCollectionError::StorageAllocationFailed { limit: usize::MAX })
1789        ));
1790    }
1791
1792    #[test]
1793    fn overflow_rejects_the_frame_before_mutating_input() {
1794        let (application, generation) = identity();
1795        let mut input = state(1);
1796        assert!(
1797            input
1798                .collect_frame(
1799                    &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
1800                    false,
1801                    application,
1802                    generation,
1803                    1,
1804                )
1805                .is_ok()
1806        );
1807        let before_frame = input.frame_input();
1808        let before_fixed = input.fixed_input();
1809
1810        let result = input.collect_frame(
1811            &[
1812                InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1813                InputEvent::key(PhysicalKeyCode::Enter, ButtonState::Pressed),
1814            ],
1815            false,
1816            application,
1817            generation,
1818            2,
1819        );
1820
1821        assert_eq!(
1822            result,
1823            Err(InputCollectionError::EventLimitExceeded {
1824                limit: 1,
1825                received: 2,
1826            })
1827        );
1828        assert_eq!(
1829            before_frame.pressed(TestAction::Move).count(),
1830            input.frame_input().pressed(TestAction::Move).count()
1831        );
1832        assert_eq!(
1833            before_fixed.pressed(TestAction::Move).count(),
1834            input.fixed_input().pressed(TestAction::Move).count()
1835        );
1836        assert!(input.frame_input().held(TestAction::Move));
1837    }
1838
1839    #[test]
1840    fn retained_fixed_edge_overflow_is_atomic_without_fixed_delivery() {
1841        let (application, generation) = identity();
1842        let mut input = state(2);
1843        assert!(
1844            input
1845                .collect_frame(
1846                    &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
1847                    false,
1848                    application,
1849                    generation,
1850                    1,
1851                )
1852                .is_ok()
1853        );
1854        input.end_frame();
1855        assert!(
1856            input
1857                .collect_frame(
1858                    &[InputEvent::key(
1859                        PhysicalKeyCode::KeyW,
1860                        ButtonState::Released,
1861                    )],
1862                    false,
1863                    application,
1864                    generation,
1865                    2,
1866                )
1867                .is_ok()
1868        );
1869        input.end_frame();
1870
1871        let occurrence_before = input.next_occurrence;
1872        let result = input.collect_frame(
1873            &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed)],
1874            false,
1875            application,
1876            generation,
1877            3,
1878        );
1879
1880        assert_eq!(
1881            result,
1882            Err(InputCollectionError::RetainedFixedEdgeLimitExceeded {
1883                limit: 2,
1884                retained: 2,
1885                incoming: 1,
1886            })
1887        );
1888        assert_eq!(input.next_occurrence, occurrence_before);
1889        assert!(!input.frame_input().held(TestAction::Move));
1890        assert_eq!(input.frame_input().pressed(TestAction::Move).count(), 0);
1891        assert_eq!(input.fixed_input().pressed(TestAction::Move).count(), 1);
1892        assert_eq!(input.fixed_input().released(TestAction::Move).count(), 1);
1893    }
1894
1895    #[test]
1896    fn consuming_fixed_delivery_releases_the_retained_edge_budget() {
1897        let (application, generation) = identity();
1898        let mut input = state(1);
1899        assert!(
1900            input
1901                .collect_frame(
1902                    &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
1903                    false,
1904                    application,
1905                    generation,
1906                    1,
1907                )
1908                .is_ok()
1909        );
1910        input.end_frame();
1911        input.consume_fixed_delivery();
1912
1913        assert!(
1914            input
1915                .collect_frame(
1916                    &[InputEvent::key(
1917                        PhysicalKeyCode::KeyW,
1918                        ButtonState::Released,
1919                    )],
1920                    false,
1921                    application,
1922                    generation,
1923                    2,
1924                )
1925                .is_ok()
1926        );
1927        assert_eq!(input.fixed_input().released(TestAction::Move).count(), 1);
1928    }
1929
1930    #[test]
1931    fn repeated_physical_states_do_not_create_edges() {
1932        let (application, generation) = identity();
1933        let mut input = state(8);
1934        let events = [
1935            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
1936            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
1937            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1938            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1939        ];
1940
1941        let report = input.collect_frame(&events, false, application, generation, 1);
1942        let Ok(report) = report else {
1943            panic!("bounded input should be accepted");
1944        };
1945
1946        assert_eq!(report.logical_edges, 2);
1947        assert_eq!(report.suppressed_repeats, 2);
1948        assert_eq!(input.frame_input().pressed(TestAction::Move).count(), 1);
1949        assert_eq!(input.frame_input().released(TestAction::Move).count(), 1);
1950        assert!(!input.frame_input().held(TestAction::Move));
1951    }
1952
1953    #[test]
1954    fn every_supported_key_suppresses_repeated_physical_states() {
1955        let (application, generation) = identity();
1956        let new_keys = ALL_PHYSICAL_KEYS;
1957        let mut bindings = ActionBindings::new();
1958        for key in new_keys {
1959            assert!(bindings.bind(key, TestAction::Move).is_ok());
1960        }
1961        let mut input = InputState::new(bindings, new_keys.len() * 4).unwrap();
1962        let mut events = Vec::new();
1963        for key in new_keys {
1964            events.extend([
1965                InputEvent::key(key, ButtonState::Pressed),
1966                InputEvent::key(key, ButtonState::Pressed),
1967                InputEvent::key(key, ButtonState::Released),
1968                InputEvent::key(key, ButtonState::Released),
1969            ]);
1970        }
1971
1972        let report = input
1973            .collect_frame(&events, false, application, generation, 1)
1974            .unwrap();
1975
1976        assert_eq!(report.logical_edges, new_keys.len() * 2);
1977        assert_eq!(report.suppressed_repeats, new_keys.len() * 2);
1978        assert!(!input.frame_input().held(TestAction::Move));
1979    }
1980
1981    #[test]
1982    fn wasd_and_arrow_edges_keep_shared_action_held_until_both_release() {
1983        let (application, generation) = identity();
1984        let mut bindings = ActionBindings::new();
1985        assert!(
1986            bindings
1987                .bind(PhysicalKeyCode::KeyW, TestAction::Move)
1988                .is_ok()
1989        );
1990        assert!(
1991            bindings
1992                .bind(PhysicalKeyCode::ArrowUp, TestAction::Move)
1993                .is_ok()
1994        );
1995        assert!(
1996            bindings
1997                .bind(PhysicalKeyCode::Escape, TestAction::Enter)
1998                .is_ok()
1999        );
2000        let mut input = InputState::new(bindings, 8).unwrap();
2001        let first = [
2002            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
2003            InputEvent::key(PhysicalKeyCode::ArrowUp, ButtonState::Pressed),
2004            InputEvent::key(PhysicalKeyCode::Escape, ButtonState::Pressed),
2005        ];
2006        input
2007            .collect_frame(&first, false, application, generation, 1)
2008            .unwrap();
2009
2010        let frame = input.frame_input();
2011        let move_edges: Vec<_> = frame.pressed(TestAction::Move).collect();
2012        assert_eq!(move_edges.len(), 2);
2013        assert_ne!(move_edges[0].intent(), move_edges[1].intent());
2014        assert_eq!(
2015            frame.pressed(TestAction::Enter).next(),
2016            input.fixed_input().pressed(TestAction::Enter).next()
2017        );
2018
2019        input
2020            .collect_frame(
2021                &[InputEvent::key(
2022                    PhysicalKeyCode::KeyW,
2023                    ButtonState::Released,
2024                )],
2025                false,
2026                application,
2027                generation,
2028                2,
2029            )
2030            .unwrap();
2031        assert!(input.frame_input().held(TestAction::Move));
2032
2033        input
2034            .collect_frame(
2035                &[InputEvent::key(
2036                    PhysicalKeyCode::ArrowUp,
2037                    ButtonState::Released,
2038                )],
2039                false,
2040                application,
2041                generation,
2042                3,
2043            )
2044            .unwrap();
2045        assert!(!input.frame_input().held(TestAction::Move));
2046    }
2047
2048    #[test]
2049    fn two_keys_for_one_action_keep_held_state_until_both_release() {
2050        let (application, generation) = identity();
2051        let mut input = state(8);
2052        assert!(
2053            input
2054                .collect_frame(
2055                    &[
2056                        InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
2057                        InputEvent::key(PhysicalKeyCode::KeyA, ButtonState::Pressed),
2058                        InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
2059                    ],
2060                    false,
2061                    application,
2062                    generation,
2063                    1,
2064                )
2065                .is_ok()
2066        );
2067
2068        let axis = DigitalAxis2d::new(
2069            TestAction::Enter,
2070            TestAction::Move,
2071            TestAction::Fire,
2072            TestAction::Fire,
2073        );
2074        assert!(input.frame_input().held(TestAction::Move));
2075        assert_eq!(input.frame_input().digital_axis(axis), Vec2::X);
2076
2077        assert!(
2078            input
2079                .collect_frame(
2080                    &[InputEvent::key(
2081                        PhysicalKeyCode::KeyA,
2082                        ButtonState::Released,
2083                    )],
2084                    false,
2085                    application,
2086                    generation,
2087                    2,
2088                )
2089                .is_ok()
2090        );
2091        assert!(!input.frame_input().held(TestAction::Move));
2092        assert_eq!(input.frame_input().digital_axis(axis), Vec2::ZERO);
2093    }
2094
2095    #[test]
2096    fn fixed_edges_persist_until_one_tick_consumes_them() {
2097        let (application, generation) = identity();
2098        let mut input = state(8);
2099        assert!(
2100            input
2101                .collect_frame(
2102                    &[InputEvent::key(
2103                        PhysicalKeyCode::Enter,
2104                        ButtonState::Pressed,
2105                    )],
2106                    false,
2107                    application,
2108                    generation,
2109                    1,
2110                )
2111                .is_ok()
2112        );
2113        input.end_frame();
2114
2115        assert!(
2116            input
2117                .collect_frame(&[], false, application, generation, 2)
2118                .is_ok()
2119        );
2120        assert_eq!(input.frame_input().pressed(TestAction::Enter).count(), 0);
2121        assert_eq!(input.fixed_input().pressed(TestAction::Enter).count(), 1);
2122
2123        input.consume_fixed_delivery();
2124        assert_eq!(input.fixed_input().pressed(TestAction::Enter).count(), 0);
2125    }
2126
2127    #[test]
2128    fn paused_events_update_frame_and_held_but_not_fixed_edges() {
2129        let (application, generation) = identity();
2130        let mut input = state(8);
2131        assert!(
2132            input
2133                .collect_frame(
2134                    &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
2135                    true,
2136                    application,
2137                    generation,
2138                    1,
2139                )
2140                .is_ok()
2141        );
2142
2143        assert!(input.frame_input().held(TestAction::Move));
2144        assert_eq!(input.frame_input().pressed(TestAction::Move).count(), 1);
2145        assert_eq!(input.fixed_input().pressed(TestAction::Move).count(), 0);
2146    }
2147
2148    #[test]
2149    fn frame_and_fixed_views_share_one_causal_token() {
2150        let (application, generation) = identity();
2151        let mut input = state(8);
2152        assert!(
2153            input
2154                .collect_frame(
2155                    &[InputEvent::key(
2156                        PhysicalKeyCode::Enter,
2157                        ButtonState::Pressed,
2158                    )],
2159                    false,
2160                    application,
2161                    generation,
2162                    1,
2163                )
2164                .is_ok()
2165        );
2166
2167        let frame_token = input.frame_input().pressed(TestAction::Enter).next();
2168        let fixed_token = input.fixed_input().pressed(TestAction::Enter).next();
2169        assert_eq!(frame_token, fixed_token);
2170    }
2171
2172    #[test]
2173    fn reusable_snapshots_preserve_data_tokens_and_capacity() {
2174        let (application, generation) = identity();
2175        let mut input = state(8);
2176        let events = [
2177            InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
2178            InputEvent::key(PhysicalKeyCode::Enter, ButtonState::Pressed),
2179        ];
2180        assert!(
2181            input
2182                .collect_frame(&events, false, application, generation, 1)
2183                .is_ok()
2184        );
2185
2186        let expected_frame_edges = input.frame_edges.clone();
2187        let expected_fixed_edges = input.fixed_edges.clone();
2188        let mut frame = FrameInputState::empty();
2189        let mut fixed = FixedInputState::empty();
2190        input.copy_frame_snapshot_into(&mut frame);
2191        input.copy_fixed_snapshot_into(&mut fixed);
2192
2193        assert_eq!(frame.edges, expected_frame_edges);
2194        assert_eq!(fixed.edges, expected_fixed_edges);
2195        assert_eq!(input.frame_edges, expected_frame_edges);
2196        assert_eq!(input.fixed_edges, expected_fixed_edges);
2197        assert!(frame.held(TestAction::Move));
2198        assert!(frame.held(TestAction::Enter));
2199        assert!(fixed.held(TestAction::Move));
2200        assert!(fixed.held(TestAction::Enter));
2201
2202        let frame_held_capacity = frame.held.capacity();
2203        let frame_edge_capacity = frame.edges.capacity();
2204        let fixed_held_capacity = fixed.held.capacity();
2205        let fixed_edge_capacity = fixed.edges.capacity();
2206        frame.clear_reusing_storage();
2207        fixed.clear_reusing_storage();
2208        assert!(frame.held.is_empty());
2209        assert!(frame.edges.is_empty());
2210        assert!(fixed.held.is_empty());
2211        assert!(fixed.edges.is_empty());
2212        assert_eq!(frame.held.capacity(), frame_held_capacity);
2213        assert_eq!(frame.edges.capacity(), frame_edge_capacity);
2214        assert_eq!(fixed.held.capacity(), fixed_held_capacity);
2215        assert_eq!(fixed.edges.capacity(), fixed_edge_capacity);
2216
2217        input.end_frame();
2218        input.consume_fixed_delivery();
2219        assert!(
2220            input
2221                .collect_frame(
2222                    &[InputEvent::key(
2223                        PhysicalKeyCode::KeyW,
2224                        ButtonState::Released,
2225                    )],
2226                    false,
2227                    application,
2228                    generation,
2229                    2,
2230                )
2231                .is_ok()
2232        );
2233        input.copy_frame_snapshot_into(&mut frame);
2234        input.copy_fixed_snapshot_into(&mut fixed);
2235        assert_eq!(frame.edges, input.frame_edges);
2236        assert_eq!(fixed.edges, input.fixed_edges);
2237        assert_eq!(frame.held.capacity(), frame_held_capacity);
2238        assert_eq!(frame.edges.capacity(), frame_edge_capacity);
2239        assert_eq!(fixed.held.capacity(), fixed_held_capacity);
2240        assert_eq!(fixed.edges.capacity(), fixed_edge_capacity);
2241    }
2242
2243    #[test]
2244    fn using_a_token_consumes_its_occurrence_in_both_views() {
2245        let (application, generation) = identity();
2246        let mut input = state(8);
2247        assert!(
2248            input
2249                .collect_frame(
2250                    &[InputEvent::key(
2251                        PhysicalKeyCode::Enter,
2252                        ButtonState::Pressed,
2253                    )],
2254                    false,
2255                    application,
2256                    generation,
2257                    1,
2258                )
2259                .is_ok()
2260        );
2261        let edge = input.frame_input().pressed(TestAction::Enter).next();
2262        let Some(edge) = edge else {
2263            panic!("press edge should exist");
2264        };
2265
2266        assert!(input.consume_token_occurrence(edge.intent()));
2267        assert!(!input.token_is_live(edge.intent()));
2268        assert_eq!(input.frame_input().pressed(TestAction::Enter).count(), 0);
2269        assert_eq!(input.fixed_input().pressed(TestAction::Enter).count(), 0);
2270    }
2271}