Skip to main content

azalea/pathfinder/execute/
simulation.rs

1//! An alternative execution engine for the pathfinder that attempts to skip
2//! nodes in the path by running simulations.
3//!
4//! See [`SimulationPathfinderExecutionPlugin`] for more information.
5
6use std::{borrow::Cow, time::Instant};
7
8use azalea_client::{
9    ClientMovementState, SprintDirection, StartSprintEvent, StartWalkEvent,
10    local_player::WorldHolder,
11    mining::{Mining, MiningSystems, StartMiningBlockEvent},
12};
13use azalea_core::{position::BlockPos, tick::GameTick};
14use azalea_entity::{Attributes, LookDirection, Physics, Position, inventory::Inventory};
15use azalea_physics::PhysicsSystems;
16use bevy_app::{App, Plugin};
17use bevy_ecs::{prelude::*, system::SystemState};
18use tracing::{debug, trace};
19
20use crate::{
21    WalkDirection,
22    bot::{JumpEvent, LookAtEvent, direction_looking_at},
23    ecs::{
24        entity::Entity,
25        system::{Commands, Query},
26    },
27    pathfinder::{
28        ExecutingPath, PathfinderSystems,
29        debug::debug_render_path_with_particles,
30        moves::{ExecuteCtx, IsReachedCtx},
31        simulation::{SimulatedPlayerBundle, Simulation},
32    },
33};
34
35/// An alternative execution engine for the pathfinder that attempts to skip
36/// nodes in the path by running simulations.
37///
38/// This allows it to smooth the path and sprint-jump without failing jumps or
39/// looking unnatural. However, this comes at the cost of execution being more
40/// expensive and potentially less stable.
41///
42/// To use it, simply add [`SimulationPathfinderExecutionPlugin`] as a plugin.
43///
44/// ```
45/// use azalea::{
46///     pathfinder::execute::simulation::SimulationPathfinderExecutionPlugin, swarm::prelude::*,
47/// };
48///
49/// let builder = SwarmBuilder::new().add_plugins(SimulationPathfinderExecutionPlugin);
50/// // ...
51/// ```
52///
53/// [`DefaultPathfinderExecutionPlugin`]: super::DefaultPathfinderExecutionPlugin
54pub struct SimulationPathfinderExecutionPlugin;
55impl Plugin for SimulationPathfinderExecutionPlugin {
56    fn build(&self, app: &mut App) {
57        app.add_systems(
58            GameTick,
59            (
60                super::timeout_movement,
61                super::patching::check_for_path_obstruction,
62                super::check_node_reached,
63                tick_execute_path,
64                super::recalculate_near_end_of_path,
65                super::recalculate_if_has_goal_but_no_path,
66            )
67                .chain()
68                .after(PhysicsSystems)
69                .after(azalea_client::movement::send_position)
70                .after(MiningSystems)
71                .after(debug_render_path_with_particles)
72                .in_set(PathfinderSystems),
73        );
74    }
75}
76
77#[derive(Clone, Component, Debug)]
78pub enum SimulatingPathState {
79    Fail,
80    Simulated(SimulatingPathOpts),
81}
82#[derive(Clone, Debug)]
83pub struct SimulatingPathOpts {
84    pub start: BlockPos,
85    pub target: BlockPos,
86    pub jumping: bool,
87    pub jump_until_target_distance: f64,
88    pub jump_after_start_distance: f64,
89    pub sprinting: bool,
90    pub y_rot: f32,
91}
92impl SimulatingPathState {
93    pub fn as_simulated(&self) -> Option<&SimulatingPathOpts> {
94        match self {
95            Self::Fail => None,
96            Self::Simulated(s) => Some(s),
97        }
98    }
99}
100
101#[allow(clippy::type_complexity)]
102pub fn tick_execute_path(
103    mut commands: Commands,
104    mut query: Query<(
105        Entity,
106        &mut ExecutingPath,
107        &mut LookDirection,
108        &Position,
109        &Physics,
110        &ClientMovementState,
111        Option<&Mining>,
112        &WorldHolder,
113        &Attributes,
114        &Inventory,
115        Option<&SimulatingPathState>,
116    )>,
117    mut look_at_events: MessageWriter<LookAtEvent>,
118    mut sprint_events: MessageWriter<StartSprintEvent>,
119    mut walk_events: MessageWriter<StartWalkEvent>,
120    mut jump_events: MessageWriter<JumpEvent>,
121    mut start_mining_events: MessageWriter<StartMiningBlockEvent>,
122) {
123    for (
124        entity,
125        mut executing_path,
126        mut look_direction,
127        position,
128        physics,
129        physics_state,
130        mining,
131        world_holder,
132        attributes,
133        inventory,
134        mut simulating_path_state,
135    ) in &mut query
136    {
137        executing_path.ticks_since_last_node_reached += 1;
138
139        if executing_path.ticks_since_last_node_reached == 1 {
140            if let Some(SimulatingPathState::Simulated(s)) = simulating_path_state {
141                // only reset the state if we just reached the end of the
142                // simulation path (for performance)
143                if s.target == executing_path.last_reached_node
144                    // or if the current simulation target isn't in the path, reset too
145                    || !executing_path
146                        .path
147                        .iter()
148                        .any(|e| e.movement.target == s.target)
149                {
150                    simulating_path_state = None;
151                }
152            } else {
153                simulating_path_state = None;
154            }
155        }
156
157        let simulating_path_state: Cow<'_, SimulatingPathState> =
158            if let Some(simulating_path_state) = &simulating_path_state {
159                Cow::Borrowed(simulating_path_state)
160            } else {
161                let start = Instant::now();
162
163                let new_state = run_simulations(
164                    &executing_path,
165                    world_holder,
166                    SimulatedPlayerBundle {
167                        position: *position,
168                        physics: physics.clone(),
169                        physics_state: physics_state.clone(),
170                        look_direction: *look_direction,
171                        attributes: attributes.clone(),
172                        inventory: inventory.clone(),
173                    },
174                );
175                debug!("found sim in {:?}: {new_state:?}", start.elapsed());
176                commands.entity(entity).insert(new_state.clone());
177                Cow::Owned(new_state)
178            };
179
180        match &*simulating_path_state {
181            SimulatingPathState::Fail => {
182                if let Some(edge) = executing_path.path.front() {
183                    let mut ctx = ExecuteCtx {
184                        entity,
185                        target: edge.movement.target,
186                        position: **position,
187                        start: executing_path.last_reached_node,
188                        physics,
189                        is_currently_mining: mining.is_some(),
190                        can_mine: true,
191                        world: world_holder.shared.clone(),
192                        menu: inventory.inventory_menu.clone(),
193
194                        commands: &mut commands,
195                        look_at_events: &mut look_at_events,
196                        sprint_events: &mut sprint_events,
197                        walk_events: &mut walk_events,
198                        jump_events: &mut jump_events,
199                        start_mining_events: &mut start_mining_events,
200                    };
201                    ctx.on_tick_start();
202                    trace!(
203                        "executing move, position: {}, last_reached_node: {}",
204                        **position, executing_path.last_reached_node
205                    );
206                    (edge.movement.data.execute)(ctx);
207                }
208            }
209            SimulatingPathState::Simulated(SimulatingPathOpts {
210                start,
211                target,
212                jumping,
213                jump_until_target_distance,
214                jump_after_start_distance,
215                sprinting,
216                y_rot,
217            }) => {
218                look_direction.update(LookDirection::new(*y_rot, 0.));
219
220                if *sprinting {
221                    sprint_events.write(StartSprintEvent {
222                        entity,
223                        direction: SprintDirection::Forward,
224                    });
225                } else if physics_state.was_sprinting {
226                    // have to let go for a tick to be able to start walking
227                    walk_events.write(StartWalkEvent {
228                        entity,
229                        direction: WalkDirection::None,
230                    });
231                } else {
232                    walk_events.write(StartWalkEvent {
233                        entity,
234                        direction: WalkDirection::Forward,
235                    });
236                }
237                if *jumping
238                    && target.center().horizontal_distance_squared_to(**position)
239                        > jump_until_target_distance.powi(2)
240                    && start.center().horizontal_distance_squared_to(**position)
241                        > jump_after_start_distance.powi(2)
242                {
243                    jump_events.write(JumpEvent { entity });
244                }
245            }
246        }
247
248        //
249    }
250}
251
252fn run_simulations(
253    executing_path: &ExecutingPath,
254    world_holder: &WorldHolder,
255    player: SimulatedPlayerBundle,
256) -> SimulatingPathState {
257    let swimming = player.physics.is_in_water();
258
259    let mut sim = Simulation::new(world_holder.shared.read().chunks.clone(), player.clone());
260
261    // note that we can't skip more than 50 nodes without causing issues with
262    // the executing_path_limit in goto_listener
263    for nodes_ahead in [20, 15, 10, 5, 4, 3, 2, 1, 0] {
264        if nodes_ahead + 1 >= executing_path.path.len() {
265            // don't simulate to the last node since it has stricter checks
266            continue;
267        }
268
269        let mut results = Vec::new();
270
271        if let Some(simulating_to) = executing_path.path.get(nodes_ahead) {
272            let y_rot =
273                direction_looking_at(*player.position, simulating_to.movement.target.center())
274                    .y_rot();
275
276            for jump_until_target_distance in [0., 1., 3.] {
277                for jump_after_start_distance in [0., 0.5] {
278                    for jumping in [true, false] {
279                        if !jumping
280                            && (jump_until_target_distance != 0. || jump_after_start_distance != 0.)
281                        {
282                            continue;
283                        }
284
285                        // this loop is left here in case you wanna try
286                        // re-enabling walking, but it doesn't seem that useful
287                        for sprinting in [true] {
288                            if !sprinting && nodes_ahead > 2 {
289                                continue;
290                            }
291                            if swimming {
292                                if !sprinting
293                                    || jump_until_target_distance > 0.
294                                    || jump_after_start_distance > 0.
295                                {
296                                    continue;
297                                }
298                            } else if jump_until_target_distance == 0. {
299                                continue;
300                            }
301
302                            let state = SimulatingPathOpts {
303                                start: BlockPos::from(player.position),
304                                target: simulating_to.movement.target,
305                                jumping,
306                                jump_until_target_distance,
307                                jump_after_start_distance,
308                                sprinting,
309                                y_rot,
310                            };
311                            let sim_res = run_one_simulation(
312                                &mut sim,
313                                player.clone(),
314                                state.clone(),
315                                executing_path,
316                                nodes_ahead,
317                                if swimming {
318                                    (nodes_ahead * 12) + 20
319                                } else {
320                                    (nodes_ahead * 4) + 20
321                                },
322                            );
323                            if sim_res.success {
324                                results.push((state, sim_res.ticks));
325                            }
326                        }
327                    }
328                }
329            }
330        }
331
332        if !results.is_empty() {
333            let fastest = results.iter().min_by_key(|r| r.1).unwrap().0.clone();
334            return SimulatingPathState::Simulated(fastest);
335        }
336    }
337
338    SimulatingPathState::Fail
339}
340
341struct SimulationResult {
342    success: bool,
343    ticks: usize,
344}
345fn run_one_simulation(
346    sim: &mut Simulation,
347    player: SimulatedPlayerBundle,
348    state: SimulatingPathOpts,
349    executing_path: &ExecutingPath,
350    nodes_ahead: usize,
351    timeout_ticks: usize,
352) -> SimulationResult {
353    let simulating_to = &executing_path.path[nodes_ahead];
354
355    let start = BlockPos::from(player.position);
356    sim.reset(player);
357
358    // run an Update to initialize some things, including at least the Bot
359    // component (which is needed for jumping)
360    sim.run_update_schedule();
361
362    let simulating_to_block = simulating_to.movement.target;
363
364    let mut success = false;
365    let mut total_ticks = 0;
366
367    for ticks in 1..=timeout_ticks {
368        let position = sim.position();
369        let physics = sim.physics();
370
371        if physics.horizontal_collision
372            || physics.is_in_lava()
373            || (physics.velocity.y < -0.7 && !physics.is_in_water())
374        {
375            // fail
376            break;
377        }
378
379        if (simulating_to.movement.data.is_reached)(IsReachedCtx {
380            target: simulating_to_block,
381            start,
382            position,
383            physics: &physics,
384        }) {
385            success = true;
386            total_ticks = ticks;
387            break;
388        }
389
390        let ecs = sim.app.world_mut();
391
392        ecs.get_mut::<LookDirection>(sim.entity)
393            .unwrap()
394            .update(LookDirection::new(state.y_rot, 0.));
395
396        if state.sprinting {
397            ecs.write_message(StartSprintEvent {
398                entity: sim.entity,
399                direction: SprintDirection::Forward,
400            });
401        } else if ecs
402            .get::<ClientMovementState>(sim.entity)
403            .map(|p| p.was_sprinting)
404            .unwrap_or_default()
405        {
406            // have to let go for a tick to be able to start walking
407            ecs.write_message(StartWalkEvent {
408                entity: sim.entity,
409                direction: WalkDirection::None,
410            });
411        } else {
412            ecs.write_message(StartWalkEvent {
413                entity: sim.entity,
414                direction: WalkDirection::Forward,
415            });
416        }
417        if state.jumping
418            && simulating_to_block
419                .center()
420                .horizontal_distance_squared_to(position)
421                > state.jump_until_target_distance.powi(2)
422            && start.center().horizontal_distance_squared_to(position)
423                > state.jump_after_start_distance.powi(2)
424        {
425            ecs.write_message(JumpEvent { entity: sim.entity });
426        }
427
428        sim.tick();
429    }
430
431    if success {
432        // now verify that the path is safe by continuing to the next node
433
434        let mut followup_success = false;
435
436        let next_node = &executing_path.path[nodes_ahead + 1];
437        for _ in 1..=30 {
438            // add ticks here so if we sort by ticks later it'll be more
439            // accurate
440            total_ticks += 1;
441
442            {
443                let mut system_state = SystemState::<(
444                    Commands,
445                    Query<(&Position, &Physics, Option<&Mining>, &Inventory)>,
446                    MessageWriter<LookAtEvent>,
447                    MessageWriter<StartSprintEvent>,
448                    MessageWriter<StartWalkEvent>,
449                    MessageWriter<JumpEvent>,
450                    MessageWriter<StartMiningBlockEvent>,
451                )>::new(sim.app.world_mut());
452                let (
453                    mut commands,
454                    query,
455                    mut look_at_events,
456                    mut sprint_events,
457                    mut walk_events,
458                    mut jump_events,
459                    mut start_mining_events,
460                ) = system_state.get_mut(sim.app.world_mut()).unwrap();
461
462                let (position, physics, mining, inventory) = query.get(sim.entity).unwrap();
463
464                if physics.horizontal_collision {
465                    // if the simulated move made us hit a wall then it's bad
466                    break;
467                }
468                if physics.velocity.y < -0.7 && !physics.is_in_water() {
469                    break;
470                }
471
472                (next_node.movement.data.execute)(ExecuteCtx {
473                    entity: sim.entity,
474                    target: next_node.movement.target,
475                    start: simulating_to_block,
476                    position: **position,
477                    physics,
478                    is_currently_mining: mining.is_some(),
479                    // don't modify the world from the simulation
480                    can_mine: false,
481                    world: sim.world.clone(),
482                    menu: inventory.inventory_menu.clone(),
483
484                    commands: &mut commands,
485                    look_at_events: &mut look_at_events,
486                    sprint_events: &mut sprint_events,
487                    walk_events: &mut walk_events,
488                    jump_events: &mut jump_events,
489                    start_mining_events: &mut start_mining_events,
490                });
491                system_state.apply(sim.app.world_mut());
492            }
493
494            sim.tick();
495
496            if (next_node.movement.data.is_reached)(IsReachedCtx {
497                target: next_node.movement.target,
498                start: simulating_to_block,
499                position: sim.position(),
500                physics: &sim.physics(),
501            }) {
502                followup_success = true;
503                break;
504            }
505        }
506
507        if !followup_success {
508            debug!("followup failed");
509            success = false;
510        }
511    }
512
513    SimulationResult {
514        success,
515        ticks: total_ticks,
516    }
517}