azalea/pathfinder/
simulation.rs

1//! Simulate the Minecraft world, currently only used for tests.
2
3use std::sync::Arc;
4
5use azalea_client::{
6    PhysicsState, interact::BlockStatePredictionHandler, local_player::LocalGameMode,
7    mining::MineBundle,
8};
9use azalea_core::{
10    entity_id::MinecraftEntityId, game_type::GameMode, position::Vec3, tick::GameTick,
11};
12use azalea_entity::{
13    Attributes, LookDirection, Physics, Position, dimensions::EntityDimensions,
14    inventory::Inventory,
15};
16use azalea_registry::builtin::EntityKind;
17use azalea_world::{ChunkStorage, PartialWorld, World, WorldName, Worlds};
18use bevy_app::App;
19use bevy_ecs::prelude::*;
20use parking_lot::RwLock;
21use uuid::Uuid;
22
23#[derive(Bundle, Clone)]
24pub struct SimulatedPlayerBundle {
25    pub position: Position,
26    pub physics: Physics,
27    pub physics_state: PhysicsState,
28    pub look_direction: LookDirection,
29    pub attributes: Attributes,
30    pub inventory: Inventory,
31}
32
33impl SimulatedPlayerBundle {
34    pub fn new(position: Vec3) -> Self {
35        let dimensions = EntityDimensions::from(EntityKind::Player);
36
37        SimulatedPlayerBundle {
38            position: Position::new(position),
39            physics: Physics::new(&dimensions, position),
40            physics_state: PhysicsState::default(),
41            look_direction: LookDirection::default(),
42            attributes: Attributes::new(EntityKind::Player),
43            inventory: Inventory::default(),
44        }
45    }
46}
47
48fn simulation_world_name() -> WorldName {
49    WorldName::new("azalea:simulation")
50}
51
52fn create_simulation_world(chunks: ChunkStorage) -> (App, Arc<RwLock<World>>) {
53    let world_name = simulation_world_name();
54
55    let world = Arc::new(RwLock::new(World {
56        chunks,
57        ..Default::default()
58    }));
59
60    let mut app = App::new();
61    // we don't use all the default azalea plugins because we don't need all of them
62    app.add_plugins((
63        azalea_physics::PhysicsPlugin,
64        azalea_entity::EntityPlugin,
65        azalea_client::movement::MovementPlugin,
66        super::PathfinderPlugin,
67        crate::bot::BotPlugin,
68        azalea_client::task_pool::TaskPoolPlugin::default(),
69        // for mining
70        azalea_client::inventory::InventoryPlugin,
71        azalea_client::mining::MiningPlugin,
72        azalea_client::interact::InteractPlugin,
73        azalea_client::loading::PlayerLoadedPlugin,
74    ))
75    .insert_resource(Worlds {
76        map: [(world_name.clone(), Arc::downgrade(&world.clone()))]
77            .iter()
78            .cloned()
79            .collect(),
80    });
81
82    app.edit_schedule(bevy_app::Main, |schedule| {
83        schedule.set_executor_kind(bevy_ecs::schedule::ExecutorKind::SingleThreaded);
84    });
85
86    (app, world)
87}
88
89fn create_simulation_player_complete_bundle(
90    world: Arc<RwLock<World>>,
91    player: &SimulatedPlayerBundle,
92) -> impl Bundle {
93    let world_name = simulation_world_name();
94
95    (
96        MinecraftEntityId(0),
97        azalea_entity::LocalEntity,
98        azalea_entity::metadata::PlayerMetadataBundle::default(),
99        azalea_entity::EntityBundle::new(
100            Uuid::nil(),
101            *player.position,
102            EntityKind::Player,
103            world_name,
104        ),
105        azalea_client::local_player::WorldHolder {
106            // the partial world is never actually used by the pathfinder, so we can leave it empty
107            partial: Arc::new(RwLock::new(PartialWorld::default())),
108            shared: world.clone(),
109        },
110        Inventory::default(),
111        LocalGameMode::from(GameMode::Survival),
112        MineBundle::default(),
113        BlockStatePredictionHandler::default(),
114        azalea_client::local_player::PermissionLevel::default(),
115        azalea_entity::PlayerAbilities::default(),
116    )
117}
118
119fn create_simulation_player(
120    ecs: &mut bevy_ecs::world::World,
121    world: Arc<RwLock<World>>,
122    player: SimulatedPlayerBundle,
123) -> Entity {
124    let mut entity = ecs.spawn(create_simulation_player_complete_bundle(world, &player));
125    entity.insert(player);
126    entity.id()
127}
128
129/// Simulate the Minecraft world to see if certain movements would be possible.
130pub struct Simulation {
131    pub app: App,
132    pub entity: Entity,
133    _world: Arc<RwLock<World>>,
134}
135
136impl Simulation {
137    pub fn new(chunks: ChunkStorage, player: SimulatedPlayerBundle) -> Self {
138        let (mut app, world) = create_simulation_world(chunks);
139        let entity = create_simulation_player(app.world_mut(), world.clone(), player);
140        Self {
141            app,
142            entity,
143            _world: world,
144        }
145    }
146
147    pub fn tick(&mut self) {
148        self.app.update();
149        self.app.world_mut().run_schedule(GameTick);
150    }
151    pub fn component<T: Component + Clone>(&self) -> T {
152        self.app.world().get::<T>(self.entity).unwrap().clone()
153    }
154    pub fn get_component<T: Component + Clone>(&self) -> Option<T> {
155        self.app.world().get::<T>(self.entity).cloned()
156    }
157    pub fn position(&self) -> Vec3 {
158        *self.component::<Position>()
159    }
160    pub fn is_mining(&self) -> bool {
161        // return true if the component is present and Some
162        self.get_component::<azalea_client::mining::MineBlockPos>()
163            .and_then(|c| *c)
164            .is_some()
165    }
166}
167
168/// A set of simulations, useful for efficiently doing multiple simulations.
169pub struct SimulationSet {
170    pub app: App,
171    world: Arc<RwLock<World>>,
172}
173impl SimulationSet {
174    pub fn new(chunks: ChunkStorage) -> Self {
175        let (app, world) = create_simulation_world(chunks);
176        Self { app, world }
177    }
178    pub fn tick(&mut self) {
179        self.app.update();
180        self.app.world_mut().run_schedule(GameTick);
181    }
182
183    pub fn spawn(&mut self, player: SimulatedPlayerBundle) -> Entity {
184        create_simulation_player(self.app.world_mut(), self.world.clone(), player)
185    }
186    pub fn despawn(&mut self, entity: Entity) {
187        self.app.world_mut().despawn(entity);
188    }
189
190    pub fn position(&self, entity: Entity) -> Vec3 {
191        **self.app.world().get::<Position>(entity).unwrap()
192    }
193}