1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 14:26:04 +00:00
azalea/azalea-client/src/plugins/packet/login/events.rs
2025-04-11 17:31:23 -10:00

71 lines
2 KiB
Rust

use std::sync::Arc;
use azalea_protocol::packets::{
Packet,
login::{ClientboundHello, ClientboundLoginPacket, ServerboundLoginPacket},
};
use bevy_ecs::prelude::*;
use tracing::{debug, error};
use super::InLoginState;
use crate::{Account, connection::RawConnection};
#[derive(Event, Debug, Clone)]
pub struct ReceiveLoginPacketEvent {
/// The client entity that received the packet.
pub entity: Entity,
/// The packet that was actually received.
pub packet: Arc<ClientboundLoginPacket>,
}
#[derive(Event)]
pub struct ReceiveHelloEvent {
pub account: Account,
pub packet: ClientboundHello,
}
/// Event for sending a login packet to the server.
#[derive(Event, Clone)]
pub struct SendLoginPacketEvent {
pub sent_by: Entity,
pub packet: ServerboundLoginPacket,
}
impl SendLoginPacketEvent {
pub fn new(entity: Entity, packet: impl Packet<ServerboundLoginPacket>) -> Self {
let packet = packet.into_variant();
Self {
sent_by: entity,
packet,
}
}
}
pub fn handle_outgoing_packets_observer(
trigger: Trigger<SendLoginPacketEvent>,
mut query: Query<(&mut RawConnection, Option<&InLoginState>)>,
) {
let event = trigger.event();
if let Ok((mut raw_conn, in_login_state)) = query.get_mut(event.sent_by) {
if in_login_state.is_none() {
error!(
"Tried to send a login packet {:?} while not in login state",
event.packet
);
return;
}
debug!("Sending login packet: {:?}", event.packet);
if let Err(e) = raw_conn.write(event.packet.clone()) {
error!("Failed to send packet: {e}");
}
}
}
/// A system that converts [`SendLoginPacketEvent`] events into triggers so
/// they get received by [`handle_outgoing_packets_observer`].
pub fn handle_outgoing_packets(
mut commands: Commands,
mut events: EventReader<SendLoginPacketEvent>,
) {
for event in events.read() {
commands.trigger(event.clone());
}
}