azalea_client/plugins/
attack.rs

1use azalea_core::{game_type::GameMode, tick::GameTick};
2use azalea_entity::{
3    Attributes, Physics,
4    indexing::EntityIdIndex,
5    metadata::{ShiftKeyDown, Sprinting},
6    update_bounding_box,
7};
8use azalea_physics::PhysicsSet;
9use azalea_protocol::packets::game::s_interact::{self, ServerboundInteract};
10use bevy_app::{App, Plugin, Update};
11use bevy_ecs::prelude::*;
12use derive_more::{Deref, DerefMut};
13use tracing::warn;
14
15use super::packet::game::SendPacketEvent;
16use crate::{
17    Client, interact::SwingArmEvent, local_player::LocalGameMode, movement::MoveEventsSet,
18    respawn::perform_respawn,
19};
20
21pub struct AttackPlugin;
22impl Plugin for AttackPlugin {
23    fn build(&self, app: &mut App) {
24        app.add_event::<AttackEvent>()
25            .add_systems(
26                Update,
27                handle_attack_event
28                    .before(update_bounding_box)
29                    .before(MoveEventsSet)
30                    .after(perform_respawn),
31            )
32            .add_systems(
33                GameTick,
34                (
35                    increment_ticks_since_last_attack,
36                    update_attack_strength_scale.after(PhysicsSet),
37                    handle_attack_queued
38                        .before(super::tick_end::game_tick_packet)
39                        .after(super::movement::send_sprinting_if_needed)
40                        .before(super::movement::send_position),
41                )
42                    .chain(),
43            );
44    }
45}
46
47impl Client {
48    /// Attack the entity with the given id.
49    pub fn attack(&self, entity: Entity) {
50        self.ecs.lock().send_event(AttackEvent {
51            entity: self.entity,
52            target: entity,
53        });
54    }
55
56    /// Whether the player has an attack cooldown.
57    ///
58    /// Also see [`Client::attack_cooldown_remaining_ticks`].
59    pub fn has_attack_cooldown(&self) -> bool {
60        let Some(attack_strength_scale) = self.get_component::<AttackStrengthScale>() else {
61            // they don't even have an AttackStrengthScale so they probably can't even
62            // attack? whatever, just return false
63            return false;
64        };
65        *attack_strength_scale < 1.0
66    }
67
68    /// Returns the number of ticks until we can attack at full strength again.
69    ///
70    /// Also see [`Client::has_attack_cooldown`].
71    pub fn attack_cooldown_remaining_ticks(&self) -> usize {
72        let mut ecs = self.ecs.lock();
73        let Ok((attributes, ticks_since_last_attack)) = ecs
74            .query::<(&Attributes, &TicksSinceLastAttack)>()
75            .get(&ecs, self.entity)
76        else {
77            return 0;
78        };
79
80        let attack_strength_delay = get_attack_strength_delay(attributes);
81        let remaining_ticks = attack_strength_delay - **ticks_since_last_attack as f32;
82
83        remaining_ticks.max(0.).ceil() as usize
84    }
85}
86
87/// A component that indicates that this client will be attacking the given
88/// entity next tick.
89#[derive(Component, Clone, Debug)]
90pub struct AttackQueued {
91    pub target: Entity,
92}
93pub fn handle_attack_queued(
94    mut commands: Commands,
95    mut query: Query<(
96        Entity,
97        &mut TicksSinceLastAttack,
98        &mut Physics,
99        &mut Sprinting,
100        &AttackQueued,
101        &LocalGameMode,
102        &ShiftKeyDown,
103        &EntityIdIndex,
104    )>,
105) {
106    for (
107        client_entity,
108        mut ticks_since_last_attack,
109        mut physics,
110        mut sprinting,
111        attack_queued,
112        game_mode,
113        sneaking,
114        entity_id_index,
115    ) in &mut query
116    {
117        let target_entity = attack_queued.target;
118        let Some(target_entity_id) = entity_id_index.get_by_ecs_entity(target_entity) else {
119            warn!("tried to attack entity {target_entity} which isn't in our EntityIdIndex");
120            continue;
121        };
122
123        commands.entity(client_entity).remove::<AttackQueued>();
124
125        commands.trigger(SendPacketEvent::new(
126            client_entity,
127            ServerboundInteract {
128                entity_id: target_entity_id,
129                action: s_interact::ActionType::Attack,
130                using_secondary_action: **sneaking,
131            },
132        ));
133        commands.trigger(SwingArmEvent {
134            entity: client_entity,
135        });
136
137        // we can't attack if we're in spectator mode but it still sends the attack
138        // packet
139        if game_mode.current == GameMode::Spectator {
140            continue;
141        };
142
143        ticks_since_last_attack.0 = 0;
144
145        physics.velocity = physics.velocity.multiply(0.6, 1.0, 0.6);
146        **sprinting = false;
147    }
148}
149
150/// Queues up an attack packet for next tick by inserting the [`AttackQueued`]
151/// component to our client.
152#[derive(Event)]
153pub struct AttackEvent {
154    /// Our client entity that will send the packets to attack.
155    pub entity: Entity,
156    /// The entity that will be attacked.
157    pub target: Entity,
158}
159pub fn handle_attack_event(mut events: EventReader<AttackEvent>, mut commands: Commands) {
160    for event in events.read() {
161        commands.entity(event.entity).insert(AttackQueued {
162            target: event.target,
163        });
164    }
165}
166
167#[derive(Default, Bundle)]
168pub struct AttackBundle {
169    pub ticks_since_last_attack: TicksSinceLastAttack,
170    pub attack_strength_scale: AttackStrengthScale,
171}
172
173#[derive(Default, Component, Clone, Deref, DerefMut)]
174pub struct TicksSinceLastAttack(pub u32);
175pub fn increment_ticks_since_last_attack(mut query: Query<&mut TicksSinceLastAttack>) {
176    for mut ticks_since_last_attack in query.iter_mut() {
177        **ticks_since_last_attack += 1;
178    }
179}
180
181#[derive(Default, Component, Clone, Deref, DerefMut)]
182pub struct AttackStrengthScale(pub f32);
183pub fn update_attack_strength_scale(
184    mut query: Query<(&TicksSinceLastAttack, &Attributes, &mut AttackStrengthScale)>,
185) {
186    for (ticks_since_last_attack, attributes, mut attack_strength_scale) in query.iter_mut() {
187        // look 0.5 ticks into the future because that's what vanilla does
188        **attack_strength_scale =
189            get_attack_strength_scale(ticks_since_last_attack.0, attributes, 0.5);
190    }
191}
192
193/// Returns how long it takes for the attack cooldown to reset (in ticks).
194pub fn get_attack_strength_delay(attributes: &Attributes) -> f32 {
195    ((1. / attributes.attack_speed.calculate()) * 20.) as f32
196}
197
198pub fn get_attack_strength_scale(
199    ticks_since_last_attack: u32,
200    attributes: &Attributes,
201    in_ticks: f32,
202) -> f32 {
203    let attack_strength_delay = get_attack_strength_delay(attributes);
204    let attack_strength = (ticks_since_last_attack as f32 + in_ticks) / attack_strength_delay;
205    attack_strength.clamp(0., 1.)
206}