Add resource syncronisation
This commit is contained in:
parent
84ff6d6947
commit
c26ff332d8
|
@ -1,3 +1,4 @@
|
|||
use crate::{tcp, Packet};
|
||||
use bevy::prelude::*;
|
||||
use std::{collections::HashMap, io, net::ToSocketAddrs, sync::Arc};
|
||||
|
||||
|
@ -7,8 +8,6 @@ use ::{
|
|||
std::{any::type_name, marker::PhantomData},
|
||||
};
|
||||
|
||||
use crate::{tcp, Packet};
|
||||
|
||||
/// A trait for a handler function.
|
||||
pub trait PacketHandlerFn: Fn(Vec<u8>, &mut World) + Send + Sync + 'static {}
|
||||
|
||||
|
@ -150,6 +149,10 @@ pub trait NetworkExt {
|
|||
#[cfg(all(feature = "sync"))]
|
||||
/// Register a [Component] to be synced.
|
||||
fn sync_component<C: Component + DeserializeOwned + Serialize + Clone>(&mut self) -> &mut Self;
|
||||
|
||||
#[cfg(all(feature = "sync"))]
|
||||
/// Register a [Resource] to be synced.
|
||||
fn sync_resource<R: Resource + DeserializeOwned + Serialize + Clone>(&mut self) -> &mut Self;
|
||||
}
|
||||
|
||||
impl NetworkExt for App {
|
||||
|
@ -224,4 +227,15 @@ impl NetworkExt for App {
|
|||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
fn sync_resource<R: Resource + DeserializeOwned + Serialize>(&mut self) -> &mut Self {
|
||||
self.add_packet_handler::<R, _>(|data, world| match bincode::deserialize::<R>(&data) {
|
||||
Ok(resource) => world.insert_resource(resource),
|
||||
Err(_) => println!("Failed to deserialize packet: {}", type_name::<R>()),
|
||||
})
|
||||
.add_packet_handler::<PhantomData<R>, _>(|_, world| {
|
||||
world.remove_resource::<R>();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -206,6 +206,10 @@ pub trait NetworkExt {
|
|||
#[cfg(all(feature = "sync"))]
|
||||
/// Register a [Component] to be synced.
|
||||
fn sync_component<C: Component + DeserializeOwned + Serialize + Clone>(&mut self) -> &mut Self;
|
||||
|
||||
#[cfg(all(feature = "sync"))]
|
||||
/// Register a [Resource] to be synced.
|
||||
fn sync_resource<R: Resource + DeserializeOwned + Serialize + Clone>(&mut self) -> &mut Self;
|
||||
}
|
||||
|
||||
impl NetworkExt for App {
|
||||
|
@ -280,4 +284,20 @@ impl NetworkExt for App {
|
|||
.add_system(send_components.after(ServerPlugin::send_synced))
|
||||
.add_system(remove_components.after(update_components))
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
fn sync_resource<R: Resource + DeserializeOwned + Serialize + Clone>(&mut self) -> &mut Self {
|
||||
let update = |resource: Res<R>, connections: Query<&ClientConnection>| {
|
||||
for connection in connections.iter() {
|
||||
connection.send(&*resource);
|
||||
}
|
||||
};
|
||||
let remove = |connections: Query<&ClientConnection>| {
|
||||
for connection in connections.iter() {
|
||||
connection.send(&PhantomData::<R>);
|
||||
}
|
||||
};
|
||||
self.add_system(update.run_if(resource_changed::<R>()))
|
||||
.add_system(remove.after(update).run_if(resource_removed::<R>()))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue