distributed_physics_test/src/net/distribution.rs
Michael Bradley 1a5a628000
All checks were successful
CI / Formatting (push) Successful in 1m7s
Partial: Dedicated Peer distribution system
This is an uncompleted commit to move the work over to my other machine. Should compile though.
2025-07-09 19:37:46 -04:00

49 lines
1.2 KiB
Rust

use bevy::prelude::*;
use super::{
packet::{InboundPacket, OutboundPacket, Packet},
peer::Peer,
state::NetworkState,
};
fn spawner<T: TryFrom<Vec<u8>> + Component>(
mut inbound: EventReader<InboundPacket>,
mut commands: Commands,
) {
for packet in inbound.read() {
if let Ok(entity) = T::try_from(packet.0.message.clone()) {
commands.spawn(entity);
}
}
}
fn sender<T: Into<Vec<u8>> + Component + Clone>(
peers: Query<&Peer, Added<Peer>>,
entities: Query<&T>,
mut outbound: EventWriter<OutboundPacket>,
) {
for peer in peers {
for entity in entities {
outbound.write(OutboundPacket(Packet::new(
(*entity).clone().into(),
peer.id,
)));
}
}
}
pub trait Networked: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone {
fn register(app: &mut App);
}
impl<T> Networked for T
where
T: Into<Vec<u8>> + TryFrom<Vec<u8>> + Component + Clone,
{
fn register(app: &mut App) {
app.add_systems(
FixedUpdate,
(sender::<T>, spawner::<T>).run_if(in_state(NetworkState::MultiPlayer)),
);
}
}