Skip to main content

chunkedge_server/
custom_payload.rs

1use bevy_app::prelude::*;
2use bevy_ecs::prelude::*;
3use chunkedge_binary::Bounded;
4use chunkedge_protocol::packets::play::{CustomPayloadC2s, CustomPayloadS2c};
5use chunkedge_protocol::{Ident, WritePacket};
6
7use crate::client::Client;
8use crate::event_loop::{EventLoopPreUpdate, PacketMessage};
9
10pub struct CustomPayloadPlugin;
11
12impl Plugin for CustomPayloadPlugin {
13    fn build(&self, app: &mut App) {
14        app.add_message::<CustomPayloadMessage>()
15            .add_systems(EventLoopPreUpdate, handle_custom_payload);
16    }
17}
18
19#[derive(Message, Clone, Debug)]
20pub struct CustomPayloadMessage {
21    pub client: Entity,
22    pub channel: Ident<String>,
23    pub data: Box<[u8]>,
24}
25
26impl Client {
27    pub fn send_custom_payload(&mut self, channel: Ident<&str>, data: &[u8]) {
28        self.write_packet(&CustomPayloadS2c {
29            channel: channel.into(),
30            data: Bounded(data.into()),
31        });
32    }
33}
34
35fn handle_custom_payload(
36    mut packets: MessageReader<PacketMessage>,
37    mut messages: MessageWriter<CustomPayloadMessage>,
38) {
39    for packet in packets.read() {
40        if let Some(pkt) = packet.decode::<CustomPayloadC2s>() {
41            messages.write(CustomPayloadMessage {
42                client: packet.client,
43                channel: pkt.channel.into(),
44                data: pkt.data.0.0.into(),
45            });
46        }
47    }
48}