chunkedge_server/
custom_payload.rs1use 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, PacketEvent};
9
10pub struct CustomPayloadPlugin;
11
12impl Plugin for CustomPayloadPlugin {
13 fn build(&self, app: &mut App) {
14 app.add_event::<CustomPayloadEvent>()
15 .add_systems(EventLoopPreUpdate, handle_custom_payload);
16 }
17}
18
19#[derive(Event, Clone, Debug)]
20pub struct CustomPayloadEvent {
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: EventReader<PacketEvent>,
37 mut events: EventWriter<CustomPayloadEvent>,
38) {
39 for packet in packets.read() {
40 if let Some(pkt) = packet.decode::<CustomPayloadC2s>() {
41 events.send(CustomPayloadEvent {
42 client: packet.client,
43 channel: pkt.channel.into(),
44 data: pkt.data.0 .0.into(),
45 });
46 }
47 }
48}