All checks were successful
CI / Formatting (push) Successful in 1m7s
This is an uncompleted commit to move the work over to my other machine. Should compile though.
69 lines
2.1 KiB
Rust
69 lines
2.1 KiB
Rust
use std::net::SocketAddr;
|
|
|
|
use bevy::prelude::*;
|
|
use uuid::Uuid;
|
|
|
|
use super::{
|
|
io::{handle_network_input, handle_network_output, heartbeat, timeout},
|
|
packet::{InboundPacket, OutboundPacket},
|
|
peer::{PeerChangeEvent, PeerData, PeerMap, handle_new_peer, handle_peer_change},
|
|
queues::{NetworkReceive, NetworkSend},
|
|
socket::bind_socket,
|
|
state::NetworkState,
|
|
};
|
|
|
|
pub struct NetIOPlugin {
|
|
listen: u16,
|
|
peer: Option<SocketAddr>,
|
|
}
|
|
|
|
impl NetIOPlugin {
|
|
pub fn new(listen: u16, peer: Option<SocketAddr>) -> Self {
|
|
Self { listen, peer }
|
|
}
|
|
}
|
|
|
|
impl Plugin for NetIOPlugin {
|
|
fn build(&self, app: &mut App) {
|
|
app.init_state::<NetworkState>()
|
|
.add_systems(
|
|
FixedPreUpdate,
|
|
(handle_network_input, handle_peer_change)
|
|
.chain()
|
|
.run_if(in_state(NetworkState::MultiPlayer)),
|
|
)
|
|
.add_systems(
|
|
FixedUpdate,
|
|
(heartbeat, timeout, handle_new_peer).run_if(in_state(NetworkState::MultiPlayer)),
|
|
)
|
|
.add_systems(
|
|
FixedPostUpdate,
|
|
handle_network_output.run_if(in_state(NetworkState::MultiPlayer)),
|
|
)
|
|
.add_event::<PeerChangeEvent>()
|
|
.add_event::<InboundPacket>()
|
|
.add_event::<OutboundPacket>();
|
|
|
|
match bind_socket(self.listen) {
|
|
Ok((send, receive)) => {
|
|
app.insert_state(NetworkState::MultiPlayer)
|
|
.insert_resource(NetworkSend::new(send))
|
|
.insert_resource(NetworkReceive::new(receive));
|
|
|
|
let mut peer_map = PeerMap::default();
|
|
if let Some(socket) = self.peer {
|
|
let entity = app.world_mut().spawn(PeerData {
|
|
addr: socket.into(),
|
|
me: Uuid::nil(),
|
|
});
|
|
peer_map.insert(Uuid::nil(), entity.id());
|
|
}
|
|
|
|
app.insert_resource(peer_map);
|
|
}
|
|
Err(err) => {
|
|
warn!("Failed to set up networking: {err}");
|
|
}
|
|
};
|
|
}
|
|
}
|