1use std::f64::consts::PI;
2
3use azalea_client::{
4 mining::Mining,
5 tick_broadcast::{TickBroadcast, UpdateBroadcast},
6};
7use azalea_core::{
8 position::{BlockPos, Vec3},
9 tick::GameTick,
10};
11use azalea_entity::{
12 Jumping, LocalEntity, LookDirection, Position, clamp_look_direction,
13 dimensions::EntityDimensions, metadata::Player, update_dimensions,
14};
15use azalea_physics::PhysicsSystems;
16use bevy_app::Update;
17use bevy_ecs::prelude::*;
18use futures_lite::Future;
19use tracing::trace;
20
21use crate::{
22 accept_resource_packs::AcceptResourcePacksPlugin,
23 app::{App, Plugin, PluginGroup, PluginGroupBuilder},
24 auto_respawn::AutoRespawnPlugin,
25 container::ContainerPlugin,
26 ecs::{
27 component::Component,
28 entity::Entity,
29 query::{With, Without},
30 system::{Commands, Query},
31 },
32 pathfinder::PathfinderPlugin,
33};
34
35#[derive(Clone, Default)]
36pub struct BotPlugin;
37impl Plugin for BotPlugin {
38 fn build(&self, app: &mut App) {
39 app.add_message::<LookAtEvent>()
40 .add_message::<JumpEvent>()
41 .add_systems(
42 Update,
43 (
44 insert_bot,
45 look_at_listener
46 .before(clamp_look_direction)
47 .after(update_dimensions),
48 jump_listener,
49 ),
50 )
51 .add_systems(
52 GameTick,
53 stop_jumping
54 .after(PhysicsSystems)
55 .after(azalea_client::movement::send_player_input_packet),
56 );
57 }
58}
59
60#[derive(Default, Component)]
63pub struct Bot {
64 jumping_once: bool,
65}
66
67#[allow(clippy::type_complexity)]
69fn insert_bot(
70 mut commands: Commands,
71 mut query: Query<Entity, (Without<Bot>, With<LocalEntity>, With<Player>)>,
72) {
73 for entity in &mut query {
74 commands.entity(entity).insert(Bot::default());
75 }
76}
77
78fn stop_jumping(mut query: Query<(&mut Jumping, &mut Bot)>) {
79 for (mut jumping, mut bot) in &mut query {
80 if bot.jumping_once && **jumping {
81 bot.jumping_once = false;
82 **jumping = false;
83 }
84 }
85}
86
87pub trait BotClientExt {
88 fn jump(&self);
90 fn look_at(&self, pos: Vec3);
92 fn get_tick_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()>;
94 fn get_update_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()>;
96 fn wait_ticks(&self, n: usize) -> impl Future<Output = ()> + Send;
98 fn wait_updates(&self, n: usize) -> impl Future<Output = ()> + Send;
100 fn mine(&self, position: BlockPos) -> impl Future<Output = ()> + Send;
105}
106
107impl BotClientExt for azalea_client::Client {
108 fn jump(&self) {
109 let mut ecs = self.ecs.lock();
110 ecs.write_message(JumpEvent {
111 entity: self.entity,
112 });
113 }
114
115 fn look_at(&self, position: Vec3) {
116 let mut ecs = self.ecs.lock();
117 ecs.write_message(LookAtEvent {
118 entity: self.entity,
119 position,
120 });
121 }
122
123 fn get_tick_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()> {
142 let ecs = self.ecs.lock();
143 let tick_broadcast = ecs.resource::<TickBroadcast>();
144 tick_broadcast.subscribe()
145 }
146
147 fn get_update_broadcaster(&self) -> tokio::sync::broadcast::Receiver<()> {
155 let ecs = self.ecs.lock();
156 let update_broadcast = ecs.resource::<UpdateBroadcast>();
157 update_broadcast.subscribe()
158 }
159
160 async fn wait_ticks(&self, n: usize) {
167 let mut receiver = self.get_tick_broadcaster();
168 for _ in 0..n {
169 let _ = receiver.recv().await;
170 }
171 }
172 async fn wait_updates(&self, n: usize) {
182 let mut receiver = self.get_update_broadcaster();
183 for _ in 0..n {
184 let _ = receiver.recv().await;
185 }
186 }
187
188 async fn mine(&self, position: BlockPos) {
189 self.start_mining(position);
190
191 let mut receiver = self.get_tick_broadcaster();
192 while receiver.recv().await.is_ok() {
193 let ecs = self.ecs.lock();
194 if ecs.get::<Mining>(self.entity).is_none() {
195 break;
196 }
197 }
198 }
199}
200
201#[derive(Message)]
203pub struct JumpEvent {
204 pub entity: Entity,
205}
206
207pub fn jump_listener(
208 mut query: Query<(&mut Jumping, &mut Bot)>,
209 mut events: MessageReader<JumpEvent>,
210) {
211 for event in events.read() {
212 if let Ok((mut jumping, mut bot)) = query.get_mut(event.entity) {
213 **jumping = true;
214 bot.jumping_once = true;
215 }
216 }
217}
218
219#[derive(Message)]
221pub struct LookAtEvent {
222 pub entity: Entity,
223 pub position: Vec3,
225}
226fn look_at_listener(
227 mut events: MessageReader<LookAtEvent>,
228 mut query: Query<(&Position, &EntityDimensions, &mut LookDirection)>,
229) {
230 for event in events.read() {
231 if let Ok((position, dimensions, mut look_direction)) = query.get_mut(event.entity) {
232 let new_look_direction =
233 direction_looking_at(position.up(dimensions.eye_height.into()), event.position);
234
235 trace!("look at {} (currently at {})", event.position, **position);
236 look_direction.update(new_look_direction);
237 }
238 }
239}
240
241pub fn direction_looking_at(current: Vec3, target: Vec3) -> LookDirection {
244 let delta = target - current;
246 let y_rot = (PI - f64::atan2(-delta.x, -delta.z)) * (180.0 / PI);
247 let ground_distance = f64::sqrt(delta.x * delta.x + delta.z * delta.z);
248 let x_rot = f64::atan2(delta.y, ground_distance) * -(180.0 / PI);
249
250 LookDirection::new(y_rot as f32, x_rot as f32)
251}
252
253pub struct DefaultBotPlugins;
256
257impl PluginGroup for DefaultBotPlugins {
258 fn build(self) -> PluginGroupBuilder {
259 PluginGroupBuilder::start::<Self>()
260 .add(BotPlugin)
261 .add(PathfinderPlugin)
262 .add(ContainerPlugin)
263 .add(AutoRespawnPlugin)
264 .add(AcceptResourcePacksPlugin)
265 }
266}