Skip to content

Commit

Permalink
switch proto mostly over to new proc macro
Browse files Browse the repository at this point in the history
  • Loading branch information
theaddonn committed Sep 29, 2024
1 parent 432fbfc commit bf8f945
Show file tree
Hide file tree
Showing 46 changed files with 281 additions and 200 deletions.
5 changes: 2 additions & 3 deletions crates/macros/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::{Attribute, DataEnum, DataStruct, Field, Fields, GenericArgument, PathArguments, Type};


fn extract_inner_type_from_vec(ty: &Type) -> Option<&Type> {
if let Type::Path(type_path) = ty {
if let Some(last_segment) = type_path.path.segments.last() {
Expand Down Expand Up @@ -148,8 +147,8 @@ pub fn build_de_struct(data_struct: &DataStruct) -> TokenStream {
pub fn build_de_enum(data_enum: &DataEnum, attrs: &[Attribute]) -> TokenStream {
let flags = get_attrs(attrs).expect("Error while getting attrs");

if let (Some(repr), Some(endian)) = (flags.enum_repr, flags.enum_endianness) {
let enum_type_de = build_de_instance(Some(endian), &repr);
if let (Some(repr), endian) = (flags.enum_repr, flags.enum_endianness) {
let enum_type_de = build_de_instance(endian, &repr);

let variants = data_enum.variants.iter().map(|var| {
let desc = var
Expand Down
14 changes: 5 additions & 9 deletions crates/proto/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ use std::future::Future;
use std::io::{Cursor, Write};
use std::sync::Arc;
use std::time::Duration;

use bedrockrs_core::int::LE;
use tokio::select;
use tokio::sync::{broadcast, watch};
use tokio::time::interval;
Expand Down Expand Up @@ -58,9 +56,7 @@ impl Connection {
Some(compression) => {
let mut compressed_stream = vec![];

LE::new(compression.id_u8())
.write(&mut compressed_stream)
.map_err(|e| ConnectionError::IOError(Arc::new(e)))?;
compressed_stream.write_u8(compression.id_u8())?;

// TODO: Overflow checking
if compression.needed() && pk_stream.len() as u16 > compression.threshold() {
Expand Down Expand Up @@ -392,10 +388,10 @@ impl ConnectionShard {
}

pub async fn recv(&mut self) -> Result<GamePackets, ConnectionError> {
match self.pk_receiver.recv().await {
Ok(pk) => pk,
Err(_) => Err(ConnectionError::ConnectionClosed),
}
self.pk_receiver
.recv()
.await
.unwrap_or_else(|_| Err(ConnectionError::ConnectionClosed))
}

pub async fn flush(&mut self) -> Result<(), ConnectionError> {
Expand Down
14 changes: 6 additions & 8 deletions crates/proto/src/gamepackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ use crate::packets::start_game::StartGamePacket;
use crate::packets::text_message::TextMessagePacket;
use crate::packets::toast_request::ToastRequestPacket;
use crate::sub_client::SubClientID;
use bedrockrs_core::int::VAR;
use bedrockrs_macros::gamepackets;
use bedrockrs_proto_core::{error::ProtoCodecError, GamePacket, ProtoCodec};
use std::io::{Cursor, Write};
use varint_rs::{VarintReader, VarintWriter};

gamepackets! {
Login: LoginPacket,
Expand Down Expand Up @@ -269,12 +269,12 @@ fn read_gamepacket_header(
stream: &mut Cursor<&[u8]>,
) -> Result<(u32, u16, SubClientID, SubClientID), ProtoCodecError> {
// Read the gamepacket length
let length = VAR::<u32>::proto_deserialize(stream)?.into_inner();
let length = stream.read_u32_varint()?;

// Read the gamepacket header and parse it into an u16
// Since the (var)int is only storing 14 bytes we can treat it as an u16
// This is normally treated as u32 varint
let game_packet_header: u16 = VAR::<u16>::proto_deserialize(stream)?.into_inner();
let game_packet_header: u16 = stream.read_u16_varint()?;

// Get the first 10 bits as the packet id
// Can never be more than a 16-bit integer due to being 10-bits big
Expand Down Expand Up @@ -326,15 +326,13 @@ fn write_gamepacket_header(
let mut game_packet_header_buf = Vec::new();

// Write the gamepacket header into temporary buffer
VAR::<u16>::new(game_packet_header).proto_serialize(&mut game_packet_header_buf)?;
game_packet_header_buf.write_u16_varint(game_packet_header)?;

// Write the gamepacket length and the header length
VAR::<u32>::new(length + game_packet_header_buf.len() as u32).proto_serialize(stream)?;
stream.write_u32_varint(length + game_packet_header_buf.len() as u32)?;

// Write the final game packet header
stream
.write_all(game_packet_header_buf.as_slice())
.map_err(ProtoCodecError::from)?;
stream.write_all(game_packet_header_buf.as_slice())?;

Ok(())
}
24 changes: 16 additions & 8 deletions crates/proto/src/packets/add_actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,24 @@ pub struct AddActorPacket {
pub target_actor_id: ActorUniqueID,
pub target_runtime_id: ActorRuntimeID,
pub actor_type: String,
pub position: Vec3<LE<f32>>,
pub velocity: Vec3<LE<f32>>,
pub rotation: Vec2<LE<f32>>,
pub y_head_rotation: LE<f32>,
pub y_body_rotation: LE<f32>,
#[len_repr(VAR::<u32>)]
#[endianness(le)]
pub position: Vec3<f32>,
#[endianness(le)]
pub velocity: Vec3<f32>,
#[endianness(le)]
pub rotation: Vec2<f32>,
#[endianness(le)]
pub y_head_rotation: f32,
#[endianness(le)]
pub y_body_rotation: f32,
#[vec_repr(u32)]
#[vec_endianness(var)]
pub attributes: Vec<Attribute>,
#[len_repr(VAR::<u32>)]
#[vec_repr(u32)]
#[vec_endianness(var)]
pub actor_data: Vec<DataItem>,
pub synced_properties: PropertySyncData,
#[len_repr(VAR::<u32>)]
#[vec_repr(u32)]
#[vec_endianness(var)]
pub actor_links: Vec<ActorLink>,
}
17 changes: 10 additions & 7 deletions crates/proto/src/packets/add_player.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::types::ability_data::AbilityData;
use crate::types::actor_link::ActorLink;
use crate::types::network_item_stack_descriptor::NetworkItemStackDescriptor;
use crate::types::item_stack_descriptor::ItemStackDescriptor;
use crate::types::property_sync_data::PropertySyncData;
use bedrockrs_core::int::{LE, VAR};
use bedrockrs_core::Vec3;
use bedrockrs_macros::{gamepacket, ProtoCodec};
use bedrockrs_shared::actor_runtime_id::ActorRuntimeID;
Expand All @@ -16,14 +15,18 @@ pub struct AddPlayerPacket {
pub name: String,
pub runtime_id: ActorRuntimeID,
pub platform_chat_id: String,
pub position: Vec3<LE<f32>>,
pub velocity: Vec3<LE<f32>>,
pub rotation: Vec3<LE<f32>>,
pub carried_item: NetworkItemStackDescriptor,
#[endianness(le)]
pub position: Vec3<f32>,
#[endianness(le)]
pub velocity: Vec3<f32>,
#[endianness(le)]
pub rotation: Vec3<f32>,
pub carried_item: ItemStackDescriptor,
pub gamemode: Gamemode,
// TODO: Impl SyncedActorDataEntityWrapper
pub synced_properties: PropertySyncData,
pub abilities: AbilityData,
#[len_repr(VAR::<u32>)]
#[vec_repr(u32)]
#[vec_endianness(var)]
pub links: Vec<ActorLink>,
}
7 changes: 5 additions & 2 deletions crates/proto/src/packets/chunk_publisher_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ use bedrockrs_macros::{gamepacket, ProtoCodec};
#[derive(ProtoCodec, Debug, Clone)]
pub struct ChunkPublisherUpdatePacket {
pub position: BlockPos,
pub radius: VAR<u32>,
#[len_repr(LE::<u32>)]
#[endianness(var)]
pub radius: u32,
#[vec_repr(u32)]
// TODO: Figure out if it is a var or le
#[vec_endianness(var)]
pub saved_chunks: Vec<ChunkPos>,
}
3 changes: 2 additions & 1 deletion crates/proto/src/packets/emote_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use uuid::Uuid;
#[derive(ProtoCodec, Debug, Clone)]
pub struct EmoteListPacket {
pub runtime_id: ActorRuntimeID,
#[len_repr(VAR::<u32>)]
#[vec_repr(u32)]
#[vec_endianness(var)]
pub emote_piece_ids: Vec<Uuid>,
}
2 changes: 1 addition & 1 deletion crates/proto/src/packets/interact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl ProtoCodec for InteractPacket {
u8::proto_serialize(&action, stream)?;

if let InteractAction::InteractUpdate(pos) = self.action {
pos.to_le().proto_serialize(stream)?;
pos.proto_serialize(stream)?;
}

Ok(())
Expand Down
4 changes: 2 additions & 2 deletions crates/proto/src/packets/inventory_content.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use bedrockrs_core::int::VAR;
use bedrockrs_macros::{gamepacket, ProtoCodec};

use crate::types::network_item_stack_descriptor::NetworkItemStackDescriptor;
use crate::types::item_stack_descriptor::ItemStackDescriptor;

#[gamepacket(id = 49)]
#[derive(ProtoCodec, Debug, Clone)]
pub struct InventoryContentPacket {
pub inventory_id: VAR<u32>,
#[len_repr(VAR::<u32>)]
pub slots: Vec<NetworkItemStackDescriptor>,
pub slots: Vec<ItemStackDescriptor>,
}
3 changes: 2 additions & 1 deletion crates/proto/src/packets/loading_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ use bedrockrs_macros::{gamepacket, ProtoCodec};
#[derive(ProtoCodec, Debug, Clone)]
pub struct LoadingScreenPacket {
pub screen_action: LoadingScreenAction,
pub screen_id: Option<LE<u32>>,
#[endianness(le)]
pub screen_id: Option<u32>,
}
4 changes: 2 additions & 2 deletions crates/proto/src/packets/mob_equipment.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use bedrockrs_core::int::VAR;
use bedrockrs_macros::{gamepacket, ProtoCodec};

use crate::types::network_item_stack_descriptor::NetworkItemStackDescriptor;
use crate::types::item_stack_descriptor::ItemStackDescriptor;

#[gamepacket(id = 31)]
#[derive(ProtoCodec, Debug, Clone)]
pub struct MobEquipmentPacket {
pub runtime_id: VAR<i32>,
pub item_stack_descriptor: NetworkItemStackDescriptor,
pub item_stack_descriptor: ItemStackDescriptor,
pub slot: u8,
pub selected_slot: u8,
pub container: u8,
Expand Down
3 changes: 2 additions & 1 deletion crates/proto/src/packets/modal_form_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use bedrockrs_macros::{gamepacket, ProtoCodec};
#[gamepacket(id = 101)]
#[derive(ProtoCodec, Debug, Clone)]
pub struct ModalFormResponsePacket {
pub form_id: VAR<u32>,
#[endianness(var)]
pub form_id: u32,
pub form_response: Option<String>,
pub cancel_reason: Option<ModalFormCancelReason>,
}
3 changes: 2 additions & 1 deletion crates/proto/src/packets/player_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ pub struct PlayerActionPacket {
pub action: PlayerActionType,
pub block_pos: BlockPos,
pub result_pos: BlockPos,
pub face: VAR<i32>,
#[endianness(var)]
pub face: i32,
}
48 changes: 26 additions & 22 deletions crates/proto/src/packets/player_auth_input.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::types::block_actions::BlockActions;
use crate::types::input_data::InputData;
use crate::types::input_mode::InputMode;
use crate::types::interaction_model::InteractionModel;
Expand All @@ -6,26 +7,26 @@ use bedrockrs_core::int::{LE, VAR};
use bedrockrs_core::{Vec2, Vec3};
use bedrockrs_macros::gamepacket;
use bedrockrs_proto_core::error::ProtoCodecError;
use bedrockrs_proto_core::ProtoCodec;
use bedrockrs_proto_core::{ProtoCodec, ProtoCodecLE, ProtoCodecVAR};
use bedrockrs_shared::actor_unique_id::ActorUniqueID;
use std::io::Cursor;

#[gamepacket(id = 144)]
#[derive(Debug, Clone)]
pub struct PlayerAuthInputPacket {
pub rotation: Vec2<LE<f32>>,
pub position: Vec3<LE<f32>>,
pub move_vec: Vec2<LE<f32>>,
pub head_rotation: LE<f32>,
pub rotation: Vec2<f32>,
pub position: Vec3<f32>,
pub move_vec: Vec2<f32>,
pub head_rotation: f32,
pub input_data: InputData,
pub input_mode: InputMode,
pub play_mode: PlayMode,
pub interaction_model: InteractionModel,
/// Which simulation frame client is on. Used to match corrections
pub client_tick: VAR<u64>,
/// Which simulation frame client is on, used to match corrections
pub client_tick: u64,
/// Velocity
pub pos_delta: Vec3<LE<f32>>,
pub analog_move_vec: Vec2<LE<f32>>,
pub pos_delta: Vec3<f32>,
pub analog_move_vec: Vec2<f32>,
}

macro_rules! set_bit {
Expand All @@ -46,14 +47,14 @@ impl ProtoCodec for PlayerAuthInputPacket {
}

fn proto_deserialize(stream: &mut Cursor<&[u8]>) -> Result<Self, ProtoCodecError> {
let rotation = Vec2::<LE<f32>>::proto_deserialize(stream)?;
let position = Vec3::<LE<f32>>::proto_deserialize(stream)?;
let move_vec = Vec2::<LE<f32>>::proto_deserialize(stream)?;
let head_rotation = LE::<f32>::proto_deserialize(stream)?;
let rotation = <Vec2<f32> as ProtoCodecLE>::proto_deserialize(stream)?;
let position = <Vec3<f32> as ProtoCodecLE>::proto_deserialize(stream)?;
let move_vec = <Vec2<f32> as ProtoCodecLE>::proto_deserialize(stream)?;
let head_rotation = <f32 as ProtoCodecLE>::proto_deserialize(stream)?;

let input_data = VAR::<u64>::proto_deserialize(stream)?.into_inner();
let input_data = <u64 as ProtoCodecVAR>::proto_deserialize(stream)?;
let input_mode = InputMode::proto_deserialize(stream)?;
let play_mode_int = VAR::<u32>::proto_deserialize(stream)?.into_inner();
let play_mode_int = <u32 as ProtoCodecVAR>::proto_deserialize(stream)?;
let interaction_model = InteractionModel::proto_deserialize(stream)?;

let play_mode = match play_mode_int {
Expand All @@ -77,13 +78,13 @@ impl ProtoCodec for PlayerAuthInputPacket {
}
};

let client_tick = VAR::<u64>::proto_deserialize(stream)?;
let pos_delta = Vec3::<LE<f32>>::proto_deserialize(stream)?;
let client_tick = <u64 as ProtoCodecVAR>::proto_deserialize(stream)?;
let pos_delta = <Vec3<f32> as ProtoCodecLE>::proto_deserialize(stream)?;

let input_data = InputData {
ascend: get_bit!(input_data, 0),
descend: get_bit!(input_data, 1),
north_jump_DEPRECATED: get_bit!(input_data, 2),
north_jump_deprecated: get_bit!(input_data, 2),
jump_down: get_bit!(input_data, 3),
sprint_down: get_bit!(input_data, 4),
change_height: get_bit!(input_data, 5),
Expand Down Expand Up @@ -116,7 +117,11 @@ impl ProtoCodec for PlayerAuthInputPacket {
start_gliding: get_bit!(input_data, 32),
stop_gliding: get_bit!(input_data, 33),
perform_item_interaction: get_bit!(input_data, 34),
perform_block_actions: get_bit!(input_data, 35),
perform_block_actions: if get_bit!(input_data, 35) {
Some(BlockActions::proto_deserialize(stream)?)
} else {
None
},
perform_item_stack_request: get_bit!(input_data, 36),
handled_teleport: get_bit!(input_data, 37),
emoting: get_bit!(input_data, 38),
Expand All @@ -128,9 +133,8 @@ impl ProtoCodec for PlayerAuthInputPacket {
client_ack_server_data: get_bit!(input_data, 44),
is_in_client_predicted_vehicle: {
if get_bit!(input_data, 45) {
let vehicle_rotation = Vec2::<LE<f32>>::proto_deserialize(stream)?;
let vehicle_rotation = <Vec2<f32> as ProtoCodecLE>::proto_deserialize(stream)?;
let client_predicted_vehicle = ActorUniqueID::proto_deserialize(stream)?;

Some((vehicle_rotation, client_predicted_vehicle))
} else {
None
Expand All @@ -142,7 +146,7 @@ impl ProtoCodec for PlayerAuthInputPacket {
input_num: get_bit!(input_data, 49),
};

let analog_move_vec = Vec2::<LE<f32>>::proto_deserialize(stream)?;
let analog_move_vec = <Vec2<f32> as ProtoCodecLE>::proto_deserialize(stream)?;

Ok(Self {
rotation,
Expand Down
7 changes: 4 additions & 3 deletions crates/proto/src/packets/player_disconnect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ impl ProtoCodec for DisconnectPlayerPacket {
// Read if the message should be skipped
let skip_message = bool::proto_deserialize(cursor)?;

let message = match skip_message {
true => None,
false => Some(String::proto_deserialize(cursor)?),
let message = if !skip_message {
Some(String::proto_deserialize(cursor)?)
} else {
None
};

Ok(Self { reason, message })
Expand Down
9 changes: 6 additions & 3 deletions crates/proto/src/packets/resource_packs_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@ pub struct ResourcePacksInfoPacket {
pub has_addon_packs: bool,
pub has_scripts: bool,
pub force_server_packs_enabled: bool,
#[len_repr(LE::<u16>)]
#[vec_repr(u16)]
#[vec_endianness(le)]
pub behavior_packs: Vec<BehaviorPackInfoType>,
#[len_repr(LE::<u16>)]
#[vec_repr(u16)]
#[vec_endianness(le)]
pub resource_packs: Vec<ResourcePackInfoType>,
#[len_repr(VAR::<u32>)]
#[vec_repr(u32)]
#[vec_endianness(var)]
pub cdn_urls: Vec<PackURL>,
}
Loading

0 comments on commit bf8f945

Please sign in to comment.