Skip to main content

azalea/pathfinder/
debug.rs

1use azalea_client::{client_chat::SendChatEvent, local_player::WorldHolder};
2use azalea_core::position::Vec3;
3use bevy_ecs::prelude::*;
4
5use super::ExecutingPath;
6use crate::pathfinder::moves::should_mine_block_state;
7
8/// A component that makes bots run /particle commands while pathfinding to show
9/// where they're going.
10///
11/// This requires the bots to have server operator permissions, and it'll make
12/// them spam *a lot* of commands. You may want to run `/gamerule
13/// sendCommandFeedback false` to hide the "Displaying particle minecraft:dust"
14/// spam.
15///
16/// ```
17/// # use azalea::prelude::*;
18/// # use azalea::pathfinder::debug::PathfinderDebugParticles;
19/// # #[derive(Clone, Component, Default)]
20/// # pub struct State;
21///
22/// async fn handle(mut bot: Client, event: azalea::Event, state: State) -> eyre::Result<()> {
23///     match event {
24///         azalea::Event::Init => {
25///             bot.ecs
26///                 .write()
27///                 .entity_mut(bot.entity)
28///                 .insert(PathfinderDebugParticles);
29///         }
30///         _ => {}
31///     }
32///     Ok(())
33/// }
34/// ```
35#[derive(Component)]
36pub struct PathfinderDebugParticles;
37
38pub fn debug_render_path_with_particles(
39    mut query: Query<(Entity, &ExecutingPath, &WorldHolder), With<PathfinderDebugParticles>>,
40    // chat_events is Option because the tests don't have SendChatEvent
41    // and we have to use ResMut<Messages> because bevy doesn't support
42    // Option<MessageWriter>
43    chat_events: Option<ResMut<Messages<SendChatEvent>>>,
44    mut tick_count: Local<usize>,
45) {
46    let Some(mut chat_events) = chat_events else {
47        return;
48    };
49    if *tick_count >= 2 {
50        *tick_count = 0;
51    } else {
52        *tick_count += 1;
53        return;
54    }
55    for (entity, executing_path, world_holder) in &mut query {
56        if executing_path.path.is_empty() {
57            continue;
58        }
59
60        let chunks = &world_holder.shared.read().chunks;
61
62        let mut start = executing_path.last_reached_node;
63        for (i, edge) in executing_path.path.iter().enumerate() {
64            let movement = &edge.movement;
65            let end = movement.target;
66
67            let start_vec3 = start.center();
68            let end_vec3 = end.center();
69
70            let step_count = (start_vec3.distance_to(end_vec3) * 4.0) as usize;
71
72            let target_block_state = chunks.get_block_state(movement.target).unwrap_or_default();
73            let above_target_block_state = chunks
74                .get_block_state(movement.target.up(1))
75                .unwrap_or_default();
76            // this isn't foolproof, there might be another block that could be
77            // mined depending on the move, but it's good enough for debugging
78            // purposes
79            let is_mining = should_mine_block_state(target_block_state)
80                || should_mine_block_state(above_target_block_state);
81
82            let (r, g, b): (f64, f64, f64) = if i == 0 {
83                (0., 1., 0.)
84            } else if is_mining {
85                (1., 0., 0.)
86            } else {
87                (0., 1., 1.)
88            };
89
90            // interpolate between the start and end positions
91            for i in 0..step_count {
92                let percent = i as f64 / step_count as f64;
93                let pos = Vec3 {
94                    x: start_vec3.x + (end_vec3.x - start_vec3.x) * percent,
95                    y: start_vec3.y + (end_vec3.y - start_vec3.y) * percent,
96                    z: start_vec3.z + (end_vec3.z - start_vec3.z) * percent,
97                };
98                let particle_command = format!(
99                    "/particle dust{{color:[{r},{g},{b}],scale:{size}}} {start_x} {start_y} {start_z} {delta_x} {delta_y} {delta_z} 0 {count}",
100                    size = 1,
101                    start_x = pos.x,
102                    start_y = pos.y,
103                    start_z = pos.z,
104                    delta_x = 0,
105                    delta_y = 0,
106                    delta_z = 0,
107                    count = 1
108                );
109                chat_events.write(SendChatEvent {
110                    entity,
111                    content: particle_command,
112                });
113            }
114
115            start = movement.target;
116        }
117    }
118}