1pub 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#[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#[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 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 fn goto(&self, goal: impl Goal + 'static) -> impl Future<Output = ()>;
177 fn goto_with_opts(
192 &self,
193 goal: impl Goal + 'static,
194 opts: PathfinderOpts,
195 ) -> impl Future<Output = ()>;
196 fn start_goto(&self, goal: impl Goal + 'static);
206 fn start_goto_with_opts(&self, goal: impl Goal + 'static, opts: PathfinderOpts);
212 fn stop_pathfinding(&self);
220 fn force_stop_pathfinding(&self);
223 fn wait_until_goto_target_reached(&self) -> impl Future<Output = ()>;
225 fn is_goto_target_reached(&self) -> bool;
228 fn is_executing_path(&self) -> bool;
233 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 self.wait_updates(1).await;
273
274 let mut tick_broadcaster = self.get_tick_broadcaster();
275 while !self.is_goto_target_reached() {
276 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 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 pathfinder.goal = None;
349 pathfinder.opts = None;
350 pathfinder.is_calculating = false;
351 debug!("already at goal, not pathfinding");
352 continue;
353 }
354
355 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 let mut start = cur_pos;
382
383 if let Some(mut executing_path) = executing_path {
384 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 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 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 let executing_path_limit = 50;
451
452 executing_path.path.truncate(executing_path_limit);
455
456 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#[inline]
502pub fn player_pos_to_block_pos(position: Vec3) -> BlockPos {
503 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
519pub 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 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 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
627pub 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 commands.entity(entity).remove::<ComputePath>();
641 }
642 }
643}
644
645#[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 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 executing_path.queued_path = Some(VecDeque::new());
764 } else {
765 }
767 }
768 pathfinder.is_calculating = false;
769 }
770}
771
772#[derive(Message)]
773pub struct StopPathfindingEvent {
774 pub entity: Entity,
775 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 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 executing_path.queued_path = Some(VecDeque::new());
803 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}