Skip to main content

azalea_client/plugins/
mining.rs

1use azalea_block::{BlockState, fluid_state::FluidState};
2use azalea_core::{direction::Direction, game_type::GameMode, position::BlockPos, tick::GameTick};
3use azalea_entity::{
4    ActiveEffects, Attributes, FluidOnEyes, Physics, PlayerAbilities, Position,
5    inventory::Inventory, mining::get_mine_progress,
6};
7use azalea_physics::{PhysicsSystems, collision::BlockWithShape};
8use azalea_protocol::packets::game::s_player_action::{self, ServerboundPlayerAction};
9use azalea_registry::{
10    builtin::{BlockKind, ItemKind},
11    item::ItemStack,
12};
13use azalea_world::{WorldName, Worlds};
14use bevy_app::{App, Plugin, Update};
15use bevy_ecs::prelude::*;
16use derive_more::{Deref, DerefMut};
17use tracing::{debug, trace, warn};
18
19use crate::{
20    client_inventory::InventorySystems,
21    interact::{
22        BlockStatePredictionHandler, SwingArmEvent, can_use_game_master_blocks,
23        check_is_interaction_restricted, pick::HitResultComponent,
24    },
25    local_player::{PermissionLevel, WorldHolder},
26    movement::MoveEventsSystems,
27    packet::game::SendGamePacketEvent,
28};
29
30/// A plugin that allows clients to break blocks in the world.
31pub struct MiningPlugin;
32impl Plugin for MiningPlugin {
33    fn build(&self, app: &mut App) {
34        app.add_message::<StartMiningBlockEvent>()
35            .add_message::<StopMiningBlockEvent>()
36            .add_message::<MineBlockProgressEvent>()
37            .add_message::<AttackBlockEvent>()
38            .add_systems(
39                GameTick,
40                (
41                    update_mining_component,
42                    handle_auto_mine,
43                    handle_mining_queued,
44                    decrement_mine_delay,
45                    continue_mining_block,
46                )
47                    .chain()
48                    .before(PhysicsSystems)
49                    .before(super::movement::send_position)
50                    .before(super::interact::handle_start_use_item_queued)
51                    .after(azalea_entity::update_fluid_on_eyes)
52                    .in_set(MiningSystems),
53            )
54            .add_systems(
55                Update,
56                (
57                    handle_start_mining_block_event,
58                    handle_stop_mining_block_event,
59                )
60                    .chain()
61                    .in_set(MiningSystems)
62                    .after(InventorySystems)
63                    .after(MoveEventsSystems)
64                    .after(crate::interact::pick::update_hit_result_component)
65                    .after(crate::attack::handle_attack_event),
66            )
67            .add_observer(handle_finish_mining_block_observer);
68    }
69}
70
71/// The Bevy system set for things related to mining.
72#[derive(Clone, Debug, Eq, Hash, PartialEq, SystemSet)]
73pub struct MiningSystems;
74
75/// A component that simulates the client holding down left click to mine the
76/// block that it's facing, but this only interacts with blocks and not
77/// entities.
78#[derive(Component)]
79pub struct LeftClickMine;
80
81#[allow(clippy::type_complexity)]
82fn handle_auto_mine(
83    mut query: Query<
84        (
85            &HitResultComponent,
86            Entity,
87            Option<&Mining>,
88            &Inventory,
89            &MineBlockPos,
90            &MineItem,
91        ),
92        With<LeftClickMine>,
93    >,
94    mut start_mining_block_event: MessageWriter<StartMiningBlockEvent>,
95    mut stop_mining_block_event: MessageWriter<StopMiningBlockEvent>,
96) {
97    for (
98        hit_result_component,
99        entity,
100        mining,
101        inventory,
102        current_mining_pos,
103        current_mining_item,
104    ) in &mut query.iter_mut()
105    {
106        let block_pos = hit_result_component
107            .as_block_hit_result_if_not_miss()
108            .map(|b| b.block_pos);
109
110        // start mining if we're looking at a block and we're not already mining
111        // it
112        if let Some(block_pos) = block_pos
113            && (mining.is_none()
114                || !is_same_mining_target(
115                    block_pos,
116                    inventory,
117                    current_mining_pos,
118                    current_mining_item,
119                ))
120        {
121            start_mining_block_event.write(StartMiningBlockEvent {
122                entity,
123                position: block_pos,
124                force: true,
125            });
126        } else if mining.is_some() && hit_result_component.miss() {
127            stop_mining_block_event.write(StopMiningBlockEvent { entity });
128        }
129    }
130}
131
132/// Information about the block we're currently mining.
133///
134/// This is only present if we're currently mining a block.
135#[derive(Clone, Component, Debug)]
136#[component(storage = "SparseSet")]
137pub struct Mining {
138    pub pos: BlockPos,
139    pub dir: Direction,
140    /// See [`MiningQueued::force`].
141    pub force: bool,
142}
143
144/// Start mining the block at the given position.
145///
146/// If we're looking at the block then the correct direction will be used,
147/// otherwise it'll be [`Direction::Down`].
148#[derive(Debug, Message)]
149pub struct StartMiningBlockEvent {
150    pub entity: Entity,
151    pub position: BlockPos,
152    /// Whether we should ignore blocks that are blocking the view of this
153    /// block.
154    ///
155    /// Most of the time, you'll want to set this to true as it'll make the
156    /// behavior more predictable. If it's set to false, then it might fail or
157    /// it might mine blocks other than the one at `position` (which may be
158    /// preferable if you're trying to act like vanilla).
159    pub force: bool,
160}
161fn handle_start_mining_block_event(
162    mut commands: Commands,
163    mut events: MessageReader<StartMiningBlockEvent>,
164    mut query: Query<&HitResultComponent>,
165) {
166    for event in events.read() {
167        trace!("{event:?}");
168        let hit_result = query.get_mut(event.entity).unwrap();
169        if event.force {
170            let direction = if let Some(block_hit_result) =
171                hit_result.as_block_hit_result_if_not_miss()
172                && block_hit_result.block_pos == event.position
173            {
174                // we're looking at the block
175                block_hit_result.direction
176            } else {
177                debug!(
178                    "Got StartMiningBlockEvent but we're not looking at the block ({hit_result:?}.block_pos != {:?}). Picking an arbitrary direction instead.",
179                    event.position
180                );
181                // we're not looking at the block, arbitrary direction
182                Direction::Down
183            };
184            commands.entity(event.entity).insert(MiningQueued {
185                position: event.position,
186                direction,
187                force: true,
188            });
189        } else {
190            // ```
191            // let block_hit_result = hit_result.as_block_hit_result_if_not_miss();
192            // let direction = block_hit_result.map_or(Direction::Down, |b| b.direction);
193            // ```
194            if let Some(block_hit_result) = hit_result.as_block_hit_result_if_not_miss()
195                && block_hit_result.block_pos == event.position
196            {
197                commands.entity(event.entity).insert(MiningQueued {
198                    position: event.position,
199                    direction: block_hit_result.direction,
200                    force: false,
201                });
202            } else {
203                warn!(
204                    "Got StartMiningBlockEvent with force=false but we're not looking at the block ({hit_result:?}.block_pos != {:?}). You should've looked at the block before trying to mine with force=false.",
205                    event.position
206                );
207            };
208        }
209    }
210}
211
212/// Present on entities when they're going to start mining a block next tick.
213#[derive(Clone, Component, Debug)]
214pub struct MiningQueued {
215    pub position: BlockPos,
216    pub direction: Direction,
217    /// Whether we should mine the block regardless of whether it's reachable.
218    pub force: bool,
219}
220#[allow(clippy::too_many_arguments, clippy::type_complexity)]
221pub fn handle_mining_queued(
222    mut commands: Commands,
223    mut attack_block_events: MessageWriter<AttackBlockEvent>,
224    mut mine_block_progress_events: MessageWriter<MineBlockProgressEvent>,
225    query: Query<(
226        Entity,
227        &MiningQueued,
228        &WorldHolder,
229        &GameMode,
230        &Inventory,
231        &ActiveEffects,
232        &FluidOnEyes,
233        &Physics,
234        &Attributes,
235        Option<&mut Mining>,
236        &mut BlockStatePredictionHandler,
237        (
238            &mut MineDelay,
239            &mut MineProgress,
240            &mut MineTicks,
241            &mut MineItem,
242            &mut MineBlockPos,
243        ),
244    )>,
245) {
246    for (
247        entity,
248        mining_queued,
249        world_holder,
250        &game_mode,
251        inventory,
252        active_effects,
253        fluid_on_eyes,
254        physics,
255        attributes,
256        mut mining,
257        mut sequence_number,
258        (
259            mut mine_delay,
260            mut mine_progress,
261            mut mine_ticks,
262            mut current_mining_item,
263            mut current_mining_pos,
264        ),
265    ) in query
266    {
267        trace!("handle_mining_queued {mining_queued:?}");
268        commands.entity(entity).remove::<MiningQueued>();
269
270        let world = world_holder.shared.read();
271        if check_is_interaction_restricted(&world, mining_queued.position, &game_mode, inventory) {
272            continue;
273        }
274        // TODO (when world border is implemented): vanilla ignores if the block
275        // is outside of the worldborder
276
277        if let Some(mining) = &mut mining {
278            // this matters if we were previously mining a block without force
279            if mining_queued.force {
280                mining.force = true;
281            }
282        }
283
284        if game_mode == GameMode::Creative {
285            // In creative mode, first send START_DESTROY_BLOCK packet then
286            // immediately finish mining
287            commands.trigger(SendGamePacketEvent::new(
288                entity,
289                ServerboundPlayerAction {
290                    action: s_player_action::Action::StartDestroyBlock,
291                    pos: mining_queued.position,
292                    direction: mining_queued.direction,
293                    seq: sequence_number.start_predicting(),
294                },
295            ));
296            commands.trigger(FinishMiningBlockEvent {
297                entity,
298                position: mining_queued.position,
299            });
300            **mine_delay = 5;
301            commands.trigger(SwingArmEvent { entity });
302        } else if mining.is_none()
303            || !is_same_mining_target(
304                mining_queued.position,
305                inventory,
306                &current_mining_pos,
307                &current_mining_item,
308            )
309        {
310            if mining.is_some() {
311                // send a packet to stop mining since we just changed target
312                commands.trigger(SendGamePacketEvent::new(
313                    entity,
314                    ServerboundPlayerAction {
315                        action: s_player_action::Action::AbortDestroyBlock,
316                        pos: current_mining_pos
317                            .expect("IsMining is true so MineBlockPos must be present"),
318                        direction: mining_queued.direction,
319                        seq: 0,
320                    },
321                ));
322            }
323
324            let target_block_state = world
325                .get_block_state(mining_queued.position)
326                .unwrap_or_default();
327
328            // we can't break blocks if they don't have a bounding box
329            let block_is_solid = !target_block_state
330                .outline_shape(mining_queued.position)
331                .is_empty();
332
333            if block_is_solid && **mine_progress == 0. {
334                // interact with the block (like note block left click) here
335                attack_block_events.write(AttackBlockEvent {
336                    entity,
337                    position: mining_queued.position,
338                });
339            }
340
341            let held_item = inventory.held_item();
342
343            if block_is_solid
344                && get_mine_progress(
345                    &*target_block_state,
346                    held_item,
347                    fluid_on_eyes,
348                    physics,
349                    attributes,
350                    active_effects,
351                ) >= 1.
352            {
353                // block was broken instantly (instamined)
354                commands.trigger(FinishMiningBlockEvent {
355                    entity,
356                    position: mining_queued.position,
357                });
358            } else {
359                let mining = Mining {
360                    pos: mining_queued.position,
361                    dir: mining_queued.direction,
362                    force: mining_queued.force,
363                };
364                trace!("inserting mining component {mining:?} for entity {entity:?}");
365                commands.entity(entity).insert(mining);
366                **current_mining_pos = Some(mining_queued.position);
367                **current_mining_item = held_item.clone();
368                **mine_progress = 0.;
369                **mine_ticks = 0.;
370                mine_block_progress_events.write(MineBlockProgressEvent {
371                    entity,
372                    position: mining_queued.position,
373                    destroy_stage: mine_progress.destroy_stage(),
374                });
375            }
376
377            commands.trigger(SendGamePacketEvent::new(
378                entity,
379                ServerboundPlayerAction {
380                    action: s_player_action::Action::StartDestroyBlock,
381                    pos: mining_queued.position,
382                    direction: mining_queued.direction,
383                    seq: sequence_number.start_predicting(),
384                },
385            ));
386            commands.trigger(SwingArmEvent { entity });
387            // another swing packet gets sent in the same tick in
388            // continue_mining_block, vanilla does this too
389        }
390    }
391}
392
393#[derive(Message)]
394pub struct MineBlockProgressEvent {
395    pub entity: Entity,
396    pub position: BlockPos,
397    pub destroy_stage: Option<u32>,
398}
399
400/// A player left clicked on a block, used for stuff like interacting with note
401/// blocks.
402#[derive(Message)]
403pub struct AttackBlockEvent {
404    pub entity: Entity,
405    pub position: BlockPos,
406}
407
408/// Returns whether the block and item are still the same as when we started
409/// mining.
410fn is_same_mining_target(
411    target_block: BlockPos,
412    inventory: &Inventory,
413    current_mining_pos: &MineBlockPos,
414    current_mining_item: &MineItem,
415) -> bool {
416    let held_item = inventory.held_item();
417    Some(target_block) == current_mining_pos.0 && held_item == &current_mining_item.0
418}
419
420/// A component bundle for players that can mine blocks.
421#[derive(Bundle, Clone, Default)]
422pub struct MineBundle {
423    pub delay: MineDelay,
424    pub progress: MineProgress,
425    pub ticks: MineTicks,
426    pub mining_pos: MineBlockPos,
427    pub mine_item: MineItem,
428}
429
430/// A component that counts down until we start mining the next block.
431#[derive(Clone, Component, Debug, Default, Deref, DerefMut)]
432pub struct MineDelay(pub u32);
433
434/// A component that stores the progress of the current mining operation.
435///
436/// This is a value between 0 and 1.
437#[derive(Clone, Component, Debug, Default, Deref, DerefMut)]
438pub struct MineProgress(pub f32);
439
440impl MineProgress {
441    pub fn destroy_stage(&self) -> Option<u32> {
442        if self.0 > 0. {
443            Some((self.0 * 10.) as u32)
444        } else {
445            None
446        }
447    }
448}
449
450/// A component that stores the number of ticks that we've been mining the same
451/// block for.
452///
453/// This is a float despite the fact that it should only ever be a round number.
454#[derive(Clone, Component, Debug, Default, Deref, DerefMut)]
455pub struct MineTicks(pub f32);
456
457/// A component that stores the position of the block we're currently mining.
458#[derive(Clone, Component, Debug, Default, Deref, DerefMut)]
459pub struct MineBlockPos(pub Option<BlockPos>);
460
461/// A component that contains the item we're currently using to mine, or
462/// [`ItemStack::Empty`] if nothing is being mined.
463#[derive(Clone, Component, Debug, Default, Deref, DerefMut)]
464pub struct MineItem(pub ItemStack);
465
466/// A trigger that's sent when we completed mining a block.
467#[derive(EntityEvent)]
468pub struct FinishMiningBlockEvent {
469    pub entity: Entity,
470    pub position: BlockPos,
471}
472
473pub fn handle_finish_mining_block_observer(
474    finish_mining_block: On<FinishMiningBlockEvent>,
475    mut query: Query<(
476        &WorldName,
477        &GameMode,
478        &Inventory,
479        &PlayerAbilities,
480        &PermissionLevel,
481        &Position,
482        &mut BlockStatePredictionHandler,
483    )>,
484    worlds: Res<Worlds>,
485) {
486    let event = finish_mining_block.event();
487
488    let (
489        world_name,
490        &game_mode,
491        inventory,
492        abilities,
493        permission_level,
494        player_pos,
495        mut prediction_handler,
496    ) = query.get_mut(finish_mining_block.entity).unwrap();
497    let world_lock = worlds.get(world_name).unwrap();
498    let world = world_lock.read();
499    if check_is_interaction_restricted(&world, event.position, &game_mode, inventory) {
500        return;
501    }
502
503    if game_mode == GameMode::Creative {
504        let held_item = inventory.held_item().kind();
505        if matches!(held_item, ItemKind::Trident | ItemKind::DebugStick)
506            || azalea_registry::tags::items::SWORDS.contains(&held_item)
507        {
508            return;
509        }
510    }
511
512    let Some(block_state) = world.get_block_state(event.position) else {
513        return;
514    };
515
516    let registry_block = block_state.as_block_kind();
517    if !can_use_game_master_blocks(abilities, permission_level)
518        && matches!(
519            registry_block,
520            BlockKind::CommandBlock | BlockKind::StructureBlock
521        )
522    {
523        return;
524    }
525    if block_state == BlockState::AIR {
526        return;
527    }
528
529    // when we break a waterlogged block we want to keep the water there
530    let fluid_state = FluidState::from(block_state);
531    let block_state_for_fluid = BlockState::from(fluid_state);
532    let old_state = world
533        .set_block_state(event.position, block_state_for_fluid)
534        .unwrap_or_default();
535    prediction_handler.retain_known_server_state(event.position, old_state, **player_pos);
536}
537
538/// Abort mining a block.
539#[derive(Message)]
540pub struct StopMiningBlockEvent {
541    pub entity: Entity,
542}
543pub fn handle_stop_mining_block_event(
544    mut events: MessageReader<StopMiningBlockEvent>,
545    mut commands: Commands,
546    mut mine_block_progress_events: MessageWriter<MineBlockProgressEvent>,
547    mut query: Query<(&MineBlockPos, &mut MineProgress)>,
548) {
549    for event in events.read() {
550        let (mine_block_pos, mut mine_progress) = query.get_mut(event.entity).unwrap();
551
552        let mine_block_pos =
553            mine_block_pos.expect("IsMining is true so MineBlockPos must be present");
554        commands.trigger(SendGamePacketEvent::new(
555            event.entity,
556            ServerboundPlayerAction {
557                action: s_player_action::Action::AbortDestroyBlock,
558                pos: mine_block_pos,
559                direction: Direction::Down,
560                seq: 0,
561            },
562        ));
563        commands.entity(event.entity).remove::<Mining>();
564        **mine_progress = 0.;
565        mine_block_progress_events.write(MineBlockProgressEvent {
566            entity: event.entity,
567            position: mine_block_pos,
568            destroy_stage: None,
569        });
570    }
571}
572
573pub fn decrement_mine_delay(mut query: Query<&mut MineDelay>) {
574    for mut mine_delay in &mut query {
575        if **mine_delay > 0 {
576            **mine_delay -= 1;
577        }
578    }
579}
580
581#[allow(clippy::too_many_arguments, clippy::type_complexity)]
582pub fn continue_mining_block(
583    mut query: Query<(
584        Entity,
585        &WorldName,
586        &GameMode,
587        &Inventory,
588        &MineBlockPos,
589        &MineItem,
590        &ActiveEffects,
591        &FluidOnEyes,
592        &Physics,
593        &Attributes,
594        &Mining,
595        &mut MineDelay,
596        &mut MineProgress,
597        &mut MineTicks,
598        &mut BlockStatePredictionHandler,
599    )>,
600    mut commands: Commands,
601    mut mine_block_progress_events: MessageWriter<MineBlockProgressEvent>,
602    worlds: Res<Worlds>,
603) {
604    for (
605        entity,
606        world_name,
607        &game_mode,
608        inventory,
609        current_mining_pos,
610        current_mining_item,
611        active_effects,
612        fluid_on_eyes,
613        physics,
614        attributes,
615        mining,
616        mut mine_delay,
617        mut mine_progress,
618        mut mine_ticks,
619        mut prediction_handler,
620    ) in query.iter_mut()
621    {
622        if game_mode == GameMode::Creative {
623            // TODO: worldborder check
624            **mine_delay = 5;
625            commands.trigger(SendGamePacketEvent::new(
626                entity,
627                ServerboundPlayerAction {
628                    action: s_player_action::Action::StartDestroyBlock,
629                    pos: mining.pos,
630                    direction: mining.dir,
631                    seq: prediction_handler.start_predicting(),
632                },
633            ));
634            commands.trigger(FinishMiningBlockEvent {
635                entity,
636                position: mining.pos,
637            });
638            commands.trigger(SwingArmEvent { entity });
639        } else if mining.force
640            || is_same_mining_target(
641                mining.pos,
642                inventory,
643                current_mining_pos,
644                current_mining_item,
645            )
646        {
647            trace!("continue mining block at {:?}", mining.pos);
648            let world_lock = worlds.get(world_name).unwrap();
649            let world = world_lock.read();
650            let target_block_state = world.get_block_state(mining.pos).unwrap_or_default();
651
652            trace!("target_block_state: {target_block_state:?}");
653
654            if target_block_state.is_air() {
655                commands.entity(entity).remove::<Mining>();
656                continue;
657            }
658            let block = target_block_state.to_trait();
659            **mine_progress += get_mine_progress(
660                block,
661                current_mining_item,
662                fluid_on_eyes,
663                physics,
664                attributes,
665                active_effects,
666            );
667
668            if **mine_ticks % 4. == 0. {
669                // vanilla makes a mining sound here
670            }
671            **mine_ticks += 1.;
672
673            if **mine_progress >= 1. {
674                // MiningQueued is removed in case we were doing an infinite
675                // loop that repeatedly inserts MiningQueued
676                commands.entity(entity).remove::<(Mining, MiningQueued)>();
677                trace!("finished mining block at {:?}", mining.pos);
678                commands.trigger(FinishMiningBlockEvent {
679                    entity,
680                    position: mining.pos,
681                });
682                commands.trigger(SendGamePacketEvent::new(
683                    entity,
684                    ServerboundPlayerAction {
685                        action: s_player_action::Action::StopDestroyBlock,
686                        pos: mining.pos,
687                        direction: mining.dir,
688                        seq: prediction_handler.start_predicting(),
689                    },
690                ));
691                **mine_progress = 0.;
692                **mine_ticks = 0.;
693                **mine_delay = 5;
694            }
695
696            mine_block_progress_events.write(MineBlockProgressEvent {
697                entity,
698                position: mining.pos,
699                destroy_stage: mine_progress.destroy_stage(),
700            });
701            commands.trigger(SwingArmEvent { entity });
702        } else {
703            trace!("switching mining target to {:?}", mining.pos);
704            commands.entity(entity).insert(MiningQueued {
705                position: mining.pos,
706                direction: mining.dir,
707                force: false,
708            });
709        }
710    }
711}
712
713pub fn update_mining_component(
714    mut commands: Commands,
715    mut query: Query<(Entity, &mut Mining, &HitResultComponent)>,
716) {
717    for (entity, mut mining, hit_result_component) in &mut query.iter_mut() {
718        if let Some(block_hit_result) = hit_result_component.as_block_hit_result_if_not_miss() {
719            if mining.force && block_hit_result.block_pos != mining.pos {
720                continue;
721            }
722
723            if mining.pos != block_hit_result.block_pos {
724                debug!(
725                    "Updating Mining::pos from {:?} to {:?}",
726                    mining.pos, block_hit_result.block_pos
727                );
728                mining.pos = block_hit_result.block_pos;
729            }
730            mining.dir = block_hit_result.direction;
731        } else {
732            if mining.force {
733                continue;
734            }
735
736            debug!("Removing mining component because we're no longer looking at the block");
737            commands.entity(entity).remove::<Mining>();
738        }
739    }
740}