Skip to main content

azalea/pathfinder/execute/
mod.rs

1pub mod patching;
2pub mod simulation;
3
4use std::{cmp, time::Duration};
5
6use azalea_block::BlockState;
7use azalea_client::{
8    StartSprintEvent, StartWalkEvent,
9    local_player::WorldHolder,
10    mining::{Mining, MiningSystems, StartMiningBlockEvent},
11};
12use azalea_core::{position::Vec3, tick::GameTick};
13use azalea_entity::{Physics, Position, inventory::Inventory};
14use azalea_physics::{PhysicsSystems, get_block_pos_below_that_affects_movement};
15use azalea_world::{WorldName, Worlds};
16use bevy_app::{App, Plugin};
17use bevy_ecs::prelude::*;
18use tracing::{debug, info, trace, warn};
19
20use crate::{
21    WalkDirection,
22    bot::{JumpEvent, LookAtEvent},
23    ecs::{
24        entity::Entity,
25        query::Without,
26        system::{Commands, Query, Res},
27    },
28    pathfinder::{
29        ExecutingPath, GotoEvent, Pathfinder, PathfinderSystems,
30        astar::PathfinderTimeout,
31        custom_state::CustomPathfinderState,
32        debug::debug_render_path_with_particles,
33        execute::simulation::SimulatingPathState,
34        moves::{ExecuteCtx, IsReachedCtx},
35        player_pos_to_block_pos,
36    },
37};
38
39pub struct DefaultPathfinderExecutionPlugin;
40impl Plugin for DefaultPathfinderExecutionPlugin {
41    fn build(&self, _app: &mut App) {}
42
43    fn finish(&self, app: &mut App) {
44        if app.is_plugin_added::<simulation::SimulationPathfinderExecutionPlugin>() {
45            info!("pathfinder simulation executor plugin is enabled, disabling default executor.");
46            return;
47        }
48
49        app.add_systems(
50            GameTick,
51            (
52                timeout_movement,
53                patching::check_for_path_obstruction,
54                check_node_reached,
55                tick_execute_path,
56                recalculate_near_end_of_path,
57                recalculate_if_has_goal_but_no_path,
58            )
59                .chain()
60                .after(PhysicsSystems)
61                .after(azalea_client::movement::send_position)
62                .after(MiningSystems)
63                .after(debug_render_path_with_particles)
64                .in_set(PathfinderSystems),
65        );
66    }
67}
68
69#[allow(clippy::type_complexity)]
70pub fn tick_execute_path(
71    mut commands: Commands,
72    mut query: Query<(
73        Entity,
74        &mut ExecutingPath,
75        &Position,
76        &Physics,
77        Option<&Mining>,
78        &WorldHolder,
79        &Inventory,
80    )>,
81    mut look_at_events: MessageWriter<LookAtEvent>,
82    mut sprint_events: MessageWriter<StartSprintEvent>,
83    mut walk_events: MessageWriter<StartWalkEvent>,
84    mut jump_events: MessageWriter<JumpEvent>,
85    mut start_mining_events: MessageWriter<StartMiningBlockEvent>,
86) {
87    for (entity, mut executing_path, position, physics, mining, world_holder, inventory) in
88        &mut query
89    {
90        executing_path.ticks_since_last_node_reached += 1;
91
92        if let Some(edge) = executing_path.path.front() {
93            let mut ctx = ExecuteCtx {
94                entity,
95                target: edge.movement.target,
96                position: **position,
97                start: executing_path.last_reached_node,
98                physics,
99                is_currently_mining: mining.is_some(),
100                can_mine: true,
101                world: world_holder.shared.clone(),
102                menu: inventory.inventory_menu.clone(),
103
104                commands: &mut commands,
105                look_at_events: &mut look_at_events,
106                sprint_events: &mut sprint_events,
107                walk_events: &mut walk_events,
108                jump_events: &mut jump_events,
109                start_mining_events: &mut start_mining_events,
110            };
111            ctx.on_tick_start();
112            trace!(
113                "executing move, position: {}, last_reached_node: {}",
114                **position, executing_path.last_reached_node
115            );
116            (edge.movement.data.execute)(ctx);
117        }
118    }
119}
120
121pub fn check_node_reached(
122    mut query: Query<(
123        Entity,
124        &mut Pathfinder,
125        &mut ExecutingPath,
126        &Position,
127        &Physics,
128        &WorldName,
129    )>,
130    mut walk_events: MessageWriter<StartWalkEvent>,
131    mut commands: Commands,
132    worlds: Res<Worlds>,
133) {
134    for (entity, mut pathfinder, mut executing_path, position, physics, world_name) in &mut query {
135        let Some(world) = worlds.get(world_name) else {
136            warn!("entity is pathfinding but not in a valid world");
137            continue;
138        };
139
140        'skip: loop {
141            // we check if the goal was reached *before* actually executing the
142            // movement so we don't unnecessarily execute a movement when it
143            // wasn't necessary
144
145            // see if we already reached any future nodes and can skip ahead
146            for (i, edge) in executing_path
147                .path
148                .clone()
149                .into_iter()
150                .enumerate()
151                .take(60)
152                .rev()
153            {
154                let movement = edge.movement;
155                let is_reached_ctx = IsReachedCtx {
156                    target: movement.target,
157                    start: executing_path.last_reached_node,
158                    position: **position,
159                    physics,
160                };
161                let extra_check = if i == executing_path.path.len() - 1
162                    // only do the extra check if we don't have a new path immediately queued up
163                    && executing_path.is_empty_queued_path()
164                {
165                    // be extra strict about the velocity and centering if we're
166                    // on the last node so we don't fall off
167
168                    let x_difference_from_center = position.x - (movement.target.x as f64 + 0.5);
169                    let z_difference_from_center = position.z - (movement.target.z as f64 + 0.5);
170
171                    let block_pos_below = get_block_pos_below_that_affects_movement(*position);
172
173                    let block_below = {
174                        let world = world.read();
175                        world
176                            .chunks
177                            .get_block_state(block_pos_below)
178                            .unwrap_or(BlockState::AIR)
179                    };
180
181                    // friction for normal blocks is 0.6, for ice it's 0.98
182                    let block_friction = block_below.behavior().friction as f64;
183
184                    // if the block has the default friction, this will multiply
185                    // by 1 for blocks like ice, it'll multiply by a higher
186                    // number
187                    let scaled_velocity = physics.velocity * (0.4 / (1. - block_friction));
188
189                    let x_predicted_offset = (x_difference_from_center + scaled_velocity.x).abs();
190                    let z_predicted_offset = (z_difference_from_center + scaled_velocity.z).abs();
191
192                    // this is to make sure we don't fall off immediately after
193                    // finishing the path
194                    (physics.on_ground() || physics.is_in_water())
195                        && player_pos_to_block_pos(**position) == movement.target
196                        // adding the delta like this isn't a perfect solution but it helps to make
197                        // sure we don't keep going if our delta is high
198                        && x_predicted_offset < 0.2
199                        && z_predicted_offset < 0.2
200                } else {
201                    true
202                };
203
204                if (movement.data.is_reached)(is_reached_ctx) && extra_check {
205                    executing_path.path = executing_path.path.split_off(i + 1);
206                    executing_path.last_reached_node = movement.target;
207                    executing_path.ticks_since_last_node_reached = 0;
208                    trace!("reached node {}", movement.target);
209
210                    if let Some(new_path) = executing_path.queued_path.take() {
211                        debug!(
212                            "swapped path to {:?}",
213                            new_path.iter().take(10).collect::<Vec<_>>()
214                        );
215                        executing_path.path = new_path;
216
217                        if executing_path.path.is_empty() {
218                            info!("the path we just swapped to was empty, so reached end of path");
219                            walk_events.write(StartWalkEvent {
220                                entity,
221                                direction: WalkDirection::None,
222                            });
223                            commands.entity(entity).remove::<ExecutingPath>();
224                            break;
225                        }
226
227                        // run the function again since we just swapped
228                        continue 'skip;
229                    }
230
231                    if executing_path.path.is_empty() {
232                        debug!("pathfinder path is now empty");
233                        walk_events.write(StartWalkEvent {
234                            entity,
235                            direction: WalkDirection::None,
236                        });
237                        commands.entity(entity).remove::<ExecutingPath>();
238                        if let Some(goal) = pathfinder.goal.clone()
239                            && goal.success(movement.target)
240                        {
241                            info!("goal was reached!");
242                            pathfinder.goal = None;
243                            pathfinder.opts = None;
244                        }
245                    }
246
247                    break;
248                }
249            }
250            break;
251        }
252    }
253}
254
255#[allow(clippy::type_complexity)]
256pub fn timeout_movement(
257    mut query: Query<(
258        Entity,
259        &mut Pathfinder,
260        &mut ExecutingPath,
261        &Position,
262        Option<&Mining>,
263        &WorldName,
264        &Inventory,
265        Option<&CustomPathfinderState>,
266        Option<&mut SimulatingPathState>,
267    )>,
268    worlds: Res<Worlds>,
269) {
270    for (
271        entity,
272        mut pathfinder,
273        mut executing_path,
274        position,
275        mining,
276        world_name,
277        inventory,
278        custom_state,
279        simulating_path_state,
280    ) in &mut query
281    {
282        if !executing_path.path.is_empty() {
283            let (start, end) = if let Some(s) = &simulating_path_state
284                && let SimulatingPathState::Simulated(ref simulating_path_state) = **s
285            {
286                (simulating_path_state.start, simulating_path_state.target)
287            } else {
288                (
289                    executing_path.last_reached_node,
290                    executing_path.path[0].movement.target,
291                )
292            };
293
294            let (start, end) = (start.center_bottom(), end.center_bottom());
295            // TODO: use an actual 2d point-line distance formula here instead
296            // of the 3d one lol
297            let xz_distance =
298                point_line_distance_3d(&position.with_y(0.), &(start.with_y(0.), end.with_y(0.)));
299            let y_distance = point_line_distance_1d(position.y, (start.y, end.y));
300
301            let xz_tolerance = 3.;
302            // longer moves have more y tolerance (in case we're climbing a hill
303            // or smth in a single movement)
304            let y_tolerance = start.horizontal_distance_to(end) / 2. + 1.5;
305
306            if xz_distance > xz_tolerance || y_distance > y_tolerance {
307                warn!(
308                    "pathfinder went too far from path (xz_distance={xz_distance}/{xz_tolerance}, y_distance={y_distance}/{y_tolerance}, line is {start} to {end}, point at {}), trying to patch!",
309                    **position
310                );
311
312                if let Some(mut simulating_path_state) = simulating_path_state {
313                    // don't keep executing the simulation
314                    *simulating_path_state = SimulatingPathState::Fail;
315                }
316
317                patch_path_from_timeout(
318                    entity,
319                    &mut executing_path,
320                    &mut pathfinder,
321                    &worlds,
322                    position,
323                    world_name,
324                    custom_state,
325                    inventory,
326                );
327                continue;
328            }
329        }
330
331        // don't timeout if we're mining
332        if let Some(mining) = mining {
333            // also make sure we're close enough to the block that's being mined
334            if mining.pos.distance_squared_to(position.into()) < 6_i32.pow(2) {
335                // also reset the ticks_since_last_node_reached so we don't
336                // timeout after we finish mining
337                executing_path.ticks_since_last_node_reached = 0;
338                continue;
339            }
340        }
341
342        let mut timeout = 2 * 20;
343
344        if simulating_path_state.is_some() {
345            // longer timeout if we're following a simulated path from the other
346            // execution engine
347            timeout = 5 * 20;
348        }
349
350        if executing_path.ticks_since_last_node_reached > timeout
351            && !pathfinder.is_calculating
352            && !executing_path.path.is_empty()
353        {
354            warn!("pathfinder timeout, trying to patch path");
355
356            patch_path_from_timeout(
357                entity,
358                &mut executing_path,
359                &mut pathfinder,
360                &worlds,
361                position,
362                world_name,
363                custom_state,
364                inventory,
365            );
366        }
367    }
368}
369
370#[allow(clippy::too_many_arguments)]
371fn patch_path_from_timeout(
372    entity: Entity,
373    executing_path: &mut ExecutingPath,
374    pathfinder: &mut Pathfinder,
375    worlds: &Worlds,
376    position: &Position,
377    world_name: &WorldName,
378    custom_state: Option<&CustomPathfinderState>,
379    inventory: &Inventory,
380) {
381    executing_path.queued_path = None;
382    let cur_pos = player_pos_to_block_pos(**position);
383    executing_path.last_reached_node = cur_pos;
384
385    let world_lock = worlds
386        .get(world_name)
387        .expect("Entity tried to pathfind but the entity isn't in a valid world");
388    let Some(opts) = pathfinder.opts.clone() else {
389        warn!(
390            "pathfinder was going to patch path because of timeout, but pathfinder.opts was None"
391        );
392        return;
393    };
394
395    let custom_state = custom_state.cloned().unwrap_or_default();
396
397    // try to fix the path without recalculating everything.
398    // (though, it'll still get fully recalculated by
399    // `recalculate_near_end_of_path` if the new path is too short)
400    patching::patch_path(
401        0..=cmp::min(20, executing_path.path.len() - 1),
402        executing_path,
403        pathfinder,
404        inventory,
405        entity,
406        world_lock,
407        custom_state,
408        opts,
409    );
410    // reset last_node_reached_at so we don't immediately try to patch again
411    executing_path.ticks_since_last_node_reached = 0
412}
413
414pub fn recalculate_near_end_of_path(
415    mut query: Query<(Entity, &mut Pathfinder, &mut ExecutingPath)>,
416    mut walk_events: MessageWriter<StartWalkEvent>,
417    mut goto_events: MessageWriter<GotoEvent>,
418    mut commands: Commands,
419) {
420    for (entity, mut pathfinder, mut executing_path) in &mut query {
421        let Some(mut opts) = pathfinder.opts.clone() else {
422            continue;
423        };
424
425        // start recalculating if the path ends soon. 50 is arbitrary, that's
426        // just to make us recalculate once when we start nearing the
427        // end. this doesn't account for skipping nodes, though...
428
429        // TODO: have a variable to store whether we've recalculated, and then
430        // check that `&& path.len() <= 50` to see if we should
431        // recalculate.
432
433        if (executing_path.path.len() == 50 || executing_path.path.len() < 5)
434            && !pathfinder.is_calculating
435            && executing_path.is_path_partial
436            // don't recalculate if we're already planning on switching to a different path
437            && executing_path.queued_path.is_none()
438        {
439            match pathfinder.goal.as_ref().cloned() {
440                Some(goal) => {
441                    debug!("Recalculating path because it's empty or ends soon");
442                    debug!(
443                        "   executing_path.is_path_partial: {}",
444                        executing_path.is_path_partial
445                    );
446
447                    opts.min_timeout = if executing_path.path.len() == 50 {
448                        // we have quite some time until the node is reached,
449                        // soooo we might as well burn some cpu cycles to get a
450                        // good path
451                        PathfinderTimeout::Time(Duration::from_secs(5))
452                    } else {
453                        PathfinderTimeout::Time(Duration::from_secs(1))
454                    };
455
456                    goto_events.write(GotoEvent { entity, goal, opts });
457                    pathfinder.is_calculating = true;
458
459                    if executing_path.path.is_empty() {
460                        if let Some(new_path) = executing_path.queued_path.take() {
461                            executing_path.path = new_path;
462                            if executing_path.path.is_empty() {
463                                info!(
464                                    "the path we just swapped to was empty, so reached end of path"
465                                );
466                                walk_events.write(StartWalkEvent {
467                                    entity,
468                                    direction: WalkDirection::None,
469                                });
470                                commands.entity(entity).remove::<ExecutingPath>();
471                                break;
472                            }
473                        } else {
474                            walk_events.write(StartWalkEvent {
475                                entity,
476                                direction: WalkDirection::None,
477                            });
478                            commands.entity(entity).remove::<ExecutingPath>();
479                        }
480                    }
481                }
482                _ => {
483                    if executing_path.path.is_empty() {
484                        // idk when this can happen but stop moving just in case
485                        walk_events.write(StartWalkEvent {
486                            entity,
487                            direction: WalkDirection::None,
488                        });
489                    }
490                }
491            }
492        }
493    }
494}
495
496pub fn recalculate_if_has_goal_but_no_path(
497    mut query: Query<(Entity, &mut Pathfinder), Without<ExecutingPath>>,
498    mut goto_events: MessageWriter<GotoEvent>,
499) {
500    for (entity, mut pathfinder) in &mut query {
501        if pathfinder.goal.is_some()
502            && !pathfinder.is_calculating
503            && let Some(goal) = pathfinder.goal.as_ref().cloned()
504            && let Some(opts) = pathfinder.opts.clone()
505        {
506            debug!("Recalculating path because it has a goal but no ExecutingPath");
507            goto_events.write(GotoEvent { entity, goal, opts });
508            pathfinder.is_calculating = true;
509        }
510    }
511}
512
513// based on https://stackoverflow.com/a/36425155
514/// Returns the distance of a point from a line.
515///
516/// This is used in the pathfinder for checking if the bot is too far from the
517/// current path.
518pub fn point_line_distance_3d(point: &Vec3, (start, end): &(Vec3, Vec3)) -> f64 {
519    let start_to_end = end - start;
520    let start_to_point = point - start;
521
522    if start_to_point.dot(start_to_end) <= 0. {
523        return start_to_point.length();
524    }
525
526    let end_to_point = point - end;
527    if end_to_point.dot(start_to_end) >= 0. {
528        return end_to_point.length();
529    }
530
531    start_to_end.cross(start_to_point).length() / start_to_end.length()
532}
533pub fn point_line_distance_1d(point: f64, (start, end): (f64, f64)) -> f64 {
534    let min = start.min(end);
535    let max = start.max(end);
536    if point < min {
537        min - point
538    } else if point > max {
539        point - max
540    } else {
541        0.
542    }
543}