use super::*;
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum InputBinding {
Key(u32),
MouseButton(u32),
}
#[derive(Clone)]
pub struct ActionMap {
pub(super) bindings: HashMap<String, Vec<InputBinding>>,
}
impl ActionMap {
pub fn new() -> Self {
Self {
bindings: HashMap::new(),
}
}
pub fn bind_key(&mut self, action_name: &str, keycode: u32) {
self.bindings
.entry(action_name.to_string())
.or_default()
.push(InputBinding::Key(keycode));
}
pub fn bind_mouse_button(&mut self, action_name: &str, button: u32) {
self.bindings
.entry(action_name.to_string())
.or_default()
.push(InputBinding::MouseButton(button));
}
pub fn bind_action(&mut self, action_name: &str, keycode: u32) {
self.bind_key(action_name, keycode);
}
pub fn is_action_pressed(&self, input: &Input, action_name: &str) -> bool {
if let Some(bindings) = self.bindings.get(action_name) {
for binding in bindings {
match binding {
InputBinding::Key(k) => {
if input.is_key_pressed(*k) {
return true;
}
}
InputBinding::MouseButton(b) => {
if input.is_mouse_button_pressed(*b) {
return true;
}
}
}
}
}
false
}
pub fn is_action_just_pressed(&self, input: &Input, action_name: &str) -> bool {
if let Some(bindings) = self.bindings.get(action_name) {
for binding in bindings {
match binding {
InputBinding::Key(k) => {
if input.is_key_just_pressed(*k) {
return true;
}
}
InputBinding::MouseButton(b) => {
if input.is_mouse_button_just_pressed(*b) {
return true;
}
}
}
}
}
false
}
pub fn is_action_just_released(&self, input: &Input, action_name: &str) -> bool {
if let Some(bindings) = self.bindings.get(action_name) {
for binding in bindings {
match binding {
InputBinding::Key(k) => {
if input.is_key_just_released(*k) {
return true;
}
}
InputBinding::MouseButton(b) => {
if input.is_mouse_button_just_released(*b) {
return true;
}
}
}
}
}
false
}
}
impl Default for ActionMap {
fn default() -> Self {
Self::new()
}
}