Convert potential peer ping to a timer run condition

This commit is contained in:
Michael Bradley 2025-10-18 17:30:31 -04:00
parent 27b4644730
commit 1ba4b96863
Signed by: MichaelBradley
SSH key fingerprint: SHA256:BKO2eI2LPsCbQS3n3i5SdwZTAIV3F1lHezR07qP+Ob0
2 changed files with 15 additions and 31 deletions

View file

@ -11,11 +11,9 @@ use super::{
queues::NetworkSend,
};
const PING_FREQUENCY: Duration = Duration::from_secs(3);
const MISSED_PINGS: u32 = 3;
pub const PING_FREQUENCY: Duration = Duration::from_secs(1);
const MISSED_PINGS: u32 = 5;
// TODO: Perhaps this needs a state rethink, is Single/Multiplayer actually useful vs Disconnected, Connecting, Connected?
// Would also help to state-scope some of these things, like InitialAddresses vs PeerMap
pub fn heartbeat(
peers: Query<(&PeerID, &PeerSendTiming)>,
time: Res<Time>,
@ -44,34 +42,16 @@ pub fn timeout(
}
}
#[derive(Debug, Resource)]
pub struct PotentialPeerTimer {
timer: Timer,
}
impl Default for PotentialPeerTimer {
fn default() -> Self {
Self {
timer: Timer::new(PING_FREQUENCY, TimerMode::Repeating),
}
}
}
pub fn ping_potential_peers(
mut timer: ResMut<PotentialPeerTimer>,
time: Res<Time>,
peers: Res<PotentialPeers>,
to_socket: Res<NetworkSend>,
config: Res<Config>,
) -> Result {
timer.timer.tick(time.delta());
if timer.timer.is_finished() {
for peer in &peers.addresses {
to_socket.send(
format_message(&Vec::new(), PacketType::Peer, config.id),
*peer,
)?;
}
for peer in &peers.addresses {
to_socket.send(
format_message(&Vec::new(), PacketType::Peer, config.id),
*peer,
)?;
}
Ok(())
}

View file

@ -1,9 +1,9 @@
use std::net::SocketAddr;
use bevy::prelude::*;
use bevy::{prelude::*, time::common_conditions::on_timer};
use super::{
heartbeat::{PotentialPeerTimer, heartbeat, ping_potential_peers, timeout},
heartbeat::{PING_FREQUENCY, heartbeat, ping_potential_peers, timeout},
io::{Config, handle_network_input, handle_network_output},
packet::{InboundPacket, OutboundPacket},
peer::{
@ -39,12 +39,16 @@ impl Plugin for NetIOPlugin {
)
.add_systems(
FixedUpdate,
(heartbeat, timeout, handle_new_peer, ping_potential_peers),
(
heartbeat,
timeout,
handle_new_peer,
ping_potential_peers.run_if(on_timer(PING_FREQUENCY)),
),
)
.add_systems(FixedPostUpdate, handle_network_output)
.init_resource::<Config>()
.init_resource::<PeerMap>()
.init_resource::<PotentialPeerTimer>()
.insert_resource(PotentialPeers::new(self.initial_peers.clone()))
.add_message::<PeerChangeMessage>()
.add_message::<InboundPacket>()