Remove unused packet variant, move peer UUID to start of packet

This commit is contained in:
Michael Bradley 2025-10-25 22:22:11 -04:00
parent fee5fb3c95
commit fe967d70b9
Signed by: MichaelBradley
SSH key fingerprint: SHA256:BKO2eI2LPsCbQS3n3i5SdwZTAIV3F1lHezR07qP+Ob0
5 changed files with 18 additions and 66 deletions

View file

@ -40,7 +40,7 @@ where
} }
} }
fn spawner<T: NetworkDecodable + Component>( fn incoming_network_entity<T: NetworkDecodable + Component>(
mut inbound: MessageReader<InboundPacket>, mut inbound: MessageReader<InboundPacket>,
mut commands: Commands, mut commands: Commands,
) { ) {
@ -59,7 +59,7 @@ fn new_peer<T: NetworkEncodable + Component>(
) -> Result { ) -> Result {
let peer = peers.get(add.entity)?; let peer = peers.get(add.entity)?;
for component in components { for component in components {
outbound.write(Packet::create(component.encode(), peer.id)); outbound.write(Packet::create(peer.id, component.encode()));
} }
Ok(()) Ok(())
} }
@ -72,13 +72,13 @@ fn new_entity<T: NetworkEncodable + Component>(
) { ) {
if let Ok(component) = components.get(add.entity) { if let Ok(component) = components.get(add.entity) {
for peer in peers { for peer in peers {
outbound.write(Packet::create(component.encode(), peer.id)); outbound.write(Packet::create(peer.id, component.encode()));
} }
} }
} }
pub fn distribution_plugin<T: Networked>(app: &mut App) { pub fn distribution_plugin<T: Networked>(app: &mut App) {
app.add_systems(FixedUpdate, spawner::<T>) app.add_systems(FixedUpdate, incoming_network_entity::<T>)
.add_observer(new_peer::<T>) .add_observer(new_peer::<T>)
.add_observer(new_entity::<T>); .add_observer(new_entity::<T>);
} }

View file

@ -2,7 +2,7 @@ use std::time::Duration;
use bevy::prelude::*; use bevy::prelude::*;
use crate::net::{packet::PacketType, peer::PotentialPeers}; use crate::net::peer::PotentialPeers;
use super::{ use super::{
io::{Config, format_message}, io::{Config, format_message},
@ -24,7 +24,7 @@ pub fn heartbeat(
if last.time() + PING_FREQUENCY > time.elapsed() { if last.time() + PING_FREQUENCY > time.elapsed() {
continue; continue;
} }
outbound.write(Packet::create(Vec::new(), peer.id)); outbound.write(Packet::create(peer.id, Vec::new()));
} }
Ok(()) Ok(())
} }
@ -48,10 +48,7 @@ pub fn ping_potential_peers(
config: Res<Config>, config: Res<Config>,
) -> Result { ) -> Result {
for peer in &peers.addresses { for peer in &peers.addresses {
to_socket.send( to_socket.send(format_message(config.id, &Vec::new()), *peer)?;
format_message(&Vec::new(), PacketType::Peer, config.id),
*peer,
)?;
} }
Ok(()) Ok(())
} }

View file

@ -1,8 +1,6 @@
use bevy::prelude::*; use bevy::prelude::*;
use uuid::Uuid; use uuid::Uuid;
use crate::net::packet::PacketType;
use super::{ use super::{
packet::{InboundPacket, OutboundPacket, Packet}, packet::{InboundPacket, OutboundPacket, Packet},
peer::{PeerChangeMessage, PeerData, PeerMap, PeerReceiveTiming, PeerSendTiming}, peer::{PeerChangeMessage, PeerData, PeerMap, PeerReceiveTiming, PeerSendTiming},
@ -20,8 +18,8 @@ impl Default for Config {
} }
} }
pub fn format_message(data: &Vec<u8>, variant: PacketType, id: Uuid) -> Vec<u8> { pub fn format_message(id: Uuid, data: &Vec<u8>) -> Vec<u8> {
[data.as_slice(), &[variant as u8], id.as_bytes()].concat() [id.as_bytes(), data.as_slice()].concat()
} }
pub fn handle_network_input( pub fn handle_network_input(
@ -65,7 +63,7 @@ pub fn handle_network_output(
for OutboundPacket(packet) in from_app.read() { for OutboundPacket(packet) in from_app.read() {
let peer_id = peer_map.try_get(&packet.peer)?; let peer_id = peer_map.try_get(&packet.peer)?;
let (peer, mut last) = peers.get_mut(*peer_id)?; let (peer, mut last) = peers.get_mut(*peer_id)?;
let message = format_message(&packet.message, packet.variant, config.id); let message = format_message(config.id, &packet.message);
to_socket.send(message, peer.addr.into())?; to_socket.send(message, peer.addr.into())?;
last.update(&time); last.update(&time);
} }

View file

@ -5,58 +5,19 @@ use uuid::Uuid;
pub enum TryFromBytesError { pub enum TryFromBytesError {
InsufficientLength, InsufficientLength,
NotUUID, NotUUID,
NotVariant,
}
#[derive(Clone, Copy, Debug)]
pub enum PacketType {
Standard = 0x00,
Peer = 0x01,
}
impl From<PacketType> for u8 {
fn from(value: PacketType) -> Self {
value as u8
}
}
impl TryFrom<u8> for PacketType {
type Error = TryFromBytesError;
fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
match value {
value if value == PacketType::Standard as u8 => Ok(PacketType::Standard),
value if value == PacketType::Peer as u8 => Ok(PacketType::Peer),
_ => Err(TryFromBytesError::NotVariant),
}
}
} }
pub const UUID_SIZE: usize = 16; pub const UUID_SIZE: usize = 16;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Packet { pub struct Packet {
pub message: Vec<u8>,
pub variant: PacketType,
pub peer: Uuid, pub peer: Uuid,
pub message: Vec<u8>,
} }
impl Packet { impl Packet {
pub fn new(message: Vec<u8>, variant: PacketType, peer: Uuid) -> Self { pub fn create<T: From<Packet>>(peer: Uuid, message: Vec<u8>) -> T {
Self { Self { peer, message }.into()
message,
variant,
peer,
}
}
pub fn create<T: From<Packet>>(message: Vec<u8>, peer: Uuid) -> T {
Self {
message,
variant: PacketType::Standard,
peer,
}
.into()
} }
} }
@ -67,13 +28,9 @@ impl TryFrom<Vec<u8>> for Packet {
if value.len() < UUID_SIZE { if value.len() < UUID_SIZE {
return Err(TryFromBytesError::InsufficientLength); return Err(TryFromBytesError::InsufficientLength);
} }
let uuid = Uuid::from_slice(value.split_off(value.len() - UUID_SIZE).as_slice()) let message = value.split_off(UUID_SIZE);
.map_err(|_| TryFromBytesError::NotUUID)?; let uuid = Uuid::from_slice(value.as_slice()).map_err(|_| TryFromBytesError::NotUUID)?;
let variant = value Ok(Packet::create(uuid, message))
.pop()
.ok_or(TryFromBytesError::InsufficientLength)?
.try_into()?;
Ok(Packet::new(value, variant, uuid))
} }
} }

View file

@ -8,7 +8,7 @@ use std::{
use bevy::prelude::*; use bevy::prelude::*;
use uuid::Uuid; use uuid::Uuid;
use super::packet::{InboundPacket, OutboundPacket, Packet, PacketType}; use super::packet::{InboundPacket, OutboundPacket, Packet};
#[derive(Component, Debug, Default)] #[derive(Component, Debug, Default)]
pub struct PeerSendTiming(Duration); pub struct PeerSendTiming(Duration);
@ -280,7 +280,7 @@ pub fn handle_new_peer(
if change.is_added() { if change.is_added() {
for (_, other, data) in peers { for (_, other, data) in peers {
if peer.id != other.id { if peer.id != other.id {
outbound.write(Packet::new(data.addr.into(), PacketType::Peer, peer.id).into()); outbound.write(Packet::create(peer.id, data.addr.into()));
} }
} }
} }