coreheart/crates/input/src/lib.rs

250 lines
7.7 KiB
Rust
Raw Normal View History

2025-08-24 09:42:18 -04:00
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
pub mod actions;
pub mod conditions;
use std::{fs, marker::PhantomData};
use bevy::{
input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll},
platform::collections::HashMap,
prelude::*,
};
2025-08-24 09:42:18 -04:00
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use state::GameSystemSet;
use crate::actions::InputAction;
pub struct InputPlugin;
impl Plugin for InputPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Inputs<FixedUpdate>>()
.init_resource::<Inputs<Update>>()
.configure_sets(Update, GameSystemSet::UpdateInputs)
.add_systems(Startup, setup_input_map)
.add_systems(
Update,
(update_inputs_frame, save_input_map).in_set(GameSystemSet::UpdateInputs),
)
.add_systems(FixedPostUpdate, clear_changed_fixed);
}
}
#[derive(Hash, Clone, Copy, Debug, Reflect, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputMethod {
Unbound,
2025-08-24 09:42:18 -04:00
MouseButton(MouseButton),
KeyCode(KeyCode),
MouseScroll,
2025-08-24 09:42:18 -04:00
MouseMovementX,
MouseMovementY,
}
#[derive(Resource, Serialize, Deserialize)]
pub struct InputMap {
pub map: HashMap<InputMethod, Vec<InputAction>>,
2025-08-24 09:42:18 -04:00
}
impl InputMap {
pub fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = (InputMethod, InputAction)>,
{
let mut map: HashMap<InputMethod, Vec<InputAction>> = HashMap::new();
for (method, action) in iter {
map.entry(method).or_insert_with(Vec::new).push(action);
}
Self { map }
}
2025-08-24 09:42:18 -04:00
fn save_to_file(&self, path: &str) -> Result<()> {
2025-08-24 14:56:42 -04:00
let ron = ron::ser::to_string_pretty(self, PrettyConfig::default())?;
fs::write(path, ron)?;
2025-08-24 09:42:18 -04:00
Ok(())
}
fn load_from_file(path: &str) -> Result<Self> {
let content = fs::read_to_string(path)?;
let input_map = ron::from_str(&content)?;
Ok(input_map)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct InputState {
changed: bool,
value: f32,
}
impl InputState {
pub fn pressed(&self) -> bool {
self.value > 0.
}
pub fn just_pressed(&self) -> bool {
self.pressed() && self.changed
}
pub fn released(&self) -> bool {
!self.pressed()
}
pub fn just_released(&self) -> bool {
self.released() && self.changed
}
pub fn get(&self) -> f32 {
self.value
}
}
#[derive(Resource, Default)]
/// updates before pretick
pub struct Inputs<T> {
schedule: PhantomData<T>,
map: HashMap<InputAction, InputState>,
}
impl<T> Inputs<T> {
pub fn pressed(&self, action: InputAction) -> bool {
self.map.get(&action).map_or(false, |state| state.pressed())
}
pub fn just_pressed(&self, action: InputAction) -> bool {
self.map
.get(&action)
.map_or(false, |state| state.just_pressed())
}
pub fn released(&self, action: InputAction) -> bool {
self.map
.get(&action)
.map_or(false, |state| state.released())
}
pub fn just_released(&self, action: InputAction) -> bool {
self.map
.get(&action)
.map_or(false, |state| state.just_released())
}
pub fn get(&self, action: InputAction) -> f32 {
self.map.get(&action).map_or(0.0, |state| state.get())
}
}
fn update_inputs_frame(
mut fixed_inputs: ResMut<Inputs<FixedUpdate>>,
mut frame_inputs: ResMut<Inputs<Update>>,
input_map: Res<InputMap>,
mouse_movement: Res<AccumulatedMouseMotion>,
mouse_buttons: Res<ButtonInput<MouseButton>>,
mouse_scroll: Res<AccumulatedMouseScroll>,
2025-08-24 09:42:18 -04:00
keyboard: Res<ButtonInput<KeyCode>>,
) {
fn set_value(action: &InputAction, value: f32, map: &mut HashMap<InputAction, InputState>) {
let mut current_state = map.get(action).copied().unwrap_or_default();
if current_state.value != value {
current_state.changed = true;
}
current_state.value = value;
map.insert(*action, current_state);
}
fn add_value(action: &InputAction, value: f32, map: &mut HashMap<InputAction, InputState>) {
let mut current_state = map.get(action).copied().unwrap_or_default();
if value != 0. {
current_state.changed = true;
}
current_state.value += value;
map.insert(*action, current_state);
}
for input in frame_inputs.map.values_mut() {
input.changed = false;
}
for (method, actions) in input_map.map.iter() {
for action in actions.iter() {
match method {
InputMethod::Unbound => {
set_value(action, 0., &mut frame_inputs.map);
set_value(action, 0., &mut fixed_inputs.map);
}
InputMethod::MouseButton(mouse_button) => {
let value = if mouse_buttons.pressed(*mouse_button) {
1.0
} else {
-1.0
};
set_value(action, value, &mut frame_inputs.map);
set_value(action, value, &mut fixed_inputs.map);
}
InputMethod::KeyCode(key_code) => {
let value = if keyboard.pressed(*key_code) {
1.0
} else {
-1.0
};
set_value(action, value, &mut frame_inputs.map);
set_value(action, value, &mut fixed_inputs.map);
}
InputMethod::MouseScroll => {
let value = mouse_scroll.delta.y;
set_value(action, value, &mut frame_inputs.map);
// want to get accumulated mouse movement in here if needed
add_value(action, value, &mut fixed_inputs.map);
}
InputMethod::MouseMovementX => {
let value = mouse_movement.delta.x;
set_value(action, value, &mut frame_inputs.map);
// want to get accumulated mouse movement in here if needed
add_value(action, value, &mut fixed_inputs.map);
}
InputMethod::MouseMovementY => {
let value = mouse_movement.delta.y;
set_value(action, value, &mut frame_inputs.map);
// want to get accumulated mouse movement in here if needed
add_value(action, value, &mut fixed_inputs.map);
}
2025-08-24 09:42:18 -04:00
}
}
}
}
fn clear_changed_fixed(mut fixed_inputs: ResMut<Inputs<FixedUpdate>>) {
for input in fixed_inputs.map.values_mut() {
input.changed = false;
}
}
const INPUT_MAP_PATH: &'static str = "assets/settings/input_map.ron";
fn save_input_map(input_map: Res<InputMap>) {
if input_map.is_changed() {
if let Err(e) = input_map.save_to_file(INPUT_MAP_PATH) {
error!("Failed to save input map: {}", e);
} else {
info!("Input map saved successfully");
}
}
}
fn setup_input_map(mut commands: Commands) {
let input_map = match InputMap::load_from_file(INPUT_MAP_PATH) {
Ok(mut map) => {
2025-08-24 09:42:18 -04:00
info!("Loaded input map");
for (key, value) in InputMap::default().map {
if !map.map.values().any(|v| *v == value) {
info!("missing action {:?}, adding default", value);
map.map.insert(key, value);
}
}
2025-08-24 09:42:18 -04:00
map
}
Err(e) => {
error!("Failed to load input map: {}", e);
default()
}
};
commands.insert_resource(input_map);
}