Skip to main content

azalea/pathfinder/
mod.rs

1//! A pathfinding plugin to make bots able to traverse the world.
2//!
3//! For the new functions on `Client` that the pathfinder adds, see
4//! [`PathfinderClientExt`].
5//!
6//! Note that the pathfinder is highly optimized, but it will be very slow if
7//! it's not compiled with optimizations enabled.
8//!
9//! For smoother and more realistic path execution, also see
10//! [`SimulationPathfinderExecutionPlugin`].
11//!
12//! Much of the pathfinder's code is based on [Baritone](https://github.com/cabaletta/baritone). <3
13//!
14//! [`SimulationPathfinderExecutionPlugin`]: execute::simulation::SimulationPathfinderExecutionPlugin
15
16pub mod astar;
17pub mod costs;
18pub mod custom_state;
19pub mod debug;
20pub mod execute;
21pub mod goals;
22mod goto_event;
23pub mod mining;
24pub mod moves;
25pub mod positions;
26pub mod simulation;
27#[cfg(test)]
28mod tests;
29pub mod world;
30
31use std::{
32    collections::VecDeque,
33    sync::{
34        Arc,
35        atomic::{self, AtomicBool, AtomicUsize},
36    },
37    time::Instant,
38};
39
40use astar::Edge;
41use azalea_client::{
42    StartWalkEvent, client_inventory::InventorySystems, movement::MoveEventsSystems,
43};
44use azalea_core::{
45    position::{BlockPos, Vec3},
46    tick::GameTick,
47};
48use azalea_entity::{LocalEntity, Position, inventory::Inventory, metadata::Player};
49use azalea_world::{WorldName, Worlds};
50use bevy_app::{PreUpdate, Update};
51use bevy_ecs::prelude::*;
52use bevy_tasks::{AsyncComputeTaskPool, Task};
53use custom_state::{CustomPathfinderState, CustomPathfinderStateRef};
54use futures_lite::future;
55pub use goto_event::{GotoEvent, PathfinderOpts};
56use parking_lot::RwLock;
57use positions::RelBlockPos;
58use tokio::sync::broadcast::error::RecvError;
59use tracing::{debug, error, info, warn};
60
61use self::{
62    debug::debug_render_path_with_particles, goals::Goal, mining::MiningCache, moves::SuccessorsFn,
63};
64use crate::{
65    Client, WalkDirection,
66    app::{App, Plugin},
67    ecs::{
68        component::Component,
69        entity::Entity,
70        query::{With, Without},
71        system::{Commands, Query, Res},
72    },
73    pathfinder::{
74        astar::{PathfinderTimeout, a_star},
75        execute::{DefaultPathfinderExecutionPlugin, simulation::SimulatingPathState},
76        moves::MovesCtx,
77        world::CachedWorld,
78    },
79};
80
81#[derive(Clone, Default)]
82pub struct PathfinderPlugin;
83impl Plugin for PathfinderPlugin {
84    fn build(&self, app: &mut App) {
85        app.add_message::<GotoEvent>()
86            .add_message::<PathFoundEvent>()
87            .add_message::<StopPathfindingEvent>()
88            .add_systems(
89                GameTick,
90                debug_render_path_with_particles.in_set(PathfinderSystems),
91            )
92            .add_systems(PreUpdate, add_default_pathfinder.in_set(PathfinderSystems))
93            .add_systems(
94                Update,
95                (
96                    goto_listener,
97                    handle_tasks,
98                    stop_pathfinding_on_world_change,
99                    path_found_listener,
100                    handle_stop_pathfinding_event,
101                )
102                    .chain()
103                    .before(MoveEventsSystems)
104                    .before(InventorySystems)
105                    .in_set(PathfinderSystems),
106            )
107            .add_plugins(DefaultPathfinderExecutionPlugin);
108    }
109}
110
111#[derive(Clone, Debug, Eq, Hash, PartialEq, SystemSet)]
112pub struct PathfinderSystems;
113
114/// A component that makes this client able to pathfind.
115#[derive(Clone, Component, Default)]
116#[non_exhaustive]
117pub struct Pathfinder {
118    pub goal: Option<Arc<dyn Goal>>,
119    pub opts: Option<PathfinderOpts>,
120    pub is_calculating: bool,
121    pub goto_id: Arc<AtomicUsize>,
122}
123
124/// A component that's present on clients that are actively following a
125/// pathfinder path.
126#[derive(Clone, Component)]
127pub struct ExecutingPath {
128    pub path: VecDeque<astar::Edge<BlockPos, moves::MoveData>>,
129    pub queued_path: Option<VecDeque<astar::Edge<BlockPos, moves::MoveData>>>,
130    pub last_reached_node: BlockPos,
131    // count ticks instead of using real time to make our timeouts more
132    // consistent, in case we lag and our ticks take a while
133    pub ticks_since_last_node_reached: usize,
134    pub is_path_partial: bool,
135}
136impl ExecutingPath {
137    pub fn is_empty_queued_path(&self) -> bool {
138        self.queued_path.is_none() || self.queued_path.as_ref().is_some_and(|p| p.is_empty())
139    }
140}
141
142#[derive(Clone, Debug, Message)]
143#[non_exhaustive]
144pub struct PathFoundEvent {
145    pub entity: Entity,
146    pub start: BlockPos,
147    pub path: Option<VecDeque<astar::Edge<BlockPos, moves::MoveData>>>,
148    pub is_partial: bool,
149    pub successors_fn: SuccessorsFn,
150    pub allow_mining: bool,
151}
152
153#[allow(clippy::type_complexity)]
154pub fn add_default_pathfinder(
155    mut commands: Commands,
156    mut query: Query<Entity, (Without<Pathfinder>, With<LocalEntity>, With<Player>)>,
157) {
158    for entity in &mut query {
159        commands.entity(entity).insert(Pathfinder::default());
160    }
161}
162
163pub trait PathfinderClientExt {
164    /// Pathfind to the given goal and wait until either the target is reached
165    /// or the pathfinding is canceled.
166    ///
167    /// You can use [`Self::start_goto`] instead if you don't want to wait.
168    ///
169    /// ```
170    /// # use azalea::prelude::*;
171    /// # use azalea::{BlockPos, pathfinder::goals::BlockPosGoal};
172    /// # async fn example(bot: &Client) {
173    /// bot.goto(BlockPosGoal(BlockPos::new(0, 70, 0))).await;
174    /// # }
175    /// ```
176    fn goto(&self, goal: impl Goal + 'static) -> impl Future<Output = ()>;
177    /// Same as [`Self::goto`], but allows you to set custom options for
178    /// pathfinding, including disabling mining and setting custom moves.
179    ///
180    /// ```
181    /// # use azalea::prelude::*;
182    /// # use azalea::{BlockPos, pathfinder::{goals::BlockPosGoal, PathfinderOpts}};
183    /// # async fn example(bot: &Client) {
184    /// bot.goto_with_opts(
185    ///     BlockPosGoal(BlockPos::new(0, 70, 0)),
186    ///     PathfinderOpts::new().allow_mining(false),
187    /// )
188    /// .await;
189    /// # }
190    /// ```
191    fn goto_with_opts(
192        &self,
193        goal: impl Goal + 'static,
194        opts: PathfinderOpts,
195    ) -> impl Future<Output = ()>;
196    /// Start pathfinding to a given goal.
197    ///
198    /// ```
199    /// # use azalea::prelude::*;
200    /// # use azalea::{BlockPos, pathfinder::goals::BlockPosGoal};
201    /// # fn example(bot: &Client) {
202    /// bot.start_goto(BlockPosGoal(BlockPos::new(0, 70, 0)));
203    /// # }
204    /// ```
205    fn start_goto(&self, goal: impl Goal + 'static);
206    /// Same as [`Self::start_goto`], but allows you to set custom
207    /// options for pathfinding, including disabling mining and setting custom
208    /// moves.
209    ///
210    /// Also see [`Self::goto_with_opts`].
211    fn start_goto_with_opts(&self, goal: impl Goal + 'static, opts: PathfinderOpts);
212    /// Stop calculating a path, and stop moving once the current movement is
213    /// finished.
214    ///
215    /// This behavior exists to prevent the bot from taking damage if
216    /// `stop_pathfinding` was called while executing a parkour jump, but if
217    /// it's undesirable then you may want to consider using
218    /// [`Self::force_stop_pathfinding`] instead.
219    fn stop_pathfinding(&self);
220    /// Stop calculating a path and stop executing the current movement
221    /// immediately.
222    fn force_stop_pathfinding(&self);
223    /// Waits forever until the bot no longer has a pathfinder goal.
224    fn wait_until_goto_target_reached(&self) -> impl Future<Output = ()>;
225    /// Returns true if the pathfinder has no active goal and isn't calculating
226    /// a path.
227    fn is_goto_target_reached(&self) -> bool;
228    /// Whether the pathfinder is currently following a path.
229    ///
230    /// Also see [`Self::is_calculating_path`] and
231    /// [`Self::is_goto_target_reached`].
232    fn is_executing_path(&self) -> bool;
233    /// Whether the pathfinder is currently calculating a path.
234    ///
235    /// Also see [`Self::is_executing_path`] and
236    /// [`Self::is_goto_target_reached`].
237    fn is_calculating_path(&self) -> bool;
238}
239
240impl PathfinderClientExt for Client {
241    async fn goto(&self, goal: impl Goal + 'static) {
242        self.goto_with_opts(goal, PathfinderOpts::new()).await;
243    }
244    async fn goto_with_opts(&self, goal: impl Goal + 'static, opts: PathfinderOpts) {
245        self.start_goto_with_opts(goal, opts);
246        self.wait_until_goto_target_reached().await;
247    }
248    fn start_goto(&self, goal: impl Goal + 'static) {
249        self.start_goto_with_opts(goal, PathfinderOpts::new());
250    }
251    fn start_goto_with_opts(&self, goal: impl Goal + 'static, opts: PathfinderOpts) {
252        self.ecs
253            .write()
254            .write_message(GotoEvent::new(self.entity, goal, opts));
255    }
256    fn stop_pathfinding(&self) {
257        self.ecs.write().write_message(StopPathfindingEvent {
258            entity: self.entity,
259            force: false,
260        });
261    }
262    fn force_stop_pathfinding(&self) {
263        self.ecs.write().write_message(StopPathfindingEvent {
264            entity: self.entity,
265            force: true,
266        });
267    }
268
269    async fn wait_until_goto_target_reached(&self) {
270        // we do this to make sure the event got handled before we start
271        // checking is_goto_target_reached
272        self.wait_updates(1).await;
273
274        let mut tick_broadcaster = self.get_tick_broadcaster();
275        while !self.is_goto_target_reached() {
276            // check every tick
277            match tick_broadcaster.recv().await {
278                Ok(_) => (),
279                Err(RecvError::Closed) => return,
280                Err(err) => warn!("{err}"),
281            };
282        }
283    }
284    fn is_goto_target_reached(&self) -> bool {
285        self.component::<Pathfinder>()
286            .ok()
287            .is_none_or(|p| p.goal.is_none() && !p.is_calculating)
288    }
289    fn is_executing_path(&self) -> bool {
290        self.component::<ExecutingPath>().is_ok()
291    }
292    fn is_calculating_path(&self) -> bool {
293        self.component::<Pathfinder>()
294            .is_ok_and(|p| p.is_calculating)
295    }
296}
297
298#[derive(Component)]
299pub struct ComputePath(Task<Option<PathFoundEvent>>);
300
301#[allow(clippy::type_complexity)]
302pub fn goto_listener(
303    mut commands: Commands,
304    mut events: MessageReader<GotoEvent>,
305    mut path_found_events: MessageWriter<PathFoundEvent>,
306    mut query: Query<(
307        &mut Pathfinder,
308        Option<&mut ExecutingPath>,
309        Option<&SimulatingPathState>,
310        &Position,
311        &WorldName,
312        &Inventory,
313        Option<&CustomPathfinderState>,
314    )>,
315    worlds: Res<Worlds>,
316) {
317    let thread_pool = AsyncComputeTaskPool::get();
318
319    for event in events.read() {
320        let Ok((
321            mut pathfinder,
322            executing_path,
323            simulating_path_state,
324            position,
325            world_name,
326            inventory,
327            custom_state,
328        )) = query.get_mut(event.entity)
329        else {
330            warn!("got goto event for an entity that can't pathfind");
331            continue;
332        };
333
334        // this env variable is set from the build.rs
335        if env!("OPT_LEVEL") == "0" {
336            static WARNED: AtomicBool = AtomicBool::new(false);
337            if !WARNED.swap(true, atomic::Ordering::Relaxed) {
338                warn!(
339                    "Azalea was compiled with no optimizations, which may result in significantly reduced pathfinding performance. Consider following the steps at https://azalea.rs/azalea/#optimization for faster performance in debug mode."
340                )
341            }
342        }
343
344        let cur_pos = player_pos_to_block_pos(**position);
345
346        if event.goal.success(cur_pos) {
347            // we're already at the goal, nothing to do
348            pathfinder.goal = None;
349            pathfinder.opts = None;
350            pathfinder.is_calculating = false;
351            debug!("already at goal, not pathfinding");
352            continue;
353        }
354
355        // we store the goal so it can be recalculated later if necessary
356        pathfinder.goal = Some(event.goal.clone());
357        pathfinder.opts = Some(event.opts.clone());
358        pathfinder.is_calculating = true;
359
360        let world_lock = worlds
361            .get(world_name)
362            .expect("Entity tried to pathfind but the entity isn't in a valid world");
363
364        let goal = event.goal.clone();
365        let entity = event.entity;
366
367        let goto_id_atomic = pathfinder.goto_id.clone();
368
369        let allow_mining = event.opts.allow_mining;
370        let inventory_menu = if allow_mining {
371            Some(inventory.inventory_menu.clone())
372        } else {
373            None
374        };
375
376        let custom_state = custom_state.cloned().unwrap_or_default();
377        let opts = event.opts.clone();
378
379        // if we're executing a path, this might get replaced with something
380        // else
381        let mut start = cur_pos;
382
383        if let Some(mut executing_path) = executing_path {
384            // first try calculating the path instantly, which allows us to
385            // react quickly for easy paths (but we'll fall back to spawning a
386            // thread if this fails)
387
388            // first, try starting at the node that we're going to
389            let instant_path_start = simulating_path_state
390                .and_then(|s| s.as_simulated().map(|s| s.target))
391                .unwrap_or_else(|| {
392                    executing_path
393                        .path
394                        .iter()
395                        .next()
396                        .map(|e| e.movement.target)
397                        .unwrap_or(cur_pos)
398                });
399
400            let path_found_event = calculate_path(CalculatePathCtx {
401                entity,
402                start: instant_path_start,
403                goal: goal.clone(),
404                world_lock: world_lock.clone(),
405                goto_id_atomic: goto_id_atomic.clone(),
406                mining_cache: MiningCache::new(inventory_menu.clone()),
407                custom_state: custom_state.clone(),
408                opts: PathfinderOpts {
409                    min_timeout: PathfinderTimeout::Nodes(2_000),
410                    max_timeout: PathfinderTimeout::Nodes(2_000),
411                    ..opts
412                },
413            });
414
415            if let Some(path_found_event) = path_found_event
416                && !path_found_event.is_partial
417            {
418                debug!("Found path instantly!");
419
420                // instant_path_start needs to be equal to
421                // `executing_path.path.back()` for the path merging in
422                // path_found_listener to work correctly
423                let instant_path_start_index = executing_path
424                    .path
425                    .iter()
426                    .position(|e| e.movement.target == instant_path_start);
427                if let Some(instant_path_start_index) = instant_path_start_index {
428                    let truncate_to_len = instant_path_start_index + 1;
429                    debug!("truncating to {truncate_to_len} for instant path");
430                    executing_path.path.truncate(truncate_to_len);
431
432                    path_found_events.write(path_found_event);
433
434                    // we found the path instantly, so we're done here :)
435                    continue;
436                } else {
437                    warn!(
438                        "we just calculated an instant path, but the start of it isn't in the current path? instant_path_start: {instant_path_start:?}, simulating_path_state: {simulating_path_state:?}, executing_path.path: {:?}",
439                        executing_path.path
440                    )
441                }
442            } else {
443                debug!("Couldn't find path instantly...");
444            }
445
446            if !executing_path.path.is_empty() {
447                // if we're currently pathfinding and got a goto event, start a
448                // little ahead
449
450                let executing_path_limit = 50;
451
452                // truncate the executing path so we can cleanly combine the two
453                // paths later
454                executing_path.path.truncate(executing_path_limit);
455
456                // TODO: this should probably have better handling when we have
457                // a queued path (since it can result in skipped nodes which is
458                // very bad). you should probably write a test for this before
459                // trying to fix it, though.
460                start = executing_path
461                    .path
462                    .back()
463                    .expect("path was just checked to not be empty")
464                    .movement
465                    .target;
466            }
467        }
468
469        if start == cur_pos {
470            info!("got goto {:?}, starting from {start:?}", event.goal);
471        } else {
472            info!(
473                "got goto {:?}, starting from {start:?} (currently at {cur_pos:?})",
474                event.goal,
475            );
476        }
477
478        let mining_cache = MiningCache::new(inventory_menu);
479        let task = thread_pool.spawn(async move {
480            calculate_path(CalculatePathCtx {
481                entity,
482                start,
483                goal,
484                world_lock,
485                goto_id_atomic,
486                mining_cache,
487                custom_state,
488                opts,
489            })
490        });
491
492        commands.entity(event.entity).insert(ComputePath(task));
493    }
494}
495
496/// Convert a player position to a block position, used internally in the
497/// pathfinder.
498///
499/// This is almost the same as `BlockPos::from(position)`, except that non-full
500/// blocks are handled correctly.
501#[inline]
502pub fn player_pos_to_block_pos(position: Vec3) -> BlockPos {
503    // 0.5 to account for non-full blocks
504    BlockPos::from(position.up(0.5))
505}
506
507pub struct CalculatePathCtx {
508    pub entity: Entity,
509    pub start: BlockPos,
510    pub goal: Arc<dyn Goal>,
511    pub world_lock: Arc<RwLock<azalea_world::World>>,
512    pub goto_id_atomic: Arc<AtomicUsize>,
513    pub mining_cache: MiningCache,
514    pub custom_state: CustomPathfinderState,
515
516    pub opts: PathfinderOpts,
517}
518
519/// Calculate the [`PathFoundEvent`] for the given pathfinder options.
520///
521/// You usually want to just use [`PathfinderClientExt::goto`] or send a
522/// [`GotoEvent`] instead of calling this directly.
523///
524/// You are expected to immediately send the `PathFoundEvent` you received after
525/// calling this function. `None` will be returned if the pathfinding was
526/// interrupted by another path calculation.
527pub fn calculate_path(ctx: CalculatePathCtx) -> Option<PathFoundEvent> {
528    debug!("start: {}", ctx.start);
529
530    let goto_id = ctx.goto_id_atomic.fetch_add(1, atomic::Ordering::SeqCst) + 1;
531
532    let origin = ctx.start;
533    let cached_world = CachedWorld::new(ctx.world_lock, origin);
534    let successors = |pos: RelBlockPos| {
535        call_successors_fn(
536            &cached_world,
537            &ctx.mining_cache,
538            &ctx.custom_state.0.read(),
539            ctx.opts.successors_fn,
540            pos,
541        )
542    };
543
544    let start_time = Instant::now();
545
546    let astar::Path {
547        movements,
548        is_partial,
549        cost,
550    } = a_star(
551        RelBlockPos::get_origin(origin),
552        |n| ctx.goal.heuristic(n.apply(origin)),
553        successors,
554        |n| ctx.goal.success(n.apply(origin)),
555        ctx.opts.min_timeout,
556        ctx.opts.max_timeout,
557    );
558    let end_time = Instant::now();
559    debug!("partial: {is_partial:?}, cost: {cost}");
560    let duration = end_time - start_time;
561    if is_partial {
562        if movements.is_empty() {
563            info!("Pathfinder took {duration:?} (empty path)");
564        } else {
565            info!("Pathfinder took {duration:?} (incomplete path)");
566        }
567    } else {
568        info!("Pathfinder took {duration:?}");
569    }
570
571    debug!("Path:");
572    for movement in &movements {
573        debug!("  {}", movement.target.apply(origin));
574    }
575
576    let path = movements.into_iter().collect::<VecDeque<_>>();
577
578    let goto_id_now = ctx.goto_id_atomic.load(atomic::Ordering::SeqCst);
579    if goto_id != goto_id_now {
580        // we must've done another goto while calculating this path, so throw it
581        // away
582        warn!("finished calculating a path, but it's outdated");
583        return None;
584    }
585
586    if path.is_empty() && is_partial {
587        debug!("this path is empty, we might be stuck :(");
588    }
589
590    let mut mapped_path = VecDeque::with_capacity(path.len());
591    let mut current_position = RelBlockPos::get_origin(origin);
592    for movement in path {
593        let mut found_edge = None;
594        for edge in successors(current_position) {
595            if edge.movement.target == movement.target {
596                found_edge = Some(edge);
597                break;
598            }
599        }
600
601        let found_edge = found_edge.expect(
602            "path should always still be possible because we're using the same world cache",
603        );
604        current_position = found_edge.movement.target;
605
606        // we don't just clone the found_edge because we're using BlockPos
607        // instead of RelBlockPos as the target type
608        mapped_path.push_back(Edge {
609            movement: astar::Movement {
610                target: movement.target.apply(origin),
611                data: movement.data,
612            },
613            cost: found_edge.cost,
614        });
615    }
616
617    Some(PathFoundEvent {
618        entity: ctx.entity,
619        start: ctx.start,
620        path: Some(mapped_path),
621        is_partial,
622        successors_fn: ctx.opts.successors_fn,
623        allow_mining: ctx.opts.allow_mining,
624    })
625}
626
627// poll the tasks and send the PathFoundEvent if they're done
628pub fn handle_tasks(
629    mut commands: Commands,
630    mut transform_tasks: Query<(Entity, &mut ComputePath)>,
631    mut path_found_events: MessageWriter<PathFoundEvent>,
632) {
633    for (entity, mut task) in &mut transform_tasks {
634        if let Some(optional_path_found_event) = future::block_on(future::poll_once(&mut task.0)) {
635            if let Some(path_found_event) = optional_path_found_event {
636                path_found_events.write(path_found_event);
637            }
638
639            // Task is complete, so remove task component from entity
640            commands.entity(entity).remove::<ComputePath>();
641        }
642    }
643}
644
645// set the path for the target entity when we get the PathFoundEvent
646#[allow(clippy::type_complexity)]
647pub fn path_found_listener(
648    mut events: MessageReader<PathFoundEvent>,
649    mut query: Query<(
650        &mut Pathfinder,
651        Option<&mut ExecutingPath>,
652        &WorldName,
653        &Inventory,
654        Option<&CustomPathfinderState>,
655    )>,
656    worlds: Res<Worlds>,
657    mut commands: Commands,
658) {
659    for event in events.read() {
660        let Ok((mut pathfinder, executing_path, world_name, inventory, custom_state)) =
661            query.get_mut(event.entity)
662        else {
663            debug!("got path found event for an entity that can't pathfind");
664            continue;
665        };
666        if let Some(found_path) = &event.path {
667            if let Some(mut executing_path) = executing_path {
668                let mut new_path = VecDeque::new();
669
670                // combine the old and new paths if the first node of the new
671                // path is a successor of the last node of the old path
672                if let Some(last_node_of_current_path) = executing_path.path.back() {
673                    let world_lock = worlds
674                        .get(world_name)
675                        .expect("Entity tried to pathfind but the entity isn't in a valid world");
676                    let origin = event.start;
677                    let successors_fn: moves::SuccessorsFn = event.successors_fn;
678                    let cached_world = CachedWorld::new(world_lock, origin);
679                    let mining_cache = MiningCache::new(if event.allow_mining {
680                        Some(inventory.inventory_menu.clone())
681                    } else {
682                        None
683                    });
684                    let custom_state = custom_state.cloned().unwrap_or_default();
685                    let custom_state_ref = custom_state.0.read();
686                    let successors = |pos: RelBlockPos| {
687                        call_successors_fn(
688                            &cached_world,
689                            &mining_cache,
690                            &custom_state_ref,
691                            successors_fn,
692                            pos,
693                        )
694                    };
695
696                    if let Some(first_node_of_new_path) = found_path.front() {
697                        let last_target_of_current_path = RelBlockPos::from_origin(
698                            origin,
699                            last_node_of_current_path.movement.target,
700                        );
701                        let first_target_of_new_path = RelBlockPos::from_origin(
702                            origin,
703                            first_node_of_new_path.movement.target,
704                        );
705
706                        let successors = successors(last_target_of_current_path);
707                        if successors
708                            .iter()
709                            .any(|edge| edge.movement.target == first_target_of_new_path)
710                        {
711                            debug!("combining old and new paths");
712                            debug!(
713                                "old path: {:?}",
714                                executing_path.path.iter().collect::<Vec<_>>()
715                            );
716                            debug!(
717                                "new path: {:?}",
718                                found_path.iter().take(10).collect::<Vec<_>>()
719                            );
720                            new_path.extend(executing_path.path.iter().cloned());
721                        } else {
722                            debug!(
723                                "failed to combine old and new paths. first_target_of_new_path: {first_target_of_new_path:?}, successors: {successors:?}"
724                            )
725                        }
726                    } else {
727                        new_path.extend(executing_path.path.iter().cloned());
728                    }
729                }
730
731                new_path.extend(found_path.to_owned());
732
733                debug!(
734                    "set queued path to {:?}",
735                    new_path.iter().take(10).collect::<Vec<_>>()
736                );
737                executing_path.queued_path = Some(new_path);
738                executing_path.is_path_partial = event.is_partial;
739            } else if found_path.is_empty() {
740                debug!("calculated path is empty, so didn't add ExecutingPath");
741                if !pathfinder.opts.as_ref().is_some_and(|o| o.retry_on_no_path) {
742                    debug!("retry_on_no_path is set to false, removing goal");
743                    pathfinder.goal = None;
744                }
745            } else {
746                commands.entity(event.entity).insert(ExecutingPath {
747                    path: found_path.to_owned(),
748                    queued_path: None,
749                    last_reached_node: event.start,
750                    ticks_since_last_node_reached: 0,
751                    is_path_partial: event.is_partial,
752                });
753                debug!(
754                    "set path to {:?}",
755                    found_path.iter().take(10).collect::<Vec<_>>()
756                );
757                debug!("partial: {}", event.is_partial);
758            }
759        } else {
760            error!("No path found");
761            if let Some(mut executing_path) = executing_path {
762                // set the queued path so we don't stop in the middle of a move
763                executing_path.queued_path = Some(VecDeque::new());
764            } else {
765                // wasn't executing a path, don't need to do anything
766            }
767        }
768        pathfinder.is_calculating = false;
769    }
770}
771
772#[derive(Message)]
773pub struct StopPathfindingEvent {
774    pub entity: Entity,
775    /// Whether we should stop moving immediately without waiting for the
776    /// current movement to finish.
777    ///
778    /// This is usually set to false, since it might cause the bot to fall if it
779    /// was in the middle of parkouring.
780    pub force: bool,
781}
782
783pub fn handle_stop_pathfinding_event(
784    mut events: MessageReader<StopPathfindingEvent>,
785    mut query: Query<(&mut Pathfinder, &mut ExecutingPath)>,
786    mut walk_events: MessageWriter<StartWalkEvent>,
787    mut commands: Commands,
788) {
789    for event in events.read() {
790        // stop computing any path that's being computed
791        commands.entity(event.entity).remove::<ComputePath>();
792
793        let Ok((mut pathfinder, mut executing_path)) = query.get_mut(event.entity) else {
794            continue;
795        };
796        pathfinder.goal = None;
797        if event.force {
798            executing_path.path.clear();
799            executing_path.queued_path = None;
800        } else {
801            // switch to an empty path as soon as it can
802            executing_path.queued_path = Some(VecDeque::new());
803            // make sure it doesn't recalculate
804            executing_path.is_path_partial = false;
805        }
806
807        if executing_path.path.is_empty() {
808            walk_events.write(StartWalkEvent {
809                entity: event.entity,
810                direction: WalkDirection::None,
811            });
812            commands.entity(event.entity).remove::<ExecutingPath>();
813        }
814    }
815}
816
817pub fn stop_pathfinding_on_world_change(
818    mut query: Query<(Entity, &mut ExecutingPath), Changed<WorldName>>,
819    mut stop_pathfinding_events: MessageWriter<StopPathfindingEvent>,
820) {
821    for (entity, mut executing_path) in &mut query {
822        if !executing_path.path.is_empty() {
823            debug!("world changed, clearing path");
824            executing_path.path.clear();
825            stop_pathfinding_events.write(StopPathfindingEvent {
826                entity,
827                force: true,
828            });
829        }
830    }
831}
832
833pub fn call_successors_fn(
834    cached_world: &CachedWorld,
835    mining_cache: &MiningCache,
836    custom_state: &CustomPathfinderStateRef,
837    successors_fn: SuccessorsFn,
838    pos: RelBlockPos,
839) -> Vec<astar::Edge<RelBlockPos, moves::MoveData>> {
840    let mut edges = Vec::with_capacity(16);
841    let mut ctx = MovesCtx {
842        edges: &mut edges,
843        world: cached_world,
844        mining_cache,
845        custom_state,
846    };
847    successors_fn(&mut ctx, pos);
848    edges
849}