diff --git a/src/client.rs b/src/client.rs index 7698d426..ba0c690a 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,5 +1,5 @@ use bevy::{ - ecs::{system::SystemState, world::EntityMut}, + ecs::world::EntityMut, prelude::*, utils::{Entry, HashMap}, }; @@ -45,17 +45,13 @@ impl Plugin for ClientPlugin { } impl ClientPlugin { - fn diff_receiving_system(world: &mut World, state: &mut SystemState>) { - let mut client = state.get_mut(world); - let mut last_message = None; - while let Some(message) = client.receive_message(REPLICATION_CHANNEL_ID) { - last_message = Some(message); - } - - if let Some(last_message) = last_message { - WorldDiff::deserialize_to_world(world, last_message) - .expect("server should send only valid world diffs"); - } + fn diff_receiving_system(world: &mut World) { + world.resource_scope(|world, mut client: Mut| { + while let Some(message) = client.receive_message(REPLICATION_CHANNEL_ID) { + WorldDiff::deserialize_to_world(world, message) + .expect("server should send only valid world diffs"); + } + }); } fn ack_sending_system(last_tick: Res, mut client: ResMut) { diff --git a/src/replicon_core.rs b/src/replicon_core.rs index 9cfa3cb8..4ccf8a2c 100644 --- a/src/replicon_core.rs +++ b/src/replicon_core.rs @@ -343,17 +343,24 @@ impl WorldDiff<'_> { } /// Deserializes itself from bytes directly into the world by applying all changes. + /// + /// Does nothing if world already received a more recent diff. + /// See also [`LastTick`]. pub(super) fn deserialize_to_world( world: &mut World, message: Bytes, ) -> Result<(), bincode::Error> { - world.resource_scope(|world, replication_rules: Mut| { - world.resource_scope(|world, mut entity_map: Mut| { - let mut cursor = Cursor::new(message); + let mut cursor = Cursor::new(message); - let tick = bincode::deserialize_from(&mut cursor)?; - world.resource_mut::().0 = tick; + let tick = bincode::deserialize_from(&mut cursor)?; + let mut last_tick = world.resource_mut::(); + if last_tick.0 >= tick { + return Ok(()); + } + last_tick.0 = tick; + world.resource_scope(|world, replication_rules: Mut| { + world.resource_scope(|world, mut entity_map: Mut| { let entities_count: usize = bincode::deserialize_from(&mut cursor)?; for _ in 0..entities_count { let entity = bincode::deserialize_from(&mut cursor)?;