aboutsummaryrefslogtreecommitdiff
path: root/azalea-client/src/plugins/packet/mod.rs
blob: 546405e0ba45d636ae214f20f705a83b72fed730 (plain)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use azalea_entity::metadata::Health;
use bevy_app::{App, Plugin, Update};
use bevy_ecs::{
    prelude::*,
    system::{SystemParam, SystemState},
};

use self::game::DeathEvent;
use crate::client_chat::ChatReceivedEvent;

pub mod config;
pub mod game;
pub mod login;
pub mod relative_updates;

pub struct PacketPlugin;

pub fn death_event_on_0_health(
    query: Query<(Entity, &Health), Changed<Health>>,
    mut death_events: MessageWriter<DeathEvent>,
) {
    for (entity, health) in query.iter() {
        if **health == 0. {
            death_events.write(DeathEvent {
                entity,
                packet: None,
            });
        }
    }
}

impl Plugin for PacketPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            relative_updates::debug_detect_updates_received_on_local_entities,
        )
        .add_observer(game::handle_outgoing_packets_observer)
        .add_observer(config::handle_outgoing_packets_observer)
        .add_observer(login::handle_outgoing_packets_observer)
        .add_systems(Update, death_event_on_0_health)
        .add_message::<game::ReceiveGamePacketEvent>()
        .add_message::<config::ReceiveConfigPacketEvent>()
        .add_message::<login::ReceiveLoginPacketEvent>()
        //
        .add_message::<game::AddPlayerEvent>()
        .add_message::<game::RemovePlayerEvent>()
        .add_message::<game::UpdatePlayerEvent>()
        .add_message::<ChatReceivedEvent>()
        .add_message::<game::DeathEvent>()
        .add_message::<game::ResourcePackEvent>()
        .add_message::<game::WorldLoadedEvent>()
        .add_message::<login::ReceiveCustomQueryEvent>();
    }
}

pub(crate) use azalea_protocol::azalea_protocol_macros::declare_packet_handlers;

#[derive(Resource)]
struct CachedSystemState<T: SystemParam + 'static>(SystemState<T>);

pub(crate) fn as_system<T>(ecs: &mut World, f: impl FnOnce(T::Item<'_, '_>))
where
    T: SystemParam + 'static,
{
    // creating a new SystemState is expensive, so we save them as a Resource in the
    // ecs
    let mut system_state = match ecs.remove_resource::<CachedSystemState<T>>() {
        Some(s) => s.0,
        None => SystemState::<T>::new(ecs),
    };
    let values = system_state.get_mut(ecs);
    f(values);
    system_state.apply(ecs);
    ecs.insert_resource(CachedSystemState(system_state));
}