use bevy::prelude::{
App, EventReader, EventWriter, FixedUpdate, IntoSystemConfigs, IntoSystemSetConfigs, Plugin,
ResMut, SystemSet,
};
use crate::netcode::ClientId;
use crate::protocol::Protocol;
use crate::server::resource::Server;
use crate::shared::events::InputEvent;
use crate::shared::sets::FixedUpdateSet;
pub struct InputPlugin<P: Protocol> {
_marker: std::marker::PhantomData<P>,
}
impl<P: Protocol> Default for InputPlugin<P> {
fn default() -> Self {
Self {
_marker: std::marker::PhantomData,
}
}
}
#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum InputSystemSet {
WriteInputEvents,
ClearInputEvents,
}
impl<P: Protocol> Plugin for InputPlugin<P> {
fn build(&self, app: &mut App) {
app.add_event::<InputEvent<P::Input, ClientId>>();
app.configure_sets(
FixedUpdate,
(
FixedUpdateSet::TickUpdate,
InputSystemSet::WriteInputEvents,
FixedUpdateSet::Main,
InputSystemSet::ClearInputEvents,
)
.chain(),
);
app.add_systems(
FixedUpdate,
write_input_event::<P>.in_set(InputSystemSet::WriteInputEvents),
);
app.add_systems(
FixedUpdate,
bevy::ecs::event::event_update_system::<InputEvent<P::Input, ClientId>>
.in_set(InputSystemSet::ClearInputEvents),
);
}
}
fn write_input_event<P: Protocol>(
mut server: ResMut<Server<P>>,
mut input_events: EventWriter<InputEvent<P::Input, ClientId>>,
) {
for (input, client_id) in server.pop_inputs() {
input_events.send(InputEvent::new(input, client_id));
}
}
fn clear_input_events<P: Protocol>(mut input_events: EventReader<InputEvent<P::Input, ClientId>>) {
input_events.clear();
}