bevy_enhanced_input 0.23.0

Input manager for Bevy, inspired by Unreal Engine Enhanced Input
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/*!
Contexts are a way to group actions and manage their evaluation order.
They allow you to define when actions are active and which inputs they respond to.

Actions are checked only if their context is active,
and are evaluated in the order of their context's [`ContextPriority`],
then mainly by the order in which the actions were added to the context,
with the first action having the highest priority.

Further details on how to order actions due to their inputs being consumed
can be found in the documentation for [`ActionSettings::consume_input`].

# Removing contexts

If you despawn an entity with its context, the actions and bindings will also be despawned.
However, if you only want to remove a context from an entity, you must remove the required components
**and** manually despawn its actions.

```
use bevy::prelude::*;
use bevy_enhanced_input::prelude::*;

#[derive(Component)]
struct OnFoot;

#[derive(InputAction)]
#[action_output(bool)]
struct Jump;

#[derive(InputAction)]
#[action_output(bool)]
struct Fire;

let mut world = World::new();
let mut player = world.spawn((
    OnFoot,
    actions!(OnFoot[
        (Action::<Jump>::new(), bindings![KeyCode::Space, GamepadButton::South]),
        (Action::<Fire>::new(), bindings![MouseButton::Left, GamepadButton::RightTrigger2]),
    ])
));

player
    .remove_with_requires::<OnFoot>()
    .despawn_related::<Actions<OnFoot>>();

assert_eq!(world.entities().count_spawned(), 1, "only the player entity should be left");
```

Actions aren't despawned automatically via [`EntityWorldMut::remove_with_requires`], since Bevy doesn't automatically
despawn related entities when their relationship targets (like [`Actions<C>`]) are removed. For this reason, [`Actions<C>`]
is not a required component for `C`. See [#20252](https://github.com/bevyengine/bevy/issues/20252) for more details.

When an action is despawned, it automatically transitions its state to [`ActionState::None`] with [`ActionValue::zero`],
triggering the corresponding events. Depending on your use case, using [`ContextActivity`] might be more convenient than removal.
*/

pub mod input_reader;
mod instance;
pub mod time;
mod trigger_tracker;

use core::{
    any::TypeId,
    cmp::{Ordering, Reverse},
    marker::PhantomData,
};

#[cfg(test)]
use bevy::ecs::system::SystemState;
use bevy::{
    ecs::{
        component::ComponentId,
        entity_disabling::Disabled,
        schedule::ScheduleLabel,
        system::{ParamBuilder, QueryParamBuilder},
        world::{FilteredEntityMut, FilteredEntityRef},
    },
    prelude::*,
};
use log::{debug, trace};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};

use crate::{
    action::fns::ActionFns,
    binding::FirstActivation,
    condition::fns::{ConditionFns, ConditionRegistry},
    context::{input_reader::PendingBindings, trigger_tracker::TriggerTracker},
    modifier::fns::{ModifierFns, ModifierRegistry},
    prelude::*,
};
use input_reader::InputReader;
use instance::ContextInstances;

/// An extension trait for [`App`] to assign input to components.
pub trait InputContextAppExt {
    /// Registers type `C` as an input context, whose actions will be evaluated during [`PreUpdate`].
    ///
    /// Action evaluation follows these steps:
    ///
    /// - If the action has an [`ActionMock`] component, use the mocked [`ActionValue`] and [`ActionState`] directly.
    /// - Otherwise, evaluate the action from its bindings:
    ///     1. Iterate over each binding from the [`Bindings`] component.
    ///         1. Read the binding input as an [`ActionValue`], or [`ActionValue::zero`] if the input was already consumed by another action.
    ///            The enum variant depends on the input source.
    ///         2. Apply all binding-level [`InputModifier`]s.
    ///         3. Evaluate all input-level [`InputCondition`]s, combining their results based on their [`InputCondition::kind`].
    ///     2. Select all [`ActionValue`]s with the most significant [`ActionState`] and combine them using the
    ///        [`ActionSettings::accumulation`] strategy.
    ///     3. Convert the combined value to [`ActionOutput::DIM`] using [`ActionValue::convert`].
    ///     4. Apply all action-level [`InputModifier`]s.
    ///     5. Evaluate all action-level [`InputCondition`]s, combining their results based on their [`InputCondition::kind`].
    ///     6. Convert the final value to [`ActionOutput::DIM`] again using [`ActionValue::convert`].
    ///     7. Apply the resulting [`ActionState`] and [`ActionValue`] to the action entity.
    ///     8. If the final state is not [`ActionState::None`], consume the binding input value.
    ///
    /// This logic may look complicated, but you don't have to memorize it. It behaves surprisingly intuitively.
    fn add_input_context<C: Component>(&mut self) -> &mut Self {
        self.add_input_context_to::<PreUpdate, C>()
    }

    /// Like [`Self::add_input_context`], but allows specifying the schedule
    /// in which the context's actions will be evaluated.
    ///
    /// For example, if your game logic runs inside [`FixedMain`](bevy::app::FixedMain), you can set the schedule
    /// to [`FixedPreUpdate`]. This way, if the schedule runs multiple times per frame, events like [`Start`] or
    /// [`Complete`] will be triggered only once per schedule run.
    fn add_input_context_to<S: ScheduleLabel + Default, C: Component>(&mut self) -> &mut Self;
}

impl InputContextAppExt for App {
    fn add_input_context_to<S: ScheduleLabel + Default, C: Component>(&mut self) -> &mut Self {
        debug!(
            "registering `{}` for `{}`",
            ShortName::of::<C>(),
            ShortName::of::<S>(),
        );

        let actions_id = self.world_mut().register_component::<Actions<C>>();
        let activity_id = self.world_mut().register_component::<ContextActivity<C>>();
        let mut registry = self.world_mut().resource_mut::<ContextRegistry>();
        if let Some(contexts) = registry
            .iter_mut()
            .find(|c| c.schedule_id == TypeId::of::<S>())
        {
            debug_assert!(
                !contexts.actions_ids.contains(&actions_id),
                "context `{}` shouldn't be added more than once",
                ShortName::of::<C>()
            );
            contexts.actions_ids.push(actions_id);
            contexts.activity_ids.push(activity_id);
        } else {
            let mut contexts = ScheduleContexts::new::<S>();
            contexts.actions_ids.push(actions_id);
            contexts.activity_ids.push(activity_id);
            registry.push(contexts);
        }

        let _ = self.try_register_required_components::<C, ContextPriority<C>>();
        let _ = self.try_register_required_components::<C, ContextActivity<C>>();

        self.add_observer(register::<C, S>)
            .add_observer(unregister::<C, S>)
            .add_observer(deactivate::<C>)
            .add_observer(reset_action::<C>);

        self
    }
}

/// Tracks registered input contexts for each schedule.
///
/// In Bevy, it's impossible to know which schedule is used inside a system,
/// so we genericize update systems over schedules.
///
/// This resource stores registered contexts per-schedule in a type-erased way
/// to perform the setup after all registrations in [`App::finish`].
///
/// Exists only during the plugin initialization.
#[derive(Resource, Default, Deref, DerefMut)]
pub(crate) struct ContextRegistry(Vec<ScheduleContexts>);

pub(crate) struct ScheduleContexts {
    /// Schedule ID for which all actions were registered.
    schedule_id: TypeId,

    /// IDs of [`Actions<C>`].
    actions_ids: Vec<ComponentId>,

    /// IDs of [`ContextActivity<C>`].
    activity_ids: Vec<ComponentId>,

    /// Configures the app for this schedule.
    setup: fn(&Self, &mut App, &ConditionRegistry, &ModifierRegistry),
}

impl ScheduleContexts {
    /// Creates a new instance for schedule `S`.
    ///
    /// [`Self::setup`] will configure the app for `S`.
    #[must_use]
    fn new<S: ScheduleLabel + Default>() -> Self {
        Self {
            schedule_id: TypeId::of::<S>(),
            actions_ids: Default::default(),
            activity_ids: Default::default(),
            // Since the type is not present in the function signature, we can store
            // functions for specific type without making the struct generic.
            setup: Self::setup_typed::<S>,
        }
    }

    /// Calls [`Self::setup_typed`] for `S` that was associated in [`Self::new`].
    pub(crate) fn setup(
        &self,
        app: &mut App,
        conditions: &ConditionRegistry,
        modifiers: &ModifierRegistry,
    ) {
        (self.setup)(self, app, conditions, modifiers);
    }

    /// Configures the app for all contexts registered for schedule `C`.
    pub(crate) fn setup_typed<S: ScheduleLabel + Default>(
        &self,
        app: &mut App,
        conditions: &ConditionRegistry,
        modifiers: &ModifierRegistry,
    ) {
        debug!("setting up systems for `{}`", ShortName::of::<S>());

        let update_fn = (
            ParamBuilder,
            ParamBuilder,
            ParamBuilder,
            ParamBuilder,
            QueryParamBuilder::new(|builder| {
                builder
                    .data::<Option<&GamepadDevice>>()
                    .optional(|builder| {
                        for &id in &self.activity_ids {
                            builder.mut_id(id);
                        }
                        for &id in &self.actions_ids {
                            builder.mut_id(id);
                        }
                    });
            }),
            ParamBuilder,
            ParamBuilder,
            ParamBuilder,
            QueryParamBuilder::new(|builder| {
                builder.optional(|builder| {
                    for &id in &**conditions {
                        builder.mut_id(id);
                    }
                    for &id in &**modifiers {
                        builder.mut_id(id);
                    }
                });
            }),
        )
            .build_state(app.world_mut())
            .build_system(update::<S>);

        let trigger_fn = (
            ParamBuilder,
            ParamBuilder,
            QueryParamBuilder::new(|builder| {
                builder.optional(|builder| {
                    for &id in &self.activity_ids {
                        builder.mut_id(id);
                    }
                    for &id in &self.actions_ids {
                        builder.ref_id(id);
                    }
                });
            }),
            ParamBuilder,
        )
            .build_state(app.world_mut())
            .build_system(apply::<S>);

        app.init_resource::<ContextInstances<S>>()
            .configure_sets(
                S::default(),
                (EnhancedInputSystems::Update, EnhancedInputSystems::Apply).chain(),
            )
            .add_systems(
                S::default(),
                (
                    update_fn.in_set(EnhancedInputSystems::Update),
                    trigger_fn.in_set(EnhancedInputSystems::Apply),
                ),
            );
    }
}

fn register<C: Component, S: ScheduleLabel>(
    insert: On<Insert, ContextPriority<C>>,
    mut instances: ResMut<ContextInstances<S>>,
    contexts: Query<&ContextPriority<C>, Allow<Disabled>>,
) {
    let priority = **contexts.get(insert.entity).unwrap();
    debug!(
        "registering `{}` to `{}` with priority {priority}",
        ShortName::of::<C>(),
        insert.entity
    );

    instances.add::<C>(insert.entity, priority);
}

fn unregister<C: Component, S: ScheduleLabel>(
    replace: On<Replace, ContextPriority<C>>,
    mut instances: ResMut<ContextInstances<S>>,
) {
    debug!(
        "unregistering `{}` from `{}`",
        ShortName::of::<C>(),
        replace.entity,
    );
    instances.remove::<C>(replace.entity);
}

fn deactivate<C: Component>(
    insert: On<Insert, ContextActivity<C>>,
    mut pending: ResMut<PendingBindings>,
    contexts: Query<(&ContextActivity<C>, &Actions<C>)>,
    actions: Query<(&ActionSettings, &Bindings)>,
    bindings: Query<&Binding>,
) {
    let Ok((&active, context_actions)) = contexts.get(insert.entity) else {
        return;
    };

    debug!(
        "setting activity of `{}` to `{}`",
        ShortName::of::<C>(),
        *active,
    );

    if !*active {
        for (settings, action_bindings) in actions.iter_many(context_actions) {
            if settings.require_reset {
                pending.extend(bindings.iter_many(action_bindings).copied());
            }
        }
    }
}

/// Resets action data and triggers corresponding events on removal.
pub(crate) fn reset_action<C: Component>(
    remove: On<Remove, ActionOf<C>>,
    mut commands: Commands,
    mut pending: ResMut<PendingBindings>,
    mut actions: Query<(
        &ActionOf<C>,
        &ActionSettings,
        &ActionFns,
        Option<&Bindings>,
        &mut ActionValue,
        &mut ActionState,
        &mut ActionEvents,
        &mut ActionTime,
    )>,
    bindings: Query<&Binding>,
) {
    let Ok((action_of, settings, fns, action_bindings, mut value, mut state, mut events, mut time)) =
        actions.get_mut(remove.entity)
    else {
        trace!("ignoring reset for `{}`", remove.entity);
        return;
    };

    *time = Default::default();
    events.set_if_neq(ActionEvents::new(*state, ActionState::None));
    state.set_if_neq(Default::default());
    value.set_if_neq(ActionValue::zero(value.dim()));

    fns.trigger(
        &mut commands,
        **action_of,
        remove.entity,
        *state,
        *events,
        *value,
        *time,
    );

    if let Some(action_bindings) = action_bindings
        && settings.require_reset
    {
        pending.extend(bindings.iter_many(action_bindings).copied());
    }
}

/// Marks an [`Action<C>`] as manually mocked, skipping the [`EnhancedInputSystems::Update`] logic for it.
///
/// This allows modifying any action data without its values being overridden during evaluation.
///
/// Takes precedence over [`ActionMock`], which drives specific [`ActionValue`] and [`ActionState`] during evaluation.
#[derive(Component)]
pub struct ExternallyMocked;

#[allow(clippy::too_many_arguments)]
fn update<S: ScheduleLabel>(
    mut consume_buffer: Local<Vec<Binding>>, // Consumed inputs during state evaluation.
    time: ContextTime,
    mut reader: InputReader,
    instances: Res<ContextInstances<S>>,
    mut contexts: Query<FilteredEntityMut>,
    mut actions: Query<
        (
            Entity,
            &Name,
            &ActionSettings,
            Option<&Bindings>,
            Option<&ModifierFns>,
            Option<&ConditionFns>,
            &mut ActionMock,
        ),
        Without<ExternallyMocked>,
    >,
    mut actions_data: Query<(
        &'static mut ActionValue,
        &'static mut ActionState,
        &'static mut ActionEvents,
        &'static mut ActionTime,
    )>,
    mut bindings: Query<
        (
            Entity,
            &Binding,
            &mut FirstActivation,
            Option<&ModifierFns>,
            Option<&ConditionFns>,
        ),
        Without<ActionSettings>,
    >,
    mut conds_and_mods: Query<FilteredEntityMut>,
) {
    reader.clear_consumed::<S>();

    for instance in &**instances {
        let Ok(mut context) = contexts.get_mut(instance.entity) else {
            trace!(
                "skipping updating `{}` on disabled `{}`",
                instance.name, instance.entity
            );
            continue;
        };

        let gamepad = context.get::<GamepadDevice>().copied().unwrap_or_default();
        let context_active = instance.is_active(&context.as_readonly());
        let Some(mut context_actions) = instance.actions_mut(&mut context) else {
            continue;
        };

        let mods_count = |action: &Entity| {
            let Ok((.., action_bindings, _, _, _)) = actions.get(*action) else {
                return Reverse(0);
            };

            let value = bindings
                .iter_many(action_bindings.into_iter().flatten())
                .map(|(_, b, ..)| b.mod_keys_count())
                .max()
                .unwrap_or(0);
            Reverse(value)
        };

        if !context_actions.is_sorted_by_key(mods_count) {
            context_actions.sort_by_cached_key(mods_count);
        }

        trace!("updating `{}` on `{}`", instance.name, instance.entity);

        reader.set_gamepad(gamepad);

        let mut actions_iter = actions.iter_many_mut(&*context_actions);
        while let Some((
            action,
            action_name,
            action_settings,
            action_bindings,
            modifiers,
            conditions,
            mut mock,
        )) = actions_iter.fetch_next()
        {
            let action_name = ShortName(action_name);
            let (new_state, new_value) = if !context_active {
                trace!("skipping updating `{action_name}` due to inactive context");
                let dim = actions_data.get(action).map(|(v, ..)| v.dim()).unwrap();
                (ActionState::None, ActionValue::zero(dim))
            } else if mock.enabled {
                trace!("updating `{action_name}` from `{mock:?}`");
                let expired = match &mut mock.span {
                    MockSpan::Updates(ticks) => {
                        *ticks = ticks.saturating_sub(1);
                        *ticks == 0
                    }
                    MockSpan::Duration(duration) => {
                        *duration = duration.saturating_sub(time.delta());
                        trace!("reducing mock duration by {:?}", time.delta());
                        duration.is_zero()
                    }
                    MockSpan::Manual => false,
                };

                let new_state = mock.state;
                let new_value = mock.value;
                if expired {
                    mock.enabled = false;
                }

                (new_state, new_value)
            } else {
                trace!("updating `{action_name}` from input");

                let dim = actions_data.get(action).map(|(v, ..)| v.dim()).unwrap();
                let actions_data = actions_data.as_readonly();
                let mut tracker = TriggerTracker::new(ActionValue::zero(dim));
                let mut bindings_iter =
                    bindings.iter_many_mut(action_bindings.into_iter().flatten());
                while let Some((
                    binding_entity,
                    &binding,
                    mut first_activation,
                    modifiers,
                    conditions,
                )) = bindings_iter.fetch_next()
                {
                    let new_value = reader.value(binding);
                    if action_settings.require_reset && **first_activation {
                        // Ignore until we read zero for this mapping.
                        if new_value.as_bool() {
                            // Mark the binding input as consumed regardless of the end action state.
                            reader.consume::<S>(binding);
                            continue;
                        } else {
                            **first_activation = false;
                        }
                    }

                    let mut binding_entity = conds_and_mods.get_mut(binding_entity).unwrap();

                    let mut current_tracker = TriggerTracker::new(new_value);
                    trace!("reading value `{new_value:?}`");
                    if let Some(modifiers) = modifiers {
                        current_tracker.apply_modifiers(
                            &mut binding_entity,
                            &actions_data,
                            &time,
                            modifiers,
                        );
                    }
                    if let Some(conditions) = conditions {
                        current_tracker.apply_conditions(
                            &mut binding_entity,
                            &actions_data,
                            &time,
                            conditions,
                        );
                    }

                    let current_state = current_tracker.state();
                    if current_state == ActionState::None {
                        // Ignore non-active trackers to allow the action to fire even if all
                        // input-level conditions return `ActionState::None`. This ensures that an
                        // action-level condition or modifier can still trigger the action.
                        continue;
                    }

                    match current_state.cmp(&tracker.state()) {
                        Ordering::Less => (),
                        Ordering::Equal => {
                            tracker.combine(current_tracker, action_settings.accumulation);
                            if action_settings.consume_input {
                                consume_buffer.push(binding);
                            }
                        }
                        Ordering::Greater => {
                            tracker.overwrite(current_tracker);
                            if action_settings.consume_input {
                                consume_buffer.clear();
                                consume_buffer.push(binding);
                            }
                        }
                    }
                }

                let mut action = conds_and_mods.get_mut(action).unwrap();
                if let Some(modifiers) = modifiers {
                    tracker.apply_modifiers(&mut action, &actions_data, &time, modifiers);
                }
                if let Some(conditions) = conditions {
                    tracker.apply_conditions(&mut action, &actions_data, &time, conditions);
                }

                let new_state = tracker.state();
                let new_value = tracker.value().convert(dim);

                if action_settings.consume_input {
                    if new_state != ActionState::None {
                        for &binding in &consume_buffer {
                            reader.consume::<S>(binding);
                        }
                    }
                    consume_buffer.clear();
                }

                (new_state, new_value)
            };

            trace!("evaluated to `{new_state:?}` with `{new_value:?}`");

            let (mut value, mut state, mut events, mut action_time) =
                actions_data.get_mut(action).unwrap();

            action_time.update(time.delta_secs(), *state);
            events.set_if_neq(ActionEvents::new(*state, new_state));
            state.set_if_neq(new_state);
            value.set_if_neq(new_value);
        }
    }
}

pub type ActionsQuery<'w, 's> = Query<
    'w,
    's,
    (
        &'static ActionValue,
        &'static ActionState,
        &'static ActionEvents,
        &'static ActionTime,
    ),
>;

fn apply<S: ScheduleLabel>(
    mut commands: Commands,
    instances: Res<ContextInstances<S>>,
    contexts: Query<FilteredEntityRef, Without<ActionFns>>,
    mut actions: Query<EntityMut, With<ActionFns>>,
) {
    for instance in &**instances {
        let Ok(context) = contexts.get(instance.entity) else {
            trace!(
                "skipping triggering for `{}` on disabled `{}`",
                instance.name, instance.entity,
            );
            continue;
        };
        let Some(context_actions) = instance.actions(&context) else {
            continue;
        };

        trace!(
            "running triggers for `{}` on `{}`",
            instance.name, instance.entity,
        );

        let mut actions_iter = actions.iter_many_mut(context_actions);
        while let Some(mut action) = actions_iter.fetch_next() {
            let fns = *action.get::<ActionFns>().unwrap();
            let value = *action.get::<ActionValue>().unwrap();
            fns.store_value(&mut action, value);

            let state = *action.get::<ActionState>().unwrap();
            let events = *action.get::<ActionEvents>().unwrap();
            let time = *action.get::<ActionTime>().unwrap();
            fns.trigger(
                &mut commands,
                context.id(),
                action.id(),
                state,
                events,
                value,
                time,
            );
        }
    }
}

/// Enables or disables all action updates from inputs and mocks for context `C`.
///
/// By default, all contexts are active.
///
/// Inserting [`Self::INACTIVE`] is similar to removing the context. It transitions all context action states
/// to [`ActionState::None`] with [`ActionValue::zero`], triggering the corresponding events.
/// For each action where [`ActionSettings::require_reset`] is set, it will require inputs for its bindings
/// to be inactive before they will be visible to actions from other contexts.
///
/// This is analogous to hiding an entity instead of despawning.
/// Use this component when you want to toggle quickly, preserve bindings, or keep entity IDs.
/// Use removal when the context is truly going away and you don't need it back soon.
///
/// Marked as required for `C` on context registration.
#[derive(Component, Reflect, Deref)]
#[component(immutable)]
pub struct ContextActivity<C> {
    #[deref]
    active: bool,
    #[reflect(ignore)]
    marker: PhantomData<C>,
}

impl<C> ContextActivity<C> {
    /// Active context.
    pub const ACTIVE: Self = Self::new(true);

    /// Inactive context.
    pub const INACTIVE: Self = Self::new(false);

    /// Creates a new instance with the given value.
    #[must_use]
    pub const fn new(active: bool) -> Self {
        Self {
            active,
            marker: PhantomData,
        }
    }

    /// Returns a new instance with the value inverted.
    #[must_use]
    pub const fn toggled(self) -> Self {
        if self.active {
            Self::INACTIVE
        } else {
            Self::ACTIVE
        }
    }
}

impl<C> Default for ContextActivity<C> {
    fn default() -> Self {
        Self::ACTIVE
    }
}

impl<C> Clone for ContextActivity<C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<C> Copy for ContextActivity<C> {}

/// Determines the evaluation order of the input context `C` on the entity.
///
/// Used to control how contexts are layered, as some [`Action<C>`]s may consume inputs.
///
/// The ordering applies per schedule: contexts in schedules that run earlier are evaluated first.
/// Within the same schedule, contexts with a higher priority are evaluated first.
///
/// Ordering matters because actions may "consume" inputs, making them unavailable to other actions
/// until the context that consumed them is evaluated again. This allows contexts layering, where
/// some actions take priority over others. This behavior can be customized per-action by setting
/// [`ActionSettings::consume_input`].
///
/// Marked as required for `C` on context registration.
///
/// # Examples
///
/// ```
/// use bevy::prelude::*;
/// use bevy_enhanced_input::prelude::*;
///
/// # let mut world = World::new();
/// world.spawn((
///     OnFoot,
///     InCar,
///     ContextPriority::<InCar>::new(1), // `InCar` context will be evaluated earlier.
///     // Actions...
/// ));
///
/// #[derive(Component)]
/// struct OnFoot;
///
/// #[derive(Component)]
/// struct InCar;
/// ```
#[derive(Component, Reflect, Deref)]
#[component(immutable)]
pub struct ContextPriority<C> {
    #[deref]
    value: usize,
    #[reflect(ignore)]
    marker: PhantomData<C>,
}

impl<C> ContextPriority<C> {
    pub const fn new(value: usize) -> Self {
        Self {
            value,
            marker: PhantomData,
        }
    }
}

impl<C> Default for ContextPriority<C> {
    fn default() -> Self {
        Self::new(0)
    }
}

impl<C> Clone for ContextPriority<C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<C> Copy for ContextPriority<C> {}

/// Associated gamepad for all input contexts on this entity.
///
/// If not present, input will be read from all connected gamepads.
#[derive(Component, Reflect, Debug, Default, Hash, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
pub enum GamepadDevice {
    /// Matches input from any gamepad.
    ///
    /// For an axis, the [`ActionValue`] will be calculated as the sum of inputs from all gamepads.
    /// For a button, the [`ActionValue`] will be `true` if any gamepad has this button pressed.
    #[default]
    Any,
    /// Matches input from specific gamepad.
    Single(Entity),
    /// Ignores all gamepad input.
    None,
}

impl From<Entity> for GamepadDevice {
    fn from(value: Entity) -> Self {
        Self::Single(value)
    }
}

impl From<Option<Entity>> for GamepadDevice {
    fn from(value: Option<Entity>) -> Self {
        match value {
            Some(entity) => GamepadDevice::Single(entity),
            None => GamepadDevice::None,
        }
    }
}

/// Helper for tests to simplify [`InputTime`] and [`ActionsQuery`] creation.
#[cfg(test)]
pub(crate) fn init_world<'w, 's>() -> (World, SystemState<(ContextTime<'w>, ActionsQuery<'w, 's>)>)
{
    let mut world = World::new();
    world.init_resource::<Time>();
    world.init_resource::<Time<Real>>();

    let state = SystemState::<(ContextTime, ActionsQuery)>::new(&mut world);

    (world, state)
}