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///
58/// This is used for making sure two clients don't do the same relative update
59/// on an entity.
60///
61/// If an entity is local (i.e. it's a client/LocalEntity), this component
62/// should NOT be present in the entity.
63#[derive(Component, Debug, Deref, DerefMut)]
64pub struct UpdatesReceived(u32);
65
66impl EntityCommand for RelativeEntityUpdate {
67    fn apply(self, mut entity: EntityWorldMut) {
68        let partial_entity_infos = &mut self.partial_world.write().entity_infos;
69
70        if Some(entity.id()) == partial_entity_infos.owner_entity {
71            // if the entity owns this partial world, it's always allowed to update itself
72            (self.update)(&mut entity);
73            return;
74        };
75
76        let entity_id = *entity.get::<MinecraftEntityId>().unwrap();
77        if entity.contains::<LocalEntity>() {
78            // a client tried to update another client, which isn't allowed
79            return;
80        }
81
82        let this_client_updates_received = partial_entity_infos
83            .updates_received
84            .get(&entity_id)
85            .copied();
86
87        let can_update = if let Some(updates_received) = entity.get::<UpdatesReceived>() {
88            this_client_updates_received.unwrap_or(1) == **updates_received
89        } else {
90            // no UpdatesReceived means the entity was just spawned
91            true
92        };
93        if can_update {
94            let new_updates_received = this_client_updates_received.unwrap_or(0) + 1;
95            partial_entity_infos
96                .updates_received
97                .insert(entity_id, new_updates_received);
98
99            entity.insert(UpdatesReceived(new_updates_received));
100
101            (self.update)(&mut entity);
102        }
103    }
104}
105
106/// A system that logs a warning if an entity has both [`UpdatesReceived`]
107/// and [`LocalEntity`].
108pub fn debug_detect_updates_received_on_local_entities(
109    query: Query<Entity, (With<LocalEntity>, With<UpdatesReceived>)>,
110) {
111    for entity in &query {
112        warn!("Entity {entity:?} has both LocalEntity and UpdatesReceived");
113    }
114}