1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use valence_protocol::packets::play::PlayerInteractItemC2s;
use valence_protocol::Hand;

use crate::action::ActionSequence;
use crate::event_loop::{EventLoopPreUpdate, PacketEvent};

pub struct InteractItemPlugin;

impl Plugin for InteractItemPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<InteractItemEvent>()
            .add_systems(EventLoopPreUpdate, handle_player_interact_item);
    }
}

#[derive(Event, Copy, Clone, Debug)]
pub struct InteractItemEvent {
    pub client: Entity,
    pub hand: Hand,
    pub sequence: i32,
}

fn handle_player_interact_item(
    mut packets: EventReader<PacketEvent>,
    mut clients: Query<&mut ActionSequence>,
    mut events: EventWriter<InteractItemEvent>,
) {
    for packet in packets.read() {
        if let Some(pkt) = packet.decode::<PlayerInteractItemC2s>() {
            if let Ok(mut action_seq) = clients.get_mut(packet.client) {
                action_seq.update(pkt.sequence.0);
            }

            events.send(InteractItemEvent {
                client: packet.client,
                hand: pkt.hand,
                sequence: pkt.sequence.0,
            });
        }
    }
}