This commit is contained in:
parent
c005a4dbb9
commit
9ac45e9249
6 changed files with 210 additions and 161 deletions
72
src/net/plugin.rs
Normal file
72
src/net/plugin.rs
Normal file
|
@ -0,0 +1,72 @@
|
|||
use std::net::SocketAddr;
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::game::seed::Seed;
|
||||
|
||||
use super::{
|
||||
socket::bind_socket,
|
||||
types::{NetworkReceive, NetworkSend},
|
||||
};
|
||||
|
||||
fn handle_network_io(
|
||||
receive: Res<NetworkReceive>,
|
||||
send: Res<NetworkSend>,
|
||||
seed: Option<Res<Seed>>,
|
||||
mut commands: Commands,
|
||||
) -> Result {
|
||||
for (message, address) in receive.iter() {
|
||||
if let Some(ref value) = seed {
|
||||
send.send((**value).into(), address)?;
|
||||
} else {
|
||||
commands.insert_resource::<Seed>(message.try_into()?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(States, Default, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum NetworkState {
|
||||
#[default]
|
||||
SinglePlayer,
|
||||
MultiPlayer,
|
||||
}
|
||||
|
||||
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(
|
||||
FixedUpdate,
|
||||
handle_network_io.run_if(in_state(NetworkState::MultiPlayer)),
|
||||
);
|
||||
|
||||
match bind_socket(self.listen) {
|
||||
Ok((send, receive)) => {
|
||||
if let Some(socket) = self.peer {
|
||||
if let Err(err) = send.try_send((Vec::new(), socket)) {
|
||||
warn!("Failed to send to peer: {err}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
app.insert_state(NetworkState::MultiPlayer)
|
||||
.insert_resource(NetworkSend::new(send))
|
||||
.insert_resource(NetworkReceive::new(receive));
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to set up networking: {err}");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue