azalea_entity/plugin/relative_updates.rs
1// How entity updates are processed (to avoid issues with shared worlds)
2// - each bot contains a map of { entity id: updates received }
3// - the shared world also contains a canonical "true" updates received for each
4// entity
5// - when a client loads an entity, its "updates received" is set to the same as
6// the global "updates received"
7// - when the shared world sees an entity for the first time, the "updates
8// received" is set to 1.
9// - clients can force the shared "updates received" to 0 to make it so certain
10// entities (i.e. other bots in our swarm) don't get confused and updated by
11// other bots
12// - when a client gets an update to an entity, we check if our "updates
13// received" is the same as the shared world's "updates received": if it is,
14// then process the update and increment the client's and shared world's
15// "updates received" if not, then we simply increment our local "updates
16// received" and do nothing else
17
18use std::sync::Arc;
19
20use azalea_world::{MinecraftEntityId, PartialInstance};
21use bevy_ecs::prelude::*;
22use derive_more::{Deref, DerefMut};
23use parking_lot::RwLock;
24use tracing::warn;
25
26use crate::LocalEntity;
27
28/// An [`EntityCommand`] that applies a "relative update" to an entity, which
29/// means this update won't be run multiple times by different clients in the
30/// same world.
31///
32/// This is used to avoid a bug where when there's multiple clients in the same
33/// world and an entity sends a relative move packet to all clients, its
34/// position gets desynced since the relative move is applied multiple times.
35///
36/// Don't use this unless you actually got an entity update packet that all
37/// other clients within render distance will get too. You usually don't need
38/// this when the change isn't relative either.
39pub struct RelativeEntityUpdate {
40 pub partial_world: Arc<RwLock<PartialInstance>>,
41 // a function that takes the entity and updates it
42 pub update: Box<dyn FnOnce(&mut EntityWorldMut) + Send + Sync>,
43}
44impl RelativeEntityUpdate {
45 pub fn new(
46 partial_world: Arc<RwLock<PartialInstance>>,
47 update: impl FnOnce(&mut EntityWorldMut) + Send + Sync + 'static,
48 ) -> Self {
49 Self {
50 partial_world,
51 update: Box::new(update),
52 }
53 }
54}
55
56/// A component that counts the number of times this entity has been modified.
57/// This is used for making sure two clients don't do the same relative update
58/// on an entity.
59///
60/// If an entity is local (i.e. it's a client/LocalEntity), this component
61/// should NOT be present in the entity.
62#[derive(Component, Debug, Deref, DerefMut)]
63pub struct UpdatesReceived(u32);
64
65impl EntityCommand for RelativeEntityUpdate {
66 fn apply(self, mut entity: EntityWorldMut) {
67 let partial_entity_infos = &mut self.partial_world.write().entity_infos;
68
69 if Some(entity.id()) == partial_entity_infos.owner_entity {
70 // if the entity owns this partial world, it's always allowed to update itself
71 (self.update)(&mut entity);
72 return;
73 };
74
75 let entity_id = *entity.get::<MinecraftEntityId>().unwrap();
76 if entity.contains::<LocalEntity>() {
77 // a client tried to update another client, which isn't allowed
78 return;
79 }
80
81 let this_client_updates_received = partial_entity_infos
82 .updates_received
83 .get(&entity_id)
84 .copied();
85
86 let can_update = if let Some(updates_received) = entity.get::<UpdatesReceived>() {
87 this_client_updates_received.unwrap_or(1) == **updates_received
88 } else {
89 // no UpdatesReceived means the entity was just spawned
90 true
91 };
92 if can_update {
93 let new_updates_received = this_client_updates_received.unwrap_or(0) + 1;
94 partial_entity_infos
95 .updates_received
96 .insert(entity_id, new_updates_received);
97
98 entity.insert(UpdatesReceived(new_updates_received));
99
100 (self.update)(&mut entity);
101 }
102 }
103}
104
105/// The [`UpdatesReceived`] component should never be on [`LocalEntity`]
106/// entities. This warns if an entity has both components.
107pub fn debug_detect_updates_received_on_local_entities(
108 query: Query<Entity, (With<LocalEntity>, With<UpdatesReceived>)>,
109) {
110 for entity in &query {
111 warn!(
112 "Entity {:?} has both LocalEntity and UpdatesReceived",
113 entity
114 );
115 }
116}