Skip to main content

azalea_client/
client.rs

1use std::{
2    fmt::Debug,
3    mem,
4    sync::Arc,
5    thread,
6    time::{Duration, Instant},
7};
8
9use azalea_core::tick::GameTick;
10use azalea_entity::{
11    EntityUpdateSystems, PlayerAbilities, indexing::EntityIdIndex, inventory::Inventory,
12};
13use azalea_physics::client_movement::ClientMovementState;
14use azalea_world::Worlds;
15use bevy_app::{App, AppExit, Plugin, PluginsState, SubApp, Update};
16use bevy_ecs::{
17    message::MessageCursor,
18    prelude::*,
19    schedule::{InternedScheduleLabel, LogLevel, ScheduleBuildSettings},
20};
21use parking_lot::RwLock;
22use tokio::{sync::oneshot, time};
23use tracing::{info, warn};
24
25use crate::{
26    attack,
27    block_update::QueuedServerBlockUpdates,
28    chunks::ChunkBatchInfo,
29    connection::RawConnection,
30    cookies::ServerCookies,
31    interact::BlockStatePredictionHandler,
32    local_player::{Experience, Hunger, PermissionLevel, TabList, TabListResource, WorldHolder},
33    mining,
34    movement::LastSentLookDirection,
35    player::retroactively_add_game_profile_component,
36};
37/// A bundle of components that's inserted right when we switch to the `login`
38/// state and stay present on our clients until we disconnect.
39///
40/// For the components that are only present in the `game` state, see
41/// [`JoinedClientBundle`].
42#[derive(Bundle)]
43pub struct LocalPlayerBundle {
44    pub raw_connection: RawConnection,
45    pub world_holder: WorldHolder,
46
47    pub metadata: azalea_entity::metadata::PlayerMetadataBundle,
48}
49
50/// A bundle for the components that are present on a local player that is
51/// currently in the `game` protocol state.
52///
53/// All of these components are also removed when the client disconnects.
54///
55/// If you want to filter for this, use [`InGameState`].
56#[derive(Bundle, Default)]
57pub struct JoinedClientBundle {
58    // note that WorldHolder isn't here because it's set slightly before we
59    // fully join the world
60    pub physics_state: ClientMovementState,
61    pub inventory: Inventory,
62    pub tab_list: TabList,
63    pub block_state_prediction_handler: BlockStatePredictionHandler,
64    pub queued_server_block_updates: QueuedServerBlockUpdates,
65    pub last_sent_direction: LastSentLookDirection,
66    pub abilities: PlayerAbilities,
67    pub permission_level: PermissionLevel,
68    pub chunk_batch_info: ChunkBatchInfo,
69    pub hunger: Hunger,
70    pub experience: Experience,
71    pub cookies: ServerCookies,
72
73    pub entity_id_index: EntityIdIndex,
74
75    pub mining: mining::MineBundle,
76    pub attack: attack::AttackBundle,
77
78    pub in_game_state: InGameState,
79}
80
81/// A marker component for local players that are currently in the
82/// `game` state.
83#[derive(Clone, Component, Debug, Default)]
84pub struct InGameState;
85/// A marker component for local players that are currently in the
86/// `configuration` state.
87#[derive(Clone, Component, Debug, Default)]
88pub struct InConfigState;
89
90pub struct AzaleaPlugin;
91impl Plugin for AzaleaPlugin {
92    fn build(&self, app: &mut App) {
93        app.add_systems(
94            Update,
95            (
96                // add GameProfileComponent when we get an AddPlayerEvent
97                retroactively_add_game_profile_component
98                    .after(EntityUpdateSystems::Index)
99                    .after(crate::join::handle_start_join_server_event),
100            ),
101        )
102        .init_resource::<Worlds>()
103        .init_resource::<TabListResource>();
104    }
105}
106
107/// Create the ECS world, and return a function that begins running systems.
108/// This exists to allow you to make last-millisecond updates to the world
109/// before any systems start running.
110///
111/// You can create your app with `App::new()`, but don't forget to add
112/// [`DefaultPlugins`].
113///
114/// # Panics
115///
116/// This function panics if it's called outside of a Tokio `LocalSet` (or
117/// `LocalRuntime`). This exists so Azalea doesn't unexpectedly run game ticks
118/// in the middle of blocking user code.
119#[doc(hidden)]
120pub fn start_ecs_runner(
121    app: &mut SubApp,
122) -> (
123    Arc<RwLock<World>>,
124    impl FnOnce(),
125    oneshot::Receiver<AppExit>,
126) {
127    // this block is based on Bevy's default runner:
128    // https://github.com/bevyengine/bevy/blob/390877cdae7a17095a75c8f9f1b4241fe5047e83/crates/bevy_app/src/schedule_runner.rs#L77-L85
129    if app.plugins_state() != PluginsState::Cleaned {
130        // Wait for plugins to load
131        if app.plugins_state() == PluginsState::Adding {
132            info!("Waiting for plugins to load ...");
133            while app.plugins_state() == PluginsState::Adding {
134                thread::yield_now();
135            }
136        }
137        // Finish adding plugins and cleanup
138        app.finish();
139        app.cleanup();
140    }
141
142    // all resources should have been added by now so we can take the ecs from
143    // the app
144    let ecs = Arc::new(RwLock::new(mem::take(app.world_mut())));
145
146    let ecs_clone = ecs.clone();
147    let outer_schedule_label = *app.update_schedule.as_ref().unwrap();
148
149    let (appexit_tx, appexit_rx) = oneshot::channel();
150    let start_running_systems = move || {
151        tokio::task::spawn_local(async move {
152            let appexit = run_schedule_loop(ecs_clone, outer_schedule_label).await;
153            appexit_tx.send(appexit)
154        });
155    };
156
157    (ecs, start_running_systems, appexit_rx)
158}
159
160/// Runs the `Update` schedule 60 times per second and the `GameTick` schedule
161/// 20 times per second.
162///
163/// Exits when we receive an `AppExit` event.
164async fn run_schedule_loop(
165    ecs: Arc<RwLock<World>>,
166    outer_schedule_label: InternedScheduleLabel,
167) -> AppExit {
168    let mut last_update: Option<Instant> = None;
169    let mut last_tick: Option<Instant> = None;
170
171    // azalea runs the Update schedule at most 60 times per second to simulate
172    // framerate. unlike vanilla though, we also only handle packets during
173    // Updates due to everything running in ecs systems.
174    const UPDATE_DURATION_TARGET: Duration = Duration::from_micros(1_000_000 / 60);
175    // minecraft runs at 20 tps
176    const GAME_TICK_DURATION_TARGET: Duration = Duration::from_micros(1_000_000 / 20);
177
178    loop {
179        // sleep until the next update if necessary
180        let now = Instant::now();
181        if let Some(last_update) = last_update {
182            let elapsed = now.duration_since(last_update);
183            if elapsed < UPDATE_DURATION_TARGET {
184                time::sleep(UPDATE_DURATION_TARGET - elapsed).await;
185            }
186        }
187        last_update = Some(now);
188
189        let mut ecs = ecs.write();
190
191        // if last tick is None or more than 50ms ago, run the GameTick schedule
192        ecs.run_schedule(outer_schedule_label);
193        if last_tick
194            .map(|last_tick| last_tick.elapsed() > GAME_TICK_DURATION_TARGET)
195            .unwrap_or(true)
196        {
197            if let Some(last_tick) = &mut last_tick {
198                *last_tick += GAME_TICK_DURATION_TARGET;
199
200                // if we're more than 10 ticks behind, set last_tick to now.
201                // vanilla doesn't do it in exactly the same way but it
202                // shouldn't really matter
203                if (now - *last_tick) > GAME_TICK_DURATION_TARGET * 10 {
204                    warn!(
205                        "GameTick is more than 10 ticks behind, skipping ticks so we don't have to burst too much"
206                    );
207                    *last_tick = now;
208                }
209            } else {
210                last_tick = Some(now);
211            }
212            ecs.run_schedule(GameTick);
213        }
214
215        ecs.clear_trackers();
216        if let Some(exit) = should_exit(&mut ecs) {
217            // it's possible for references to the World to stay around, so we
218            // clear the ecs
219            ecs.clear_all();
220            // ^ note that this also forcefully disconnects all of our bots
221            // without sending a disconnect packet (which is fine
222            // because we want to disconnect immediately)
223
224            return exit;
225        }
226    }
227}
228
229/// Checks whether the [`AppExit`] event was sent, and if so returns it.
230///
231/// This is based on Bevy's `should_exit` function: https://github.com/bevyengine/bevy/blob/b9fd7680e78c4073dfc90fcfdc0867534d92abe0/crates/bevy_app/src/app.rs#L1292
232fn should_exit(ecs: &mut World) -> Option<AppExit> {
233    let mut reader = MessageCursor::default();
234
235    let events = ecs.get_resource::<Messages<AppExit>>()?;
236    let mut events = reader.read(events);
237
238    if events.len() != 0 {
239        return Some(
240            events
241                .find(|exit| exit.is_error())
242                .cloned()
243                .unwrap_or(AppExit::Success),
244        );
245    }
246
247    None
248}
249
250pub struct AmbiguityLoggerPlugin;
251impl Plugin for AmbiguityLoggerPlugin {
252    fn build(&self, app: &mut App) {
253        app.edit_schedule(Update, |schedule| {
254            schedule.set_build_settings(ScheduleBuildSettings {
255                ambiguity_detection: LogLevel::Warn,
256                ..Default::default()
257            });
258        });
259        app.edit_schedule(GameTick, |schedule| {
260            schedule.set_build_settings(ScheduleBuildSettings {
261                ambiguity_detection: LogLevel::Warn,
262                ..Default::default()
263            });
264        });
265    }
266}