Convert distribution to observers

And only distribute your own components
This commit is contained in:
Michael Bradley 2025-10-18 17:49:07 -04:00
parent 1ba4b96863
commit af11fa97fb
Signed by: MichaelBradley
SSH key fingerprint: SHA256:BKO2eI2LPsCbQS3n3i5SdwZTAIV3F1lHezR07qP+Ob0

View file

@ -2,32 +2,51 @@ use bevy::prelude::*;
use super::{ use super::{
packet::{InboundPacket, OutboundPacket, Packet}, packet::{InboundPacket, OutboundPacket, Packet},
peer::{Peer, PeerID}, peer::PeerID,
}; };
#[derive(Component)]
pub struct PeerOwned;
fn spawner<T: TryFrom<Vec<u8>> + Component>( fn spawner<T: TryFrom<Vec<u8>> + Component>(
mut inbound: MessageReader<InboundPacket>, mut inbound: MessageReader<InboundPacket>,
mut commands: Commands, mut commands: Commands,
) { ) {
for InboundPacket(packet) in inbound.read() { for InboundPacket(packet) in inbound.read() {
if let Ok(entity) = T::try_from(packet.message.clone()) { if let Ok(component) = T::try_from(packet.message.clone()) {
commands.spawn(entity); commands.spawn((component, PeerOwned));
} }
} }
} }
fn sender<T: Into<Vec<u8>> + Component + Clone>( fn new_peer<T: Into<Vec<u8>> + Component + Clone>(
peers: Query<&PeerID, Added<Peer>>, add: On<Add, PeerID>,
entities: Query<&T>, peers: Query<&PeerID>,
components: Query<&T, Without<PeerOwned>>,
mut outbound: MessageWriter<OutboundPacket>,
) -> Result {
let peer = peers.get(add.entity)?;
for component in components {
outbound.write(Packet::create(component.clone().into(), peer.id));
}
Ok(())
}
fn new_entity<T: Into<Vec<u8>> + Component + Clone>(
add: On<Add, T>,
peers: Query<&PeerID>,
components: Query<&T, Without<PeerOwned>>,
mut outbound: MessageWriter<OutboundPacket>, mut outbound: MessageWriter<OutboundPacket>,
) { ) {
for peer in peers { if let Ok(component) = components.get(add.entity) {
for entity in entities { for peer in peers {
outbound.write(Packet::create((*entity).clone().into(), peer.id)); outbound.write(Packet::create(component.clone().into(), peer.id));
} }
} }
} }
pub fn distribution_plugin<T: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone>(app: &mut App) { pub fn distribution_plugin<T: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone>(app: &mut App) {
app.add_systems(FixedUpdate, (sender::<T>, spawner::<T>)); app.add_systems(FixedUpdate, spawner::<T>)
.add_observer(new_peer::<T>)
.add_observer(new_entity::<T>);
} }