Struct ActionMap

Source
pub struct ActionMap { /* private fields */ }
Expand description

Registration/rebinding may allocate. Feeds, consumption and context changes reuse bounded storage. ActionHandle access checks map ownership and bounds in constant time without allocating. Legacy usize access remains available.

Implementations§

Source§

impl ActionMap

Source

pub fn encode_config( &self, settings: ControlSettings, ) -> Result<Vec<u8>, InputError>

Save named mappings by stable action name; host registration order can change.

Source

pub fn apply_config( &mut self, bytes: &[u8], ) -> Result<AppliedConfig, InputError>

Validate the whole file before mutating mappings. Unknown retired action names are counted/ignored; omitted new actions retain host defaults. Shared sources remain allowed for compatibility. Use Self::validate_config to preview them or Self::apply_config_checked to reject conflicts in the current active contexts.

Source

pub fn validate_config( &self, bytes: &[u8], ) -> Result<ConfigValidation, ConfigError>

Preview an import without changing bindings, contexts, held suppression, pending edges, or accumulated motion. Settings are returned, never applied to a platform host. The existing FXIN v1 format remains unchanged.

All decoded bindings must be structurally valid; matched names must also match the host’s action kind, including inactive actions. Unknown names are ignored, and omitted/unnamed actions keep their current bindings. Conflicts are computed from that complete proposed mapping.

Only contexts active under the current stack participate: global is always active, exclusive contexts hide lower contexts, and passthrough contexts allow overlap. Reuse across inactive contexts is legitimate for this snapshot. Revalidate after changing the stack; this is not a promise about future context combinations. Physical values and transient held suppression do not affect diagnostics. Zero-scale bindings are ignored.

This configuration-time operation allocates bounded scratch storage for at most MAX_ACTIONS * MAX_BINDINGS bindings and retains at most MAX_CONFIG_CONFLICTS diagnostic pairs. It does not run on input feeds.

use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId,
    ContextMode, ControlSettings, InputCode};
let mut map = ActionMap::default();
let game = map.create_context("game")?;
let menu = map.create_context("menu")?;
let space = Binding::digital(InputCode::Key(32));
map.named_action("jump", ActionKind::Button, game, vec![space])?;
map.named_action("accept", ActionKind::Button, menu, vec![space])?;
let bytes = map.encode_config(ControlSettings::default())?;
map.set_context(Some(game))?;
map.push_context(menu, ContextMode::Exclusive)?;
assert!(map.validate_config(&bytes)?.conflicts.is_empty());
map.pop_context();
map.push_context(menu, ContextMode::Passthrough)?;
let report = map.validate_config(&bytes)?;
assert_eq!(report.applied.matched, 2);
let conflict = &report.conflicts[0];
assert_eq!(conflict.code, InputCode::Key(32));
assert_eq!(conflict.first.action_name.as_deref(), Some("jump"));
assert_eq!(conflict.second.context_name, "menu");
Source

pub fn apply_config_checked( &mut self, bytes: &[u8], ) -> Result<AppliedConfig, ConfigError>

Import only if the entire file is valid, compatible, and has no active binding conflicts. Any error leaves the map and all pending input intact.

Uses the same current-context snapshot as Self::validate_config, including retained defaults and unnamed actions. Success follows Self::apply_config: matched actions discard pending edges/motion, held buttons require release, and omitted actions retain their state. Hosts can deliberately accept shared sources using apply_config.

use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId,
    ControlSettings, InputCode};
let mut map = ActionMap::default();
let space = Binding::digital(InputCode::Key(32));
let jump = map.named_action("jump", ActionKind::Button, ContextId::GLOBAL, vec![space])?;
map.named_action("fire", ActionKind::Button, ContextId::GLOBAL, vec![space])?;
let bytes = map.encode_config(ControlSettings::default())?;
map.feed(InputCode::Key(32), 1.0);
assert!(map.apply_config_checked(&bytes).is_err());
assert!(map.consume_tick(jump).pressed); // Rejection preserved the edge.
Source§

impl ActionMap

Source

pub fn action(&mut self, bindings: Vec<Binding>) -> usize

Source

pub fn try_action(&mut self, bindings: Vec<Binding>) -> Option<usize>

Source

pub fn named_action( &mut self, name: &str, kind: ActionKind, context: ContextId, bindings: Vec<Binding>, ) -> Result<usize, InputError>

Source

pub fn named_action_handle( &mut self, name: &str, kind: ActionKind, context: ContextId, bindings: Vec<Binding>, ) -> Result<ActionHandle, InputError>

Register a named action and return its ownership-checked handle.

Names, bindings, capacity and contexts follow Self::named_action. A failed registration leaves existing actions and handles unchanged.

use ferravex_play::input::{ActionKind, ActionMap, ContextId};
let mut input = ActionMap::default();
let jump = input.named_action_handle("jump", ActionKind::Button, ContextId::GLOBAL, vec![])?;
assert_eq!(input.action_handle("jump"), Some(jump));
Source

pub fn action_id(&self, name: &str) -> Option<usize>

Source

pub fn action_handle(&self, name: &str) -> Option<ActionHandle>

Resolve an exact registered name once; missing names return None.

This lookup scans registered names. Subsequent Self::peek_handle and Self::consume_tick_handle calls use constant-time validated indexing. Resolution also works while the action’s context is inactive. See ActionHandle for a complete sampling example.

Source

pub fn handle_from_id(&self, id: usize) -> Option<ActionHandle>

Convert an existing in-bounds index into a handle owned by this map.

For migration of legacy/unnamed registrations. A raw index has no owner; this cannot detect an index copied from another map. Pass an index from this map, or prefer Self::action_handle for named lookup.

use ferravex_play::input::ActionMap;
let mut input = ActionMap::default();
let id = input.action(vec![]);
let handle = input.handle_from_id(id).unwrap();
assert_eq!(input.peek_handle(handle)?, input.peek(id));
assert!(input.handle_from_id(usize::MAX).is_none());
Source

pub fn named_actions( &self, ) -> impl Iterator<Item = (usize, &str, ActionKind, ContextId)>

Source

pub fn bindings(&self, id: usize) -> Option<&[Binding]>

Source

pub fn bindings_handle( &self, handle: ActionHandle, ) -> Result<&[Binding], InputError>

Inspect bindings without allocating or consuming pending input.

Stale/foreign handles return InputError::InvalidHandle. See Self::try_rebind_handle for a usage example.

Source

pub fn action_descriptor( &self, handle: ActionHandle, ) -> Result<ActionDescriptor<'_>, InputError>

Inspect metadata and current bindings using an ownership-checked handle.

Stale or foreign handles return InputError::InvalidHandle, even if their index/name matches an action here. Inactive and unbound actions are valid. This does not allocate, consume edges/motion or alter suppression. Work is bounded by the context stack, not the number of actions.

use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
let mut input = ActionMap::default();
let jump = input.named_action_handle("jump", ActionKind::Button, ContextId::GLOBAL, vec![])?;
assert!(input.action_descriptor(jump)?.bindings.is_empty());
input.try_rebind_handle(jump, vec![Binding::digital(InputCode::Key(74))])?;
assert_eq!(input.action_descriptor(jump)?.bindings[0].code, InputCode::Key(74));
Source

pub fn action_descriptors(&self) -> impl ExactSizeIterator + DoubleEndedIterator

Enumerate all actions in registration order without allocating or consuming input.

Includes unnamed, inactive and unbound actions, up to MAX_ACTIONS. Each descriptor carries a handle owned by this map and a borrowed slice of its validated bindings. Filter on ActionDescriptor::context_active for context-aware hints, or keep inactive actions for a controls editor.

use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
let mut input = ActionMap::default();
let jump = input.named_action_handle(
    "jump", ActionKind::Button, ContextId::GLOBAL,
    vec![Binding::digital(InputCode::Key(32))],
)?;
input.feed(InputCode::Key(32), 1.0);
for hint in input.action_descriptors().filter(|hint| hint.context_active) {
    assert_eq!(hint.handle, jump);
    for binding in hint.bindings {
        assert_eq!(binding.code, InputCode::Key(32));
    }
}
assert!(input.consume_tick_handle(jump)?.pressed); // Hints leave the edge queued.
Source

pub fn create_context(&mut self, name: &str) -> Result<ContextId, InputError>

Source

pub fn context(&self, name: &str) -> Option<ContextId>

Source

pub fn push_context( &mut self, id: ContextId, mode: ContextMode, ) -> Result<(), InputError>

Source

pub fn pop_context(&mut self) -> Option<ContextId>

Source

pub fn clear_contexts(&mut self)

Source

pub fn set_context(&mut self, id: Option<ContextId>) -> Result<(), InputError>

Replace the stack with one exclusive context, or clear gameplay contexts. Repeating the active setting does not discard edges or suppress input.

Source

pub fn rebind(&mut self, id: usize, bindings: Vec<Binding>) -> bool

Source

pub fn try_rebind( &mut self, id: usize, bindings: Vec<Binding>, ) -> Result<(), InputError>

Source

pub fn try_rebind_handle( &mut self, handle: ActionHandle, bindings: Vec<Binding>, ) -> Result<(), InputError>

Rebind only if the handle belongs to this map and the bindings are valid.

Failure leaves bindings and pending input unchanged. Success preserves the handle and follows Self::try_rebind: pending input is reset, and already held buttons must release before triggering the new binding.

use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
let mut input = ActionMap::default();
let jump = input.named_action_handle("jump", ActionKind::Button, ContextId::GLOBAL, vec![])?;
input.try_rebind_handle(jump, vec![Binding::digital(InputCode::Key(32))])?;
assert_eq!(input.bindings_handle(jump)?[0].code, InputCode::Key(32));
Source

pub fn feed(&mut self, code: InputCode, value: f32)

Held values normalize to [-1,1]. Relative codes delegate to feed_delta. Unknown/overflowing/nonfinite physical data cannot grow the map without bound.

Source

pub fn feed_delta(&mut self, code: InputCode, value: f32)

Motion accumulates across render frames with no simulation ticks. Consuming one delta action does not erase another action bound to the same source.

Source

pub fn peek(&self, id: usize) -> Action

Source

pub fn peek_handle(&self, handle: ActionHandle) -> Result<Action, InputError>

Read a snapshot without clearing edges or accumulated motion.

Stale/foreign handles return InputError::InvalidHandle, distinct from a valid neutral action. Context masking and held-button suppression are identical to Self::peek; validity does not depend on context activity. See ActionHandle for an example.

Source

pub fn consume_tick(&mut self, id: usize) -> Action

Source

pub fn consume_tick_handle( &mut self, handle: ActionHandle, ) -> Result<Action, InputError>

Sample one action for a simulation tick, clearing its queued edges.

Held axis/button values persist. Delta values are cleared. A press and release between ticks are both returned once, including through copied handles or mixed legacy/typed access: consumption is per action, not per handle. Other actions bound to the same source retain their own input. Stale/foreign handles return InputError::InvalidHandle without consuming anything. See ActionHandle for an example.

Source

pub fn peek_handles<const N: usize>( &self, handles: [ActionHandle; N], ) -> Result<[Action; N], ActionSnapshotError>

Snapshot a fixed group without consuming edges or relative motion.

Duplicate handles receive identical snapshots. All handles must belong to this map, including inactive/unbound actions. At most MAX_ACTIONS handles (counting duplicates) are accepted; an empty group is valid. No allocation occurs. See Self::peek_handles_into for caller storage.

use ferravex_play::input::{ActionMap, Binding, InputCode};
let mut input = ActionMap::default();
let id = input.action(vec![Binding::digital(InputCode::Key(32))]);
let jump = input.handle_from_id(id).unwrap();
input.feed(InputCode::Key(32), 1.0);
let [a, b] = input.peek_handles([jump, jump])?;
assert_eq!(a, b);
assert!(input.consume_tick_handle(jump)?.pressed);
Source

pub fn peek_handles_into( &self, handles: &[ActionHandle], output: &mut [Action], ) -> Result<(), ActionSnapshotError>

Copy snapshots into output[..handles.len()], preserving its tail.

Prevalidates the count, output capacity and every handle before any output write. On error the entire output and all input remain unchanged. Duplicates, context masking and held suppression follow Self::peek_handles. Work is O(handle count), bounded by MAX_ACTIONS, without allocation. A larger output buffer is allowed, including for an empty request.

use ferravex_play::input::{Action, ActionMap};
let mut input = ActionMap::default();
let id = input.action(vec![]);
let handle = input.handle_from_id(id).unwrap();
let sentinel = Action { value: 0.5, pressed: true, released: true };
let mut output = [sentinel; 2];
input.peek_handles_into(&[handle], &mut output)?;
assert_eq!(output, [Action::default(), sentinel]);
Source

pub fn consume_tick_handles<const N: usize>( &mut self, handles: [ActionHandle; N], ) -> Result<[Action; N], ActionSnapshotError>

Capture a fixed group for one executed simulation tick.

Like renderer PlayerInput::take_tick, every duplicate receives the same pre-consumption snapshot. Only requested actions are consumed; held axis/button values persist while pressed/released edges and delta values clear. Other actions, even on the same source, retain their own input. Edges coalesce into flags, not a tap count. Context/focus/suppression policy is unchanged from Self::consume_tick_handle.

The count (at most MAX_ACTIONS, including duplicates) and every handle are validated before consuming anything. Empty groups succeed. There is no allocation or host/time polling. Share the returned array across tick systems; consume again only for the next executed tick. Zero-tick frames must only feed/preview input, so pending taps and motion survive.

This runnable host-loop recipe injects two zero-tick frames followed by a catch-up batch. Issued steps may exceed executed updates if gameplay ends; consumption belongs after the decision to execute each update.

use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
let mut input = ActionMap::default();
let jump = input.named_action_handle("jump", ActionKind::Button,
    ContextId::GLOBAL, vec![Binding::digital(InputCode::Key(32))])?;
let pan = input.named_action_handle("pan", ActionKind::Delta,
    ContextId::GLOBAL, vec![Binding::digital(InputCode::MouseDelta(0))])?;
let mut executed = 0;
let mut requests = 0;
let mut motion = 0.0;
let mut playing = true;
// (host button level, relative motion, issued fixed steps)
for (level, delta, issued) in [(1.0, 3.0, 0), (0.0, 5.0, 0), (0.0, 0.0, 3)] {
    input.feed(InputCode::Key(32), level);
    input.feed_delta(InputCode::MouseDelta(0), delta);
    for _ in 0..issued {
        if !playing { break; }
        let [jump, pan] = input.consume_tick_handles([jump, pan])?;
        // Share these values with rules/animation; emit feedback only if accepted.
        requests += u32::from(jump.pressed);
        motion += pan.value;
        executed += 1;
        if executed == 2 { playing = false; }
    }
}
assert_eq!((executed, requests, motion), (2, 1, 8.0));
Source

pub fn consume_tick_handles_into( &mut self, handles: &[ActionHandle], output: &mut [Action], ) -> Result<(), ActionSnapshotError>

Capture a tick group in caller storage, preserving the unused output tail.

The complete count, output capacity and every handle are checked before any input/output mutation. On error nothing changes. On success all snapshots are copied before clearing any input, so duplicates match Self::consume_tick_handles. O(handle count) work and no allocation.

use ferravex_play::input::{Action, ActionMap, Binding, InputCode};
let mut input = ActionMap::default();
let id = input.action(vec![Binding::digital(InputCode::Key(32))]);
let jump = input.handle_from_id(id).unwrap();
input.feed(InputCode::Key(32), 1.0);
input.feed(InputCode::Key(32), 0.0);
let mut output = [Action::default(); 2];
input.consume_tick_handles_into(&[jump, jump], &mut output)?;
assert_eq!(output[0], output[1]);
assert!(output[0].pressed && output[0].released);
assert_eq!(input.peek_handle(jump)?, Action::default());
Source

pub fn physical_value(&self, code: InputCode) -> f32

Source

pub fn active_codes(&self) -> usize

Source

pub fn suppress_held(&mut self)

Discard queued edges/motion and require already held buttons to release. Axes can resume at their current level without a synthetic press.

Source

pub fn lose_focus(&mut self)

Neutralize held values and discard queued presses/motion on focus loss.

Trait Implementations§

Source§

impl Default for ActionMap

Source§

fn default() -> ActionMap

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.