From 85febf0789d92ca730f13163f431507eb8ae55ed Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 6 Aug 2023 00:25:04 -0700 Subject: [PATCH 01/17] Add `valence_math` --- Cargo.toml | 10 +- crates/valence_block/Cargo.toml | 4 +- crates/valence_block/build.rs | 11 +- crates/valence_client/Cargo.toml | 2 +- crates/valence_client/src/interact_block.rs | 2 +- crates/valence_client/src/lib.rs | 2 +- crates/valence_client/src/movement.rs | 2 +- crates/valence_client/src/teleport.rs | 2 +- crates/valence_core/Cargo.toml | 2 +- crates/valence_core/src/aabb.rs | 68 ------ crates/valence_core/src/block_pos.rs | 2 +- crates/valence_core/src/chunk_pos.rs | 2 +- crates/valence_core/src/lib.rs | 1 - crates/valence_core/src/protocol/impls.rs | 2 +- crates/valence_entity/Cargo.toml | 2 +- crates/valence_entity/build.rs | 8 +- crates/valence_entity/src/hitbox.rs | 26 +-- crates/valence_entity/src/lib.rs | 2 +- crates/valence_entity/src/query.rs | 2 +- crates/valence_layer/Cargo.toml | 2 +- crates/valence_layer/src/chunk.rs | 2 +- crates/valence_math/Cargo.toml | 10 + crates/valence_math/src/aabb.rs | 215 ++++++++++++++++++ crates/valence_math/src/lib.rs | 4 + crates/valence_packet/Cargo.toml | 2 +- crates/valence_packet/src/packets/play.rs | 2 +- .../src/packets/play/particle_s2c.rs | 2 +- crates/valence_scoreboard/src/lib.rs | 20 +- crates/valence_world_border/Cargo.toml | 2 +- src/lib.rs | 4 +- tools/playground/Cargo.toml | 2 +- 31 files changed, 291 insertions(+), 128 deletions(-) delete mode 100644 crates/valence_core/src/aabb.rs create mode 100644 crates/valence_math/Cargo.toml create mode 100644 crates/valence_math/src/aabb.rs create mode 100644 crates/valence_math/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 58ffa19d1..887675051 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,23 +52,24 @@ valence_client.workspace = true valence_core.workspace = true valence_dimension.workspace = true valence_entity.workspace = true -valence_layer.workspace = true valence_inventory = { workspace = true, optional = true } +valence_layer.workspace = true +valence_math = { workspace = true } valence_nbt.workspace = true valence_network = { workspace = true, optional = true } +valence_packet.workspace = true valence_player_list = { workspace = true, optional = true } valence_registry.workspace = true valence_scoreboard = { workspace = true, optional = true } -valence_world_border = { workspace = true, optional = true } -valence_packet.workspace = true valence_weather = { workspace = true, optional = true } +valence_world_border = { workspace = true, optional = true } [dev-dependencies] anyhow.workspace = true clap.workspace = true criterion.workspace = true flume.workspace = true -noise.workspace = true # For the terrain example. +noise.workspace = true # For the terrain example. tracing.workspace = true [dev-dependencies.reqwest] @@ -189,5 +190,6 @@ valence_world_border.path = "crates/valence_world_border" valence_boss_bar.path = "crates/valence_boss_bar" valence_packet.path = "crates/valence_packet" valence_weather.path = "crates/valence_weather" +valence_math.path = "crates/valence_math" valence.path = "." zip = "0.6.3" diff --git a/crates/valence_block/Cargo.toml b/crates/valence_block/Cargo.toml index c74b46dc1..971b4f3ff 100644 --- a/crates/valence_block/Cargo.toml +++ b/crates/valence_block/Cargo.toml @@ -4,9 +4,9 @@ version.workspace = true edition.workspace = true [dependencies] -valence_core.workspace = true anyhow.workspace = true -glam.workspace = true +valence_core.workspace = true +valence_math.workspace = true [build-dependencies] anyhow.workspace = true diff --git a/crates/valence_block/build.rs b/crates/valence_block/build.rs index a3d7829e2..3e8a6eed0 100644 --- a/crates/valence_block/build.rs +++ b/crates/valence_block/build.rs @@ -161,10 +161,10 @@ fn build() -> anyhow::Result { let max_y = s.max_y; let max_z = s.max_z; quote! { - Aabb { - min: dvec3(#min_x, #min_y, #min_z), - max: dvec3(#max_x, #max_y, #max_z), - } + Aabb::new_unchecked( + DVec3::new(#min_x, #min_y, #min_z), + DVec3::new(#max_x, #max_y, #max_z), + ) } }); @@ -573,8 +573,7 @@ fn build() -> anyhow::Result { let prop_value_count = prop_values.len(); Ok(quote! { - use valence_core::aabb::Aabb; - use glam::dvec3; + use valence_math::{Aabb, DVec3}; /// Represents the state of a block. This does not include block entity data such as /// the text on a sign, the design on a banner, or the content of a spawner. diff --git a/crates/valence_client/Cargo.toml b/crates/valence_client/Cargo.toml index 942d57ea8..b8a891702 100644 --- a/crates/valence_client/Cargo.toml +++ b/crates/valence_client/Cargo.toml @@ -10,7 +10,7 @@ bevy_ecs.workspace = true bevy_utils.workspace = true # Needed for `ScheduleLabel` derive macro. bitfield-struct.workspace = true bytes.workspace = true -glam.workspace = true +valence_math.workspace = true rand.workspace = true tracing.workspace = true uuid.workspace = true diff --git a/crates/valence_client/src/interact_block.rs b/crates/valence_client/src/interact_block.rs index f9bf8fe5e..229145e3d 100644 --- a/crates/valence_client/src/interact_block.rs +++ b/crates/valence_client/src/interact_block.rs @@ -1,9 +1,9 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use glam::Vec3; use valence_core::block_pos::BlockPos; use valence_core::direction::Direction; use valence_core::hand::Hand; +use valence_math::Vec3; use valence_packet::packets::play::PlayerInteractBlockC2s; use crate::action::ActionSequence; diff --git a/crates/valence_client/src/lib.rs b/crates/valence_client/src/lib.rs index b0b730acd..437ce257e 100644 --- a/crates/valence_client/src/lib.rs +++ b/crates/valence_client/src/lib.rs @@ -31,7 +31,6 @@ use bevy_ecs::query::WorldQuery; use bevy_ecs::system::Command; use byteorder::{NativeEndian, ReadBytesExt}; use bytes::{Bytes, BytesMut}; -use glam::{DVec3, Vec3}; use tracing::warn; use uuid::Uuid; use valence_biome::BiomeRegistry; @@ -55,6 +54,7 @@ use valence_entity::{ Velocity, }; use valence_layer::{ChunkLayer, EntityLayer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; +use valence_math::{DVec3, Vec3}; use valence_packet::packets::play::chunk_biome_data_s2c::ChunkBiome; use valence_packet::packets::play::game_state_change_s2c::GameEventKind; use valence_packet::packets::play::particle_s2c::Particle; diff --git a/crates/valence_client/src/movement.rs b/crates/valence_client/src/movement.rs index 2cf34b73e..8f60155ad 100644 --- a/crates/valence_client/src/movement.rs +++ b/crates/valence_client/src/movement.rs @@ -1,7 +1,7 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use glam::DVec3; use valence_entity::{HeadYaw, Look, OnGround, Position}; +use valence_math::DVec3; use valence_packet::packets::play::{ FullC2s, LookAndOnGroundC2s, OnGroundOnlyC2s, PositionAndOnGroundC2s, VehicleMoveC2s, }; diff --git a/crates/valence_client/src/teleport.rs b/crates/valence_client/src/teleport.rs index dd8b6ae49..86d83a05f 100644 --- a/crates/valence_client/src/teleport.rs +++ b/crates/valence_client/src/teleport.rs @@ -1,4 +1,4 @@ -use glam::DVec3; +use valence_math::DVec3; use valence_packet::packets::play::player_position_look_s2c::PlayerPositionLookFlags; use valence_packet::packets::play::{PlayerPositionLookS2c, TeleportConfirmC2s}; diff --git a/crates/valence_core/Cargo.toml b/crates/valence_core/Cargo.toml index 7c3f94964..f06a28df1 100644 --- a/crates/valence_core/Cargo.toml +++ b/crates/valence_core/Cargo.toml @@ -18,7 +18,7 @@ byteorder.workspace = true bytes.workspace = true cfb8 = { workspace = true, optional = true } flate2 = { workspace = true, optional = true } -glam.workspace = true +valence_math.workspace = true serde = { workspace = true, features = ["derive"] } serde_json.workspace = true thiserror.workspace = true diff --git a/crates/valence_core/src/aabb.rs b/crates/valence_core/src/aabb.rs deleted file mode 100644 index 3c6949d91..000000000 --- a/crates/valence_core/src/aabb.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::ops::Add; - -use glam::DVec3; - -/// An axis-aligned bounding box. `min` is expected to be <= `max` -/// componentwise. -#[derive(Copy, Clone, PartialEq, Default, Debug)] -pub struct Aabb { - pub min: DVec3, - pub max: DVec3, -} - -impl Aabb { - pub fn new(p0: impl Into, p1: impl Into) -> Self { - let p0 = p0.into(); - let p1 = p1.into(); - Self { - min: p0.min(p1), - max: p0.max(p1), - } - } - - pub fn from_bottom_size(bottom: impl Into, size: impl Into) -> Self { - let bottom = bottom.into(); - let size = size.into(); - - Self { - min: DVec3 { - x: bottom.x - size.x / 2.0, - y: bottom.y, - z: bottom.z - size.z / 2.0, - }, - max: DVec3 { - x: bottom.x + size.x / 2.0, - y: bottom.y + size.y, - z: bottom.z + size.z / 2.0, - }, - } - } - - pub fn intersects(&self, second: Aabb) -> bool { - self.max.x >= second.min.x - && second.max.x >= self.min.x - && self.max.y >= second.min.y - && second.max.y >= self.min.y - && self.max.z >= second.min.z - && second.max.z >= self.min.z - } -} - -impl Add for Aabb { - type Output = Aabb; - - fn add(self, rhs: DVec3) -> Self::Output { - Self { - min: self.min + rhs, - max: self.max + rhs, - } - } -} - -impl Add for DVec3 { - type Output = Aabb; - - fn add(self, rhs: Aabb) -> Self::Output { - rhs + self - } -} diff --git a/crates/valence_core/src/block_pos.rs b/crates/valence_core/src/block_pos.rs index f14024e69..8cac7b13d 100644 --- a/crates/valence_core/src/block_pos.rs +++ b/crates/valence_core/src/block_pos.rs @@ -2,7 +2,7 @@ use std::io::Write; use std::ops::{Add, Sub}; use anyhow::bail; -use glam::DVec3; +use valence_math::DVec3; use crate::chunk_pos::ChunkPos; use crate::direction::Direction; diff --git a/crates/valence_core/src/chunk_pos.rs b/crates/valence_core/src/chunk_pos.rs index 88db14dbd..0d7c5601d 100644 --- a/crates/valence_core/src/chunk_pos.rs +++ b/crates/valence_core/src/chunk_pos.rs @@ -1,4 +1,4 @@ -use glam::DVec3; +use valence_math::DVec3; use crate::block_pos::BlockPos; use crate::protocol::{Decode, Encode}; diff --git a/crates/valence_core/src/lib.rs b/crates/valence_core/src/lib.rs index aa1f59eea..55eca6a5d 100644 --- a/crates/valence_core/src/lib.rs +++ b/crates/valence_core/src/lib.rs @@ -18,7 +18,6 @@ )] #![allow(clippy::unusual_byte_groupings)] -pub mod aabb; pub mod block_pos; pub mod chunk_pos; pub mod despawn; diff --git a/crates/valence_core/src/protocol/impls.rs b/crates/valence_core/src/protocol/impls.rs index e14bb2132..3a026f6c2 100644 --- a/crates/valence_core/src/protocol/impls.rs +++ b/crates/valence_core/src/protocol/impls.rs @@ -12,8 +12,8 @@ use std::sync::Arc; use anyhow::{ensure, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; -use glam::*; use uuid::Uuid; +use valence_math::*; use valence_nbt::Compound; use super::var_int::VarInt; diff --git a/crates/valence_entity/Cargo.toml b/crates/valence_entity/Cargo.toml index c6383b515..0649df315 100644 --- a/crates/valence_entity/Cargo.toml +++ b/crates/valence_entity/Cargo.toml @@ -8,7 +8,7 @@ anyhow.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true bitfield-struct.workspace = true -glam.workspace = true +valence_math.workspace = true paste.workspace = true rustc-hash.workspace = true tracing.workspace = true diff --git a/crates/valence_entity/build.rs b/crates/valence_entity/build.rs index 4d018771d..a34e87be4 100644 --- a/crates/valence_entity/build.rs +++ b/crates/valence_entity/build.rs @@ -149,8 +149,8 @@ impl Value { Value::OptionalGlobalPos(_) => quote!(()), // TODO Value::PaintingVariant(_) => quote!(crate::PaintingKind), Value::SnifferState(_) => quote!(crate::SnifferState), - Value::Vector3f { .. } => quote!(glam::f32::Vec3), - Value::Quaternionf { .. } => quote!(glam::f32::Quat), + Value::Vector3f { .. } => quote!(valence_math::Vec3), + Value::Quaternionf { .. } => quote!(valence_math::Quat), } } @@ -251,9 +251,9 @@ impl Value { let state = ident(s.replace('.', "_").to_pascal_case()); quote!(crate::SnifferState::#state) } - Value::Vector3f { x, y, z } => quote!(glam::f32::Vec3::new(#x, #y, #z)), + Value::Vector3f { x, y, z } => quote!(valence_math::Vec3::new(#x, #y, #z)), Value::Quaternionf { x, y, z, w } => quote! { - glam::f32::Quat::from_xyzw(#x, #y, #z, #w) + valence_math::Quat::from_xyzw(#x, #y, #z, #w) }, } } diff --git a/crates/valence_entity/src/hitbox.rs b/crates/valence_entity/src/hitbox.rs index b74dd348a..fc4778464 100644 --- a/crates/valence_entity/src/hitbox.rs +++ b/crates/valence_entity/src/hitbox.rs @@ -2,9 +2,8 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use glam::{DVec3, UVec3, Vec3Swizzles}; -use valence_core::aabb::Aabb; use valence_core::direction::Direction; +use valence_math::{Aabb, DVec3, UVec3, Vec3Swizzles}; use crate::*; @@ -73,17 +72,14 @@ impl Plugin for HitboxPlugin { #[derive(Component, Debug, PartialEq)] pub struct HitboxShape(pub Aabb); -#[derive(Component, Debug)] -/// Hitbox, aabb of which is calculated each tick using it's position and +/// Hitbox, aabb of which is calculated each tick using its position and /// [`Hitbox`]. In order to change size of this hitbox you need to change -/// [`Hitbox`] +/// [`Hitbox`]. +#[derive(Component, Debug)] pub struct Hitbox(Aabb); impl HitboxShape { - pub const ZERO: HitboxShape = HitboxShape(Aabb { - min: DVec3::ZERO, - max: DVec3::ZERO, - }); + pub const ZERO: HitboxShape = HitboxShape(Aabb::ZERO); pub fn get(&self) -> Aabb { self.0 @@ -428,10 +424,7 @@ fn update_item_frame_hitbox( _ => BOUNDS23.zxy(), }; - hitbox.0 = Aabb { - min: center_pos - bounds, - max: center_pos + bounds, - } + hitbox.0 = Aabb::new(center_pos - bounds, center_pos + bounds); } } @@ -514,10 +507,7 @@ fn update_painting_hitbox( _ => DVec3::new(bounds.x as f64, bounds.y as f64, 0.0625), }; - hitbox.0 = Aabb { - min: center_pos - bounds / 2.0, - max: center_pos + bounds / 2.0, - }; + hitbox.0 = Aabb::new(center_pos - bounds / 2.0, center_pos + bounds / 2.0); } } @@ -553,6 +543,6 @@ fn update_shulker_hitbox( Direction::East => min.x -= peek, } - hitbox.0 = Aabb { min, max }; + hitbox.0 = Aabb::new(min, max); } } diff --git a/crates/valence_entity/src/lib.rs b/crates/valence_entity/src/lib.rs index ad25c8a44..6d9a54496 100644 --- a/crates/valence_entity/src/lib.rs +++ b/crates/valence_entity/src/lib.rs @@ -26,7 +26,6 @@ pub mod tracked_data; use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use glam::{DVec3, Vec3}; pub use manager::EntityManager; use paste::paste; use tracing::warn; @@ -38,6 +37,7 @@ use valence_core::protocol::var_int::VarInt; use valence_core::protocol::{Decode, Encode}; use valence_core::uuid::UniqueId; use valence_core::DEFAULT_TPS; +use valence_math::{DVec3, Vec3}; include!(concat!(env!("OUT_DIR"), "/entity.rs")); pub struct EntityPlugin; diff --git a/crates/valence_entity/src/query.rs b/crates/valence_entity/src/query.rs index dd3cd2262..23a5f6d4a 100644 --- a/crates/valence_entity/src/query.rs +++ b/crates/valence_entity/src/query.rs @@ -3,10 +3,10 @@ use std::mem; use bevy_ecs::prelude::DetectChanges; use bevy_ecs::query::WorldQuery; use bevy_ecs::world::Ref; -use glam::DVec3; use valence_core::protocol::byte_angle::ByteAngle; use valence_core::protocol::var_int::VarInt; use valence_core::uuid::UniqueId; +use valence_math::DVec3; use valence_packet::packets::play::{ EntityAnimationS2c, EntityPositionS2c, EntitySetHeadYawS2c, EntitySpawnS2c, EntityStatusS2c, EntityTrackerUpdateS2c, EntityVelocityUpdateS2c, ExperienceOrbSpawnS2c, MoveRelativeS2c, diff --git a/crates/valence_layer/Cargo.toml b/crates/valence_layer/Cargo.toml index 14f134da9..67d2994db 100644 --- a/crates/valence_layer/Cargo.toml +++ b/crates/valence_layer/Cargo.toml @@ -8,7 +8,7 @@ anyhow.workspace = true arrayvec.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true -glam.workspace = true +valence_math.workspace = true num-integer.workspace = true parking_lot.workspace = true rand.workspace = true diff --git a/crates/valence_layer/src/chunk.rs b/crates/valence_layer/src/chunk.rs index ea7ad59bf..8e5312e93 100644 --- a/crates/valence_layer/src/chunk.rs +++ b/crates/valence_layer/src/chunk.rs @@ -10,7 +10,6 @@ use std::fmt; use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use glam::{DVec3, Vec3}; use rustc_hash::FxHashMap; use valence_biome::{BiomeId, BiomeRegistry}; use valence_core::block_pos::BlockPos; @@ -20,6 +19,7 @@ use valence_core::protocol::Encode; use valence_core::sound::{Sound, SoundCategory}; use valence_core::Server; use valence_dimension::DimensionTypeRegistry; +use valence_math::{DVec3, Vec3}; use valence_nbt::Compound; use valence_packet::packets::play::particle_s2c::Particle; use valence_packet::packets::play::{ParticleS2c, PlaySoundS2c}; diff --git a/crates/valence_math/Cargo.toml b/crates/valence_math/Cargo.toml new file mode 100644 index 000000000..267134dca --- /dev/null +++ b/crates/valence_math/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "valence_math" +version.workspace = true +edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true + +[dependencies] +glam.workspace = true diff --git a/crates/valence_math/src/aabb.rs b/crates/valence_math/src/aabb.rs new file mode 100644 index 000000000..8be33c53e --- /dev/null +++ b/crates/valence_math/src/aabb.rs @@ -0,0 +1,215 @@ +use std::ops::{Add, Sub}; + +use glam::DVec3; + +/// A three-dimensional axis-aligned bounding box, or "AABB". +/// +/// The AABB is defined by two points—`min` and `max`. `min` is less than or +/// equal to `max` componentwise. +#[derive(Copy, Clone, PartialEq, Default, Debug)] +pub struct Aabb { + min: DVec3, + max: DVec3, +} + +impl Aabb { + pub const ZERO: Self = Self { + min: DVec3::ZERO, + max: DVec3::ZERO, + }; + + /// Constructs a new AABB from `min` and `max` points. + /// + /// # Panics + /// + /// Panics if `debug_assertions` are enabled and `min` is not less than or + /// equal to `max` componentwise. + #[cfg_attr(debug_assertions, track_caller)] + pub fn new(min: DVec3, max: DVec3) -> Self { + debug_assert!( + min.x <= max.x && min.y <= max.y && min.z <= max.z, + "`min` must be less than or equal to `max` componentwise (min = {min}, max = {max})" + ); + + Self { min, max } + } + + // TODO: remove when the assertion in `new` can be done in a `const` context. + #[doc(hidden)] + pub const fn new_unchecked(min: DVec3, max: DVec3) -> Self { + Self { min, max } + } + + /// Returns a new AABB containing a single point `p`. + pub fn new_point(p: DVec3) -> Self { + let p = p.into(); + Self::new(p, p) + } + + pub fn from_bottom_size(bottom: DVec3, size: DVec3) -> Self { + Self::new( + DVec3 { + x: bottom.x - size.x / 2.0, + y: bottom.y, + z: bottom.z - size.z / 2.0, + }, + DVec3 { + x: bottom.x + size.x / 2.0, + y: bottom.y + size.y, + z: bottom.z + size.z / 2.0, + }, + ) + } + + pub const fn min(self) -> DVec3 { + self.min + } + + pub const fn max(self) -> DVec3 { + self.max + } + + pub fn union(self, other: Self) -> Self { + Self::new(self.min.min(other.min), self.max.max(other.max)) + } + + pub fn intersects(self, other: Self) -> bool { + self.max.x >= other.min.x + && other.max.x >= self.min.x + && self.max.y >= other.min.y + && other.max.y >= self.min.y + && self.max.z >= other.min.z + && other.max.z >= self.min.z + } + + /// Does this bounding box contain the given point? + pub fn contains_point(self, p: DVec3) -> bool { + self.min.x <= p.x + && self.min.y <= p.y + && self.min.z <= p.z + && self.max.x >= p.x + && self.max.y >= p.y + && self.max.z >= p.z + } + + /// Returns the closest point in the AABB to the given point. + pub fn projected_point(self, p: DVec3) -> DVec3 { + p.clamp(self.min, self.max) + } + + /// Returns the smallest distance from the AABB to the point. + pub fn distance_to_point(self, p: DVec3) -> f64 { + self.projected_point(p).distance(p) + } + + /// Calculates the intersection between this AABB and a ray + /// defined by its `origin` point and `direction` vector. + /// + /// If an intersection occurs, `Some([near, far])` is returned. `near` and + /// `far` are the values of `t` in the equation `origin + t * direction = + /// point` where `point` is the nearest or furthest intersection point to + /// the `origin`. If no intersection occurs, then `None` is returned. + /// + /// In other words, if `direction` is normalized, then `near` and `far` are + /// the distances to the nearest and furthest intersection points. + pub fn ray_intersection(self, origin: DVec3, direction: DVec3) -> Option<[f64; 2]> { + let mut near: f64 = 0.0; + let mut far = f64::INFINITY; + + for i in 0..3 { + // Rust's definition of `min` and `max` properly handle the NaNs these + // computations may produce. + let t0 = (self.min[i] - origin[i]) / direction[i]; + let t1 = (self.max[i] - origin[i]) / direction[i]; + + near = near.max(t0.min(t1)); + far = far.min(t0.max(t1)); + } + + if near <= far { + Some([near, far]) + } else { + None + } + } +} + +impl Add for Aabb { + type Output = Aabb; + + fn add(self, rhs: DVec3) -> Self::Output { + Self::new(self.min + rhs, self.max + rhs) + } +} + +impl Add for DVec3 { + type Output = Aabb; + + fn add(self, rhs: Aabb) -> Self::Output { + rhs + self + } +} + +impl Sub for Aabb { + type Output = Aabb; + + fn sub(self, rhs: DVec3) -> Self::Output { + Self::new(self.min - rhs, self.max - rhs) + } +} + +impl Sub for DVec3 { + type Output = Aabb; + + fn sub(self, rhs: Aabb) -> Self::Output { + rhs - self + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ray_intersect_edge_cases() { + let bb = Aabb::new([0.0, 0.0, 0.0].into(), [1.0, 1.0, 1.0].into()); + + let ros = [ + // On a corner + DVec3::new(0.0, 0.0, 0.0), + // Outside + DVec3::new(-0.5, 0.5, -0.5), + // In the center + DVec3::new(0.5, 0.5, 0.5), + // On an edge + DVec3::new(0.0, 0.5, 0.0), + // On a face + DVec3::new(0.0, 0.5, 0.5), + // Outside slabs + DVec3::new(-2.0, -2.0, -2.0), + ]; + + let rds = [ + DVec3::new(1.0, 0.0, 0.0), + DVec3::new(-1.0, 0.0, 0.0), + DVec3::new(0.0, 1.0, 0.0), + DVec3::new(0.0, -1.0, 0.0), + DVec3::new(0.0, 0.0, 1.0), + DVec3::new(0.0, 0.0, -1.0), + ]; + + assert!(rds.iter().all(|d| d.is_normalized())); + + for ro in ros { + for rd in rds { + if let Some([near, far]) = bb.ray_intersection(ro, rd) { + assert!(near.is_finite()); + assert!(far.is_finite()); + assert!(near <= far); + assert!(near >= 0.0); + assert!(far >= 0.0); + } + } + } + } +} diff --git a/crates/valence_math/src/lib.rs b/crates/valence_math/src/lib.rs new file mode 100644 index 000000000..f7f1344cf --- /dev/null +++ b/crates/valence_math/src/lib.rs @@ -0,0 +1,4 @@ +mod aabb; + +pub use aabb::Aabb; +pub use glam::*; diff --git a/crates/valence_packet/Cargo.toml b/crates/valence_packet/Cargo.toml index f00dc53ac..93c7ffe0c 100644 --- a/crates/valence_packet/Cargo.toml +++ b/crates/valence_packet/Cargo.toml @@ -15,7 +15,7 @@ valence_packet_macros.workspace = true anyhow.workspace = true bitfield-struct.workspace = true byteorder.workspace = true -glam.workspace = true +valence_math.workspace = true uuid = { workspace = true, features = ["serde"] } bytes.workspace = true tracing.workspace = true diff --git a/crates/valence_packet/src/packets/play.rs b/crates/valence_packet/src/packets/play.rs index 50bd28844..7d83b50d8 100644 --- a/crates/valence_packet/src/packets/play.rs +++ b/crates/valence_packet/src/packets/play.rs @@ -1,6 +1,5 @@ use bitfield_struct::bitfield; use byteorder::WriteBytesExt; -use glam::{DVec3, IVec3, Vec3}; use valence_core::block_pos::BlockPos; use valence_core::chunk_pos::ChunkPos; use valence_core::difficulty::Difficulty; @@ -11,6 +10,7 @@ use valence_core::item::ItemStack; use valence_core::protocol::byte_angle::ByteAngle; use valence_core::protocol::global_pos::GlobalPos; use valence_core::protocol::var_long::VarLong; +use valence_math::{DVec3, IVec3, Vec3}; use valence_nbt::Compound; use super::*; diff --git a/crates/valence_packet/src/packets/play/particle_s2c.rs b/crates/valence_packet/src/packets/play/particle_s2c.rs index 79db86674..ce73c4576 100644 --- a/crates/valence_packet/src/packets/play/particle_s2c.rs +++ b/crates/valence_packet/src/packets/play/particle_s2c.rs @@ -1,4 +1,4 @@ -use glam::Vec3; +use valence_math::Vec3; use super::*; diff --git a/crates/valence_scoreboard/src/lib.rs b/crates/valence_scoreboard/src/lib.rs index f5780588c..635044083 100644 --- a/crates/valence_scoreboard/src/lib.rs +++ b/crates/valence_scoreboard/src/lib.rs @@ -102,7 +102,10 @@ fn create_or_update_objectives( }; let Ok(mut layer) = layers.get_mut(entity_layer.0) else { - warn!("No layer found for entity layer ID {:?}, can't update scoreboard objective", entity_layer); + warn!( + "No layer found for entity layer ID {:?}, can't update scoreboard objective", + entity_layer + ); continue; }; @@ -128,7 +131,10 @@ fn display_objectives( }; let Ok(mut layer) = layers.get_mut(entity_layer.0) else { - warn!("No layer found for entity layer ID {:?}, can't update scoreboard display", entity_layer); + warn!( + "No layer found for entity layer ID {:?}, can't update scoreboard display", + entity_layer + ); continue; }; @@ -144,7 +150,10 @@ fn remove_despawned_objectives( for (entity, objective, entity_layer) in objectives.iter() { commands.entity(entity).despawn(); let Ok(mut layer) = layers.get_mut(entity_layer.0) else { - warn!("No layer found for entity layer ID {:?}, can't remove scoreboard objective", entity_layer); + warn!( + "No layer found for entity layer ID {:?}, can't remove scoreboard objective", + entity_layer + ); continue; }; @@ -252,7 +261,10 @@ fn update_scores( ) { for (objective, scores, mut old_scores, entity_layer) in objectives.iter_mut() { let Ok(mut layer) = layers.get_mut(entity_layer.0) else { - warn!("No layer found for entity layer ID {:?}, can't update scores", entity_layer); + warn!( + "No layer found for entity layer ID {:?}, can't update scores", + entity_layer + ); continue; }; diff --git a/crates/valence_world_border/Cargo.toml b/crates/valence_world_border/Cargo.toml index 8a3ce4782..c9ca96c76 100644 --- a/crates/valence_world_border/Cargo.toml +++ b/crates/valence_world_border/Cargo.toml @@ -6,7 +6,7 @@ edition.workspace = true [dependencies] bevy_app.workspace = true bevy_ecs.workspace = true -glam.workspace = true +valence_math.workspace = true valence_client.workspace = true valence_core.workspace = true valence_entity.workspace = true diff --git a/src/lib.rs b/src/lib.rs index 12560ac1e..7f92cbc38 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,9 +49,9 @@ pub use valence_weather as weather; #[cfg(feature = "world_border")] pub use valence_world_border as world_border; pub use { - bevy_app as app, bevy_ecs as ecs, glam, valence_biome as biome, valence_block as block, + bevy_app as app, bevy_ecs as ecs, valence_biome as biome, valence_block as block, valence_client as client, valence_dimension as dimension, valence_entity as entity, - valence_layer as layer, valence_nbt as nbt, valence_packet as packet, + valence_layer as layer, valence_math as math, valence_nbt as nbt, valence_packet as packet, valence_registry as registry, }; diff --git a/tools/playground/Cargo.toml b/tools/playground/Cargo.toml index 656de011a..d1cd5ce9f 100644 --- a/tools/playground/Cargo.toml +++ b/tools/playground/Cargo.toml @@ -6,7 +6,7 @@ edition.workspace = true [dependencies] anyhow.workspace = true clap.workspace = true -glam.workspace = true +valence_math.workspace = true tracing-subscriber.workspace = true tracing.workspace = true valence_core.workspace = true From 758341237ba1a4a6546c7b5abbada6d67764ee77 Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 6 Aug 2023 02:21:20 -0700 Subject: [PATCH 02/17] valence_ident --- Cargo.toml | 3 + crates/valence_ident/Cargo.toml | 12 +++ .../src/ident.rs => valence_ident/src/lib.rs} | 75 ++++++------------- crates/valence_ident_macros/Cargo.toml | 15 ++++ crates/valence_ident_macros/src/lib.rs | 43 +++++++++++ crates/valence_nbt/Cargo.toml | 1 + crates/valence_nbt/src/value.rs | 41 +++++----- 7 files changed, 120 insertions(+), 70 deletions(-) create mode 100644 crates/valence_ident/Cargo.toml rename crates/{valence_core/src/ident.rs => valence_ident/src/lib.rs} (90%) create mode 100644 crates/valence_ident_macros/Cargo.toml create mode 100644 crates/valence_ident_macros/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 887675051..b36948d03 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,6 +63,7 @@ valence_registry.workspace = true valence_scoreboard = { workspace = true, optional = true } valence_weather = { workspace = true, optional = true } valence_world_border = { workspace = true, optional = true } +valence_ident.workspace = true [dev-dependencies] anyhow.workspace = true @@ -191,5 +192,7 @@ valence_boss_bar.path = "crates/valence_boss_bar" valence_packet.path = "crates/valence_packet" valence_weather.path = "crates/valence_weather" valence_math.path = "crates/valence_math" +valence_ident.path = "crates/valence_ident" +valence_ident_macros.path = "crates/valence_ident_macros" valence.path = "." zip = "0.6.3" diff --git a/crates/valence_ident/Cargo.toml b/crates/valence_ident/Cargo.toml new file mode 100644 index 000000000..25d0a866f --- /dev/null +++ b/crates/valence_ident/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "valence_ident" +version.workspace = true +edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +valence_ident_macros.workspace = true diff --git a/crates/valence_core/src/ident.rs b/crates/valence_ident/src/lib.rs similarity index 90% rename from crates/valence_core/src/ident.rs rename to crates/valence_ident/src/lib.rs index a5fac9244..bf27b2124 100644 --- a/crates/valence_core/src/ident.rs +++ b/crates/valence_ident/src/lib.rs @@ -4,45 +4,25 @@ use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::fmt; use std::fmt::Formatter; -use std::io::Write; use std::str::FromStr; use serde::de::Error as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use thiserror::Error; - -use crate::protocol::{Decode, Encode}; - +/// Used internally by the `ident` macro. Not public API. #[doc(hidden)] -pub mod __private { - pub use valence_core_macros::parse_ident_str; -} - -/// A wrapper around a string type `S` which guarantees the wrapped string is a -/// valid resource identifier. -/// -/// A resource identifier is a string divided into a "namespace" part and a -/// "path" part. For instance `minecraft:apple` and `valence:frobnicator` are -/// both valid identifiers. A string must match the regex -/// `^([a-z0-9_.-]+:)?[a-z0-9_.-\/]+$` to be successfully parsed. -/// -/// While parsing, if the namespace part is left off (the part before and -/// including the colon) then "minecraft:" is inserted at the beginning of the -/// string. -#[derive(Copy, Clone, Eq, Ord, Hash)] -pub struct Ident { - string: S, -} +pub use valence_ident_macros::parse_ident_str; /// Creates a new [`Ident`] at compile time from a string literal. A compile /// error is raised if the string is not a valid resource identifier. /// /// The type of the expression returned by this macro is `Ident<&'static str>`. +/// The expression is usable in a `const` context. /// /// # Examples /// /// ``` -/// # use valence_core::{ident, ident::Ident}; +/// # use valence_ident::{ident, Ident}; /// let my_ident: Ident<&'static str> = ident!("apple"); /// /// println!("{my_ident}"); @@ -50,12 +30,26 @@ pub struct Ident { #[macro_export] macro_rules! ident { ($string:literal) => { - $crate::ident::Ident::<&'static str>::new_unchecked( - $crate::ident::__private::parse_ident_str!($string), - ) + $crate::Ident::<&'static str>::new_unchecked($crate::parse_ident_str!($string)) }; } +/// A wrapper around a string type `S` which guarantees the wrapped string is a +/// valid resource identifier. +/// +/// A resource identifier is a string divided into a "namespace" part and a +/// "path" part. For instance `minecraft:apple` and `valence:frobnicator` are +/// both valid identifiers. A string must match the regex +/// `^([a-z0-9_.-]+:)?[a-z0-9_.-\/]+$` to be successfully parsed. +/// +/// While parsing, if the namespace part is left off (the part before and +/// including the colon) then "minecraft:" is inserted at the beginning of the +/// string. +#[derive(Copy, Clone, Eq, Ord, Hash)] +pub struct Ident { + string: S, +} + /// The error type created when an [`Ident`] cannot be parsed from a /// string. Contains the string that failed to parse. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Error)] @@ -69,7 +63,7 @@ impl<'a> Ident> { } impl Ident { - /// Internal API. Do not use. + /// Used internally by the `ident` macro. Not public API. #[doc(hidden)] pub const fn new_unchecked(string: S) -> Self { Self { string } @@ -324,31 +318,6 @@ where } } -impl Encode for Ident { - fn encode(&self, w: impl Write) -> anyhow::Result<()> { - self.as_ref().encode(w) - } -} - -impl<'a, S> Decode<'a> for Ident -where - S: Decode<'a>, - Ident: TryFrom, -{ - fn decode(r: &mut &'a [u8]) -> anyhow::Result { - Ok(Ident::try_from(S::decode(r)?)?) - } -} - -impl From> for valence_nbt::Value -where - S: Into, -{ - fn from(value: Ident) -> Self { - value.into_inner().into() - } -} - impl Serialize for Ident { fn serialize(&self, serializer: S) -> Result where diff --git a/crates/valence_ident_macros/Cargo.toml b/crates/valence_ident_macros/Cargo.toml new file mode 100644 index 000000000..1973e1321 --- /dev/null +++ b/crates/valence_ident_macros/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "valence_ident_macros" +version.workspace = true +edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true + +[lib] +proc-macro = true + +[dependencies] +proc-macro2.workspace = true +quote.workspace = true +syn = { workspace = true, features = ["full"] } \ No newline at end of file diff --git a/crates/valence_ident_macros/src/lib.rs b/crates/valence_ident_macros/src/lib.rs new file mode 100644 index 000000000..8b1fdf53a --- /dev/null +++ b/crates/valence_ident_macros/src/lib.rs @@ -0,0 +1,43 @@ +use proc_macro::TokenStream as StdTokenStream; +use proc_macro2::TokenStream; +use quote::quote; +use syn::{parse2, Error, LitStr, Result}; + +#[proc_macro] +pub fn parse_ident_str(item: StdTokenStream) -> StdTokenStream { + parse_ident_str_inner(item.into()) + .unwrap_or_else(Error::into_compile_error) + .into() +} + +fn parse_ident_str_inner(item: TokenStream) -> Result { + let ident_lit: LitStr = parse2(item)?; + let mut ident = ident_lit.value(); + + match ident.split_once(':') { + Some((namespace, path)) if check_namespace(namespace) && check_path(path) => {} + None if check_path(&ident) => { + ident = format!("minecraft:{ident}"); + } + _ => { + return Err(syn::Error::new( + ident_lit.span(), + "string cannot be parsed as a resource identifier", + )); + } + } + + Ok(quote!(#ident)) +} + +fn check_namespace(s: &str) -> bool { + !s.is_empty() + && s.chars() + .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '.' | '-')) +} + +fn check_path(s: &str) -> bool { + !s.is_empty() + && s.chars() + .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '.' | '-' | '/')) +} diff --git a/crates/valence_nbt/Cargo.toml b/crates/valence_nbt/Cargo.toml index 87b343cfa..dd36b6b05 100644 --- a/crates/valence_nbt/Cargo.toml +++ b/crates/valence_nbt/Cargo.toml @@ -23,6 +23,7 @@ indexmap = { workspace = true, optional = true } serde = { workspace = true, features = ["derive"], optional = true } thiserror = { workspace = true, optional = true } uuid = { workspace = true, optional = true } +valence_ident = { workspace = true, optional = true } [dev-dependencies] pretty_assertions.workspace = true diff --git a/crates/valence_nbt/src/value.rs b/crates/valence_nbt/src/value.rs index da92c2cc4..3a9b79829 100644 --- a/crates/valence_nbt/src/value.rs +++ b/crates/valence_nbt/src/value.rs @@ -1,8 +1,5 @@ use std::borrow::Cow; -#[cfg(feature = "uuid")] -use uuid::Uuid; - use crate::tag::Tag; use crate::Compound; @@ -215,20 +212,6 @@ impl From> for Value { } } -#[cfg(feature = "uuid")] -impl From for Value { - fn from(value: Uuid) -> Self { - let (most, least) = value.as_u64_pair(); - - let first = (most >> 32) as i32; - let second = most as i32; - let third = (least >> 32) as i32; - let fourth = least as i32; - - Value::IntArray(vec![first, second, third, fourth]) - } -} - impl From> for List { fn from(v: Vec) -> Self { List::Byte(v) @@ -320,3 +303,27 @@ impl From for List { } } } + +#[cfg(feature = "uuid")] +impl From for Value { + fn from(value: uuid::Uuid) -> Self { + let (most, least) = value.as_u64_pair(); + + let first = (most >> 32) as i32; + let second = most as i32; + let third = (least >> 32) as i32; + let fourth = least as i32; + + Value::IntArray(vec![first, second, third, fourth]) + } +} + +#[cfg(feature = "valence_ident")] +impl From> for Value +where + S: Into, +{ + fn from(value: valence_ident::Ident) -> Self { + value.into_inner().into() + } +} From c67a13f5f7f0b54caf752d5fd8a0fcf3a5deb2e5 Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 6 Aug 2023 03:06:12 -0700 Subject: [PATCH 03/17] valence_text --- crates/valence_build_utils/src/lib.rs | 2 + crates/valence_text/Cargo.toml | 28 +++ crates/valence_text/build.rs | 49 +++++ .../src/text => valence_text/src}/color.rs | 0 .../text => valence_text/src}/into_text.rs | 2 +- .../src/text.rs => valence_text/src/lib.rs} | 167 +----------------- crates/valence_text/src/tests.rs | 136 ++++++++++++++ crates/valence_text/src/translate.rs | 3 + 8 files changed, 226 insertions(+), 161 deletions(-) create mode 100644 crates/valence_text/Cargo.toml create mode 100644 crates/valence_text/build.rs rename crates/{valence_core/src/text => valence_text/src}/color.rs (100%) rename crates/{valence_core/src/text => valence_text/src}/into_text.rs (99%) rename crates/{valence_core/src/text.rs => valence_text/src/lib.rs} (80%) create mode 100644 crates/valence_text/src/tests.rs create mode 100644 crates/valence_text/src/translate.rs diff --git a/crates/valence_build_utils/src/lib.rs b/crates/valence_build_utils/src/lib.rs index 97c22179b..2b2d6046e 100644 --- a/crates/valence_build_utils/src/lib.rs +++ b/crates/valence_build_utils/src/lib.rs @@ -38,6 +38,8 @@ pub fn write_generated_file(content: TokenStream, out_file: &str) -> anyhow::Res Ok(()) } +/// Parses a [`proc_macro2::Ident`] from a `str`. Rust keywords are prepended +/// with underscores to make them valid identifiers. pub fn ident(s: impl AsRef) -> Ident { let s = s.as_ref().trim(); diff --git a/crates/valence_text/Cargo.toml b/crates/valence_text/Cargo.toml new file mode 100644 index 000000000..4d47059b3 --- /dev/null +++ b/crates/valence_text/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "valence_text" +version.workspace = true +edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true + +[features] +translate = [] + +[dependencies] +anyhow.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +thiserror.workspace = true +uuid = { workspace = true, features = ["serde"] } +valence_ident.workspace = true +valence_nbt.workspace = true + +[build-dependencies] +anyhow.workspace = true +heck.workspace = true +proc-macro2.workspace = true +quote.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +valence_build_utils.workspace = true diff --git a/crates/valence_text/build.rs b/crates/valence_text/build.rs new file mode 100644 index 000000000..66de1f723 --- /dev/null +++ b/crates/valence_text/build.rs @@ -0,0 +1,49 @@ +pub fn main() { + #[cfg(feature = "translate")] + valence_build_utils::write_generated_file(translate::build().unwrap(), "translate.rs").unwrap(); +} + +#[cfg(feature = "translate")] +mod translate { + use heck::ToShoutySnakeCase; + use proc_macro2::TokenStream; + use quote::quote; + use serde::Deserialize; + use valence_build_utils::ident; + + pub fn build() -> anyhow::Result { + let translations = serde_json::from_str::>(include_str!( + "../../extracted/translation_keys.json" + ))?; + + let translation_key_consts = translations + .iter() + .map(|translation| { + let const_id = ident(translation.key.replace('.', "_").to_shouty_snake_case()); + let key = &translation.key; + let english_translation = &translation.english_translation; + let doc = format!("\"{}\"", escape(english_translation)); + + quote! { + #[doc = #doc] + pub const #const_id: &str = #key; + } + }) + .collect::>(); + + Ok(quote! { + #(#translation_key_consts)* + }) + } + + #[derive(Deserialize, Clone, Debug)] + struct Translation { + key: String, + english_translation: String, + } + + /// Escapes characters that have special meaning inside docs. + fn escape(text: &str) -> String { + text.replace('[', "\\[").replace(']', "\\]") + } +} diff --git a/crates/valence_core/src/text/color.rs b/crates/valence_text/src/color.rs similarity index 100% rename from crates/valence_core/src/text/color.rs rename to crates/valence_text/src/color.rs diff --git a/crates/valence_core/src/text/into_text.rs b/crates/valence_text/src/into_text.rs similarity index 99% rename from crates/valence_core/src/text/into_text.rs rename to crates/valence_text/src/into_text.rs index c13b679a7..6efbf6359 100644 --- a/crates/valence_core/src/text/into_text.rs +++ b/crates/valence_text/src/into_text.rs @@ -12,7 +12,7 @@ use super::{ClickEvent, Color, Font, HoverEvent, Text}; /// # Usage /// /// ``` -/// # use valence_core::text::{IntoText, color::NamedColor}; +/// # use valence_text::{IntoText, color::NamedColor}; /// let mut my_text = "".into_text(); /// my_text = my_text.color(NamedColor::Red).bold(); /// my_text = my_text.add_child("CRABBBBB".obfuscated()); diff --git a/crates/valence_core/src/text.rs b/crates/valence_text/src/lib.rs similarity index 80% rename from crates/valence_core/src/text.rs rename to crates/valence_text/src/lib.rs index 5bb024c2e..520cfc31a 100644 --- a/crates/valence_core/src/text.rs +++ b/crates/valence_text/src/lib.rs @@ -1,22 +1,22 @@ //! Formatted text. use std::borrow::Cow; -use std::io::Write; use std::ops::{Deref, DerefMut}; use std::str::FromStr; use std::{fmt, ops}; -use anyhow::Context; use serde::de::Visitor; use serde::{de, Deserialize, Deserializer, Serialize}; use uuid::Uuid; +use valence_ident::Ident; use valence_nbt::Value; -use crate::ident::Ident; -use crate::protocol::{Decode, Encode}; - pub mod color; mod into_text; +#[cfg(all(test, feature = "translate"))] +mod tests; +#[cfg(feature = "translate")] +pub mod translate; pub use color::Color; pub use into_text::IntoText; @@ -34,7 +34,7 @@ pub use into_text::IntoText; /// /// With [`IntoText`] in scope, you can write the following: /// ``` -/// use valence_core::text::{Color, IntoText, Text}; +/// use valence_text::{Color, IntoText, Text}; /// /// let txt = "The text is ".into_text() /// + "Red".color(Color::RED) @@ -218,7 +218,7 @@ pub enum HoverEvent { /// Number of the items in the stack count: Option, /// NBT information about the item (sNBT format) - tag: Cow<'static, str>, // TODO replace with newtype for sNBT? + tag: Cow<'static, str>, }, /// Shows an entity. ShowEntity { @@ -591,20 +591,6 @@ impl Default for TextContent { } } -impl Encode for Text { - fn encode(&self, w: impl Write) -> anyhow::Result<()> { - serde_json::to_string(self)?.encode(w) - } -} - -impl Decode<'_> for Text { - fn decode(r: &mut &[u8]) -> anyhow::Result { - let str = <&str>::decode(r)?; - - Self::from_str(str).context("decoding text JSON") - } -} - impl<'de> Deserialize<'de> for Text { fn deserialize>(deserializer: D) -> Result { struct TextVisitor; @@ -664,142 +650,3 @@ impl<'de> Deserialize<'de> for Text { deserializer.deserialize_any(TextVisitor) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ident, translation_key}; - - #[test] - fn text_round_trip() { - let before = "foo".color(Color::RED).bold() - + ("bar".obfuscated().color(Color::YELLOW) - + "baz".underlined().not_bold().italic().color(Color::BLACK)); - - let json = format!("{before:#}"); - - let after = Text::from_str(&json).unwrap(); - - println!("==== Before ====\n"); - println!("{before:#?}"); - println!("==== After ====\n"); - println!("{after:#?}"); - - assert_eq!(before, after); - assert_eq!(before.to_string(), after.to_string()); - } - - #[test] - fn non_object_data_types() { - let input = r#"["foo", true, false, 1.9E10, 9999]"#; - let txt: Text = serde_json::from_str(input).unwrap(); - - assert_eq!(txt, "foo".into_text() + true + false + 1.9E10 + 9999); - } - - #[test] - fn translate() { - let txt = Text::translate( - translation_key::CHAT_TYPE_ADVANCEMENT_TASK, - ["arg1".into_text(), "arg2".into_text()], - ); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - assert_eq!( - serialized, - r#"{"translate":"chat.type.advancement.task","with":[{"text":"arg1"},{"text":"arg2"}]}"# - ); - assert_eq!(txt, deserialized); - } - - #[test] - fn score() { - let txt = Text::score("foo", "bar", Some(Cow::from("baz"))); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - assert_eq!( - serialized, - r#"{"score":{"name":"foo","objective":"bar","value":"baz"}}"# - ); - assert_eq!(txt, deserialized); - } - - #[test] - fn selector() { - let separator = Text::text("bar").color(Color::RED).bold(); - let txt = Text::selector("foo", Some(separator)); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - assert_eq!( - serialized, - r##"{"selector":"foo","separator":{"text":"bar","color":"red","bold":true}}"## - ); - assert_eq!(txt, deserialized); - } - - #[test] - fn keybind() { - let txt = Text::keybind("foo"); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - assert_eq!(serialized, r#"{"keybind":"foo"}"#); - assert_eq!(txt, deserialized); - } - - #[test] - fn block_nbt() { - let txt = Text::block_nbt("foo", "bar", Some(true), Some("baz".into_text())); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - let expected = r#"{"block":"foo","nbt":"bar","interpret":true,"separator":{"text":"baz"}}"#; - assert_eq!(serialized, expected); - assert_eq!(txt, deserialized); - } - - #[test] - fn entity_nbt() { - let txt = Text::entity_nbt("foo", "bar", Some(true), Some("baz".into_text())); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - let expected = - r#"{"entity":"foo","nbt":"bar","interpret":true,"separator":{"text":"baz"}}"#; - assert_eq!(serialized, expected); - assert_eq!(txt, deserialized); - } - - #[test] - fn storage_nbt() { - let txt = Text::storage_nbt(ident!("foo"), "bar", Some(true), Some("baz".into_text())); - let serialized = txt.to_string(); - let deserialized = Text::from_str(&serialized).unwrap(); - let expected = r#"{"storage":"minecraft:foo","nbt":"bar","interpret":true,"separator":{"text":"baz"}}"#; - assert_eq!(serialized, expected); - assert_eq!(txt, deserialized); - } - - #[test] - fn text_to_legacy_lossy() { - let text = "Heavily formatted green text\n" - .bold() - .italic() - .strikethrough() - .underlined() - .obfuscated() - .color(Color::GREEN) - + "Lightly formatted red text\n" - .not_bold() - .not_strikethrough() - .not_obfuscated() - .color(Color::RED) - + "Not formatted blue text" - .not_italic() - .not_underlined() - .color(Color::BLUE); - - assert_eq!( - text.to_legacy_lossy(), - "§a§k§l§m§n§oHeavily formatted green text\n§r§c§n§oLightly formatted red \ - text\n§r§9Not formatted blue text" - ); - } -} diff --git a/crates/valence_text/src/tests.rs b/crates/valence_text/src/tests.rs new file mode 100644 index 000000000..9a43d4d15 --- /dev/null +++ b/crates/valence_text/src/tests.rs @@ -0,0 +1,136 @@ +use valence_ident::ident; + +use super::*; + +#[test] +fn text_round_trip() { + let before = "foo".color(Color::RED).bold() + + ("bar".obfuscated().color(Color::YELLOW) + + "baz".underlined().not_bold().italic().color(Color::BLACK)); + + let json = format!("{before:#}"); + + let after = Text::from_str(&json).unwrap(); + + println!("==== Before ====\n"); + println!("{before:#?}"); + println!("==== After ====\n"); + println!("{after:#?}"); + + assert_eq!(before, after); + assert_eq!(before.to_string(), after.to_string()); +} + +#[test] +fn non_object_data_types() { + let input = r#"["foo", true, false, 1.9E10, 9999]"#; + let txt: Text = serde_json::from_str(input).unwrap(); + + assert_eq!(txt, "foo".into_text() + true + false + 1.9E10 + 9999); +} + +#[test] +fn translate() { + let txt = Text::translate( + translate::CHAT_TYPE_ADVANCEMENT_TASK, + ["arg1".into_text(), "arg2".into_text()], + ); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + assert_eq!( + serialized, + r#"{"translate":"chat.type.advancement.task","with":[{"text":"arg1"},{"text":"arg2"}]}"# + ); + assert_eq!(txt, deserialized); +} + +#[test] +fn score() { + let txt = Text::score("foo", "bar", Some(Cow::from("baz"))); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + assert_eq!( + serialized, + r#"{"score":{"name":"foo","objective":"bar","value":"baz"}}"# + ); + assert_eq!(txt, deserialized); +} + +#[test] +fn selector() { + let separator = Text::text("bar").color(Color::RED).bold(); + let txt = Text::selector("foo", Some(separator)); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + assert_eq!( + serialized, + r##"{"selector":"foo","separator":{"text":"bar","color":"red","bold":true}}"## + ); + assert_eq!(txt, deserialized); +} + +#[test] +fn keybind() { + let txt = Text::keybind("foo"); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + assert_eq!(serialized, r#"{"keybind":"foo"}"#); + assert_eq!(txt, deserialized); +} + +#[test] +fn block_nbt() { + let txt = Text::block_nbt("foo", "bar", Some(true), Some("baz".into_text())); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + let expected = r#"{"block":"foo","nbt":"bar","interpret":true,"separator":{"text":"baz"}}"#; + assert_eq!(serialized, expected); + assert_eq!(txt, deserialized); +} + +#[test] +fn entity_nbt() { + let txt = Text::entity_nbt("foo", "bar", Some(true), Some("baz".into_text())); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + let expected = r#"{"entity":"foo","nbt":"bar","interpret":true,"separator":{"text":"baz"}}"#; + assert_eq!(serialized, expected); + assert_eq!(txt, deserialized); +} + +#[test] +fn storage_nbt() { + let txt = Text::storage_nbt(ident!("foo"), "bar", Some(true), Some("baz".into_text())); + let serialized = txt.to_string(); + let deserialized = Text::from_str(&serialized).unwrap(); + let expected = + r#"{"storage":"minecraft:foo","nbt":"bar","interpret":true,"separator":{"text":"baz"}}"#; + assert_eq!(serialized, expected); + assert_eq!(txt, deserialized); +} + +#[test] +fn text_to_legacy_lossy() { + let text = "Heavily formatted green text\n" + .bold() + .italic() + .strikethrough() + .underlined() + .obfuscated() + .color(Color::GREEN) + + "Lightly formatted red text\n" + .not_bold() + .not_strikethrough() + .not_obfuscated() + .color(Color::RED) + + "Not formatted blue text" + .not_italic() + .not_underlined() + .color(Color::BLUE); + + assert_eq!( + text.to_legacy_lossy(), + "§a§k§l§m§n§oHeavily formatted green text\n§r§c§n§oLightly formatted red text\n§r§9Not \ + formatted blue text" + ); +} diff --git a/crates/valence_text/src/translate.rs b/crates/valence_text/src/translate.rs new file mode 100644 index 000000000..3e46fc130 --- /dev/null +++ b/crates/valence_text/src/translate.rs @@ -0,0 +1,3 @@ +//! Contains all of Minecraft's vanilla translation keys. + +include!(concat!(env!("OUT_DIR"), "/translate.rs")); \ No newline at end of file From b715078b3ee934c44f412723cf39ab4c538cefd5 Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 6 Aug 2023 06:29:10 -0700 Subject: [PATCH 04/17] valence_generated --- crates/valence_generated/Cargo.toml | 21 + crates/valence_generated/build/block.rs | 953 ++++++++++++++++++ crates/valence_generated/build/item.rs | 303 ++++++ crates/valence_generated/build/main.rs | 15 + crates/valence_generated/build/sound.rs | 124 +++ .../build/translation_key.rs | 43 + crates/valence_generated/src/block.rs | 82 ++ crates/valence_generated/src/lib.rs | 13 + 8 files changed, 1554 insertions(+) create mode 100644 crates/valence_generated/Cargo.toml create mode 100644 crates/valence_generated/build/block.rs create mode 100644 crates/valence_generated/build/item.rs create mode 100644 crates/valence_generated/build/main.rs create mode 100644 crates/valence_generated/build/sound.rs create mode 100644 crates/valence_generated/build/translation_key.rs create mode 100644 crates/valence_generated/src/block.rs create mode 100644 crates/valence_generated/src/lib.rs diff --git a/crates/valence_generated/Cargo.toml b/crates/valence_generated/Cargo.toml new file mode 100644 index 000000000..e9c9183e8 --- /dev/null +++ b/crates/valence_generated/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "valence_generated" +version.workspace = true +edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true +build = "build/main.rs" + +[dependencies] +valence_math.workspace = true +valence_ident.workspace = true + +[build-dependencies] +anyhow.workspace = true +heck.workspace = true +proc-macro2.workspace = true +quote.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +valence_build_utils.workspace = true diff --git a/crates/valence_generated/build/block.rs b/crates/valence_generated/build/block.rs new file mode 100644 index 000000000..9b981b982 --- /dev/null +++ b/crates/valence_generated/build/block.rs @@ -0,0 +1,953 @@ +use std::collections::BTreeSet; + +use heck::{ToPascalCase, ToShoutySnakeCase}; +use proc_macro2::TokenStream; +use quote::{quote, ToTokens}; +use serde::Deserialize; +use valence_build_utils::{ident, rerun_if_changed}; + +#[derive(Deserialize, Clone, Debug)] +struct TopLevel { + blocks: Vec, + shapes: Vec, + block_entity_types: Vec, +} + +#[derive(Deserialize, Clone, Debug)] +struct Block { + id: u16, + item_id: u16, + wall_variant_id: Option, + translation_key: String, + name: String, + properties: Vec, + default_state_id: u16, + states: Vec, +} + +impl Block { + pub fn min_state_id(&self) -> u16 { + self.states.iter().map(|s| s.id).min().unwrap() + } + + pub fn max_state_id(&self) -> u16 { + self.states.iter().map(|s| s.id).max().unwrap() + } +} + +#[derive(Deserialize, Clone, Debug)] +struct BlockEntityKind { + id: u32, + ident: String, + name: String, +} + +#[derive(Deserialize, Clone, Debug)] +struct Property { + name: String, + values: Vec, +} + +#[derive(Deserialize, Clone, Debug)] +struct State { + id: u16, + luminance: u8, + opaque: bool, + replaceable: bool, + collision_shapes: Vec, + block_entity_type: Option, +} + +#[derive(Deserialize, Clone, Debug)] +struct Shape { + min_x: f64, + min_y: f64, + min_z: f64, + max_x: f64, + max_y: f64, + max_z: f64, +} + +pub fn build() -> anyhow::Result { + rerun_if_changed(["../../extracted/blocks.json"]); + + let TopLevel { + blocks, + shapes, + block_entity_types, + } = serde_json::from_str(include_str!("../../../extracted/blocks.json"))?; + + let max_state_id = blocks.iter().map(|b| b.max_state_id()).max().unwrap(); + + let kind_to_translation_key_arms = blocks + .iter() + .map(|b| { + let kind = ident(b.name.replace('.', "_").to_pascal_case()); + let translation_key = &b.translation_key; + quote! { + Self::#kind => #translation_key, + } + }) + .collect::(); + + let state_to_kind_arms = blocks + .iter() + .map(|b| { + let name = ident(b.name.replace('.', "_").to_pascal_case()); + let mut token_stream = TokenStream::new(); + + let min_id = b.min_state_id(); + let max_id = b.max_state_id(); + + if min_id == max_id { + quote!(#min_id).to_tokens(&mut token_stream); + } else { + for id in min_id..max_id { + quote!(#id | ).to_tokens(&mut token_stream); + } + quote!(#max_id).to_tokens(&mut token_stream); + } + quote!(=> BlockKind::#name,).to_tokens(&mut token_stream); + token_stream + }) + .collect::(); + + let state_to_luminance_arms = blocks + .iter() + .flat_map(|b| { + b.states.iter().filter(|s| s.luminance != 0).map(|s| { + let id = s.id; + let luminance = s.luminance; + quote! { + #id => #luminance, + } + }) + }) + .collect::(); + + let state_to_opaque_arms = blocks + .iter() + .flat_map(|b| { + b.states.iter().filter(|s| !s.opaque).map(|s| { + let id = s.id; + quote! { + #id => false, + } + }) + }) + .collect::(); + + let state_to_replaceable_arms = blocks + .iter() + .flat_map(|b| { + b.states.iter().filter(|s| s.replaceable).map(|s| { + let id = s.id; + quote! { + #id => true, + } + }) + }) + .collect::(); + + let shapes = shapes.iter().map(|s| { + let min_x = s.min_x; + let min_y = s.min_y; + let min_z = s.min_z; + let max_x = s.max_x; + let max_y = s.max_y; + let max_z = s.max_z; + quote! { + Aabb::new_unchecked( + DVec3::new(#min_x, #min_y, #min_z), + DVec3::new(#max_x, #max_y, #max_z), + ) + } + }); + + let shape_count = shapes.len(); + + let state_to_collision_shapes_arms = blocks + .iter() + .flat_map(|b| { + b.states.iter().map(|s| { + let id = s.id; + let collision_shapes = &s.collision_shapes; + quote! { + #id => &[#(#collision_shapes),*], + } + }) + }) + .collect::(); + + let get_arms = blocks + .iter() + .filter(|&b| !b.properties.is_empty()) + .map(|b| { + let block_kind_name = ident(b.name.replace('.', "_").to_pascal_case()); + + let arms = b + .properties + .iter() + .map(|p| { + let prop_name = ident(p.name.replace('.', "_").to_pascal_case()); + let min_state_id = b.min_state_id(); + let product: u16 = b + .properties + .iter() + .rev() + .take_while(|&other| p.name != other.name) + .map(|p| p.values.len() as u16) + .product(); + + let values_count = p.values.len() as u16; + + let arms = p.values.iter().enumerate().map(|(i, v)| { + let value_idx = i as u16; + let value_name = ident(v.replace('.', "_").to_pascal_case()); + quote! { + #value_idx => Some(PropValue::#value_name), + } + }).collect::(); + + quote! { + PropName::#prop_name => match (self.0 - #min_state_id) / #product % #values_count { + #arms + _ => unreachable!(), + }, + } + }) + .collect::(); + + quote! { + BlockKind::#block_kind_name => match name { + #arms + _ => None, + }, + } + }) + .collect::(); + + let set_arms = blocks + .iter() + .filter(|&b| !b.properties.is_empty()) + .map(|b| { + let block_kind_name = ident(b.name.replace('.', "_").to_pascal_case()); + + let arms = b + .properties + .iter() + .map(|p| { + let prop_name = ident(p.name.replace('.', "_").to_pascal_case()); + let min_state_id = b.min_state_id(); + let product: u16 = b + .properties + .iter() + .rev() + .take_while(|&other| p.name != other.name) + .map(|p| p.values.len() as u16) + .product(); + + let values_count = p.values.len() as u16; + + let arms = p + .values + .iter() + .enumerate() + .map(|(i, v)| { + let val_idx = i as u16; + let val_name = ident(v.replace('.', "_").to_pascal_case()); + quote! { + PropValue::#val_name => + Self(self.0 - (self.0 - #min_state_id) / #product % #values_count * #product + + #val_idx * #product), + } + }) + .collect::(); + + quote! { + PropName::#prop_name => match val { + #arms + _ => self, + }, + } + }) + .collect::(); + + quote! { + BlockKind::#block_kind_name => match name { + #arms + _ => self, + }, + } + }) + .collect::(); + + let default_block_states = blocks + .iter() + .map(|b| { + let name = ident(b.name.replace('.', "_").to_shouty_snake_case()); + let state = b.default_state_id; + let doc = format!("The default block state for `{}`.", b.name); + quote! { + #[doc = #doc] + pub const #name: BlockState = BlockState(#state); + } + }) + .collect::(); + + let state_to_wall_variant_arms = blocks + .iter() + .filter(|b| b.wall_variant_id.is_some()) + .map(|b| { + let block_name = ident(b.name.replace('.', "_").to_shouty_snake_case()); + let wall_block_name = ident( + blocks[b.wall_variant_id.unwrap() as usize] + .name + .replace('.', "_") + .to_shouty_snake_case(), + ); + quote! { + BlockState::#block_name => Some(BlockState::#wall_block_name), + } + }) + .collect::(); + + let state_to_block_entity_type_arms = blocks + .iter() + .flat_map(|b| { + b.states.iter().filter_map(|s| { + let id = s.id; + let block_entity_type = s.block_entity_type?; + Some(quote! { + #id => Some(#block_entity_type), + }) + }) + }) + .collect::(); + + let kind_to_state_arms = blocks + .iter() + .map(|b| { + let kind = ident(b.name.replace('.', "_").to_pascal_case()); + let state = ident(b.name.replace('.', "_").to_shouty_snake_case()); + quote! { + BlockKind::#kind => BlockState::#state, + } + }) + .collect::(); + + let block_kind_variants = blocks + .iter() + .map(|b| ident(b.name.replace('.', "_").to_pascal_case())) + .collect::>(); + + let block_kind_from_str_arms = blocks + .iter() + .map(|b| { + let name = &b.name; + let name_ident = ident(name.replace('.', "_").to_pascal_case()); + quote! { + #name => Some(BlockKind::#name_ident), + } + }) + .collect::(); + + let block_kind_to_str_arms = blocks + .iter() + .map(|b| { + let name = &b.name; + let name_ident = ident(name.replace('.', "_").to_pascal_case()); + quote! { + BlockKind::#name_ident => #name, + } + }) + .collect::(); + + let block_kind_props_arms = blocks + .iter() + .filter(|&b| !b.properties.is_empty()) + .map(|b| { + let name = ident(b.name.replace('.', "_").to_pascal_case()); + let prop_names = b + .properties + .iter() + .map(|p| ident(p.name.replace('.', "_").to_pascal_case())); + + quote! { + Self::#name => &[#(PropName::#prop_names,)*], + } + }) + .collect::(); + + let block_kind_to_item_kind_arms = blocks + .iter() + .map(|block| { + let name = ident(block.name.replace('.', "_").to_pascal_case()); + let item_id = block.item_id; + + quote! { + BlockKind::#name => #item_id, + } + }) + .collect::(); + + let block_kind_from_item_kind_arms = blocks + .iter() + .filter(|block| block.item_id != 0) + .map(|block| { + let name = ident(block.name.replace('.', "_").to_pascal_case()); + let item_id = block.item_id; + + quote! { + #item_id => Some(BlockKind::#name), + } + }) + .collect::(); + + let block_kind_from_raw_arms = blocks + .iter() + .map(|block| { + let name = ident(block.name.replace('.', "_").to_pascal_case()); + let id = block.id; + + quote! { + #id => Some(BlockKind::#name), + } + }) + .collect::(); + + let block_entity_kind_variants = block_entity_types + .iter() + .map(|block_entity| { + let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); + let doc = format!( + "The block entity type `{}` (ID {}).", + block_entity.name, block_entity.id + ); + quote! { + #[doc = #doc] + #name, + } + }) + .collect::(); + + let block_entity_kind_from_id_arms = block_entity_types + .iter() + .map(|block_entity| { + let id = block_entity.id; + let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); + + quote! { + #id => Some(Self::#name), + } + }) + .collect::(); + + let block_entity_kind_to_id_arms = block_entity_types + .iter() + .map(|block_entity| { + let id = block_entity.id; + let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); + + quote! { + Self::#name => #id, + } + }) + .collect::(); + + let block_entity_kind_from_ident_arms = block_entity_types + .iter() + .map(|block_entity| { + let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); + let ident = &block_entity.ident; + + quote! { + #ident => Some(Self::#name), + } + }) + .collect::(); + + let block_entity_kind_to_ident_arms = block_entity_types + .iter() + .map(|block_entity| { + let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); + let ident = &block_entity.ident; + + quote! { + Self::#name => ident!(#ident), + } + }) + .collect::(); + + let block_kind_count = blocks.len(); + + let prop_names = blocks + .iter() + .flat_map(|b| b.properties.iter().map(|p| p.name.as_str())) + .collect::>(); + + let prop_name_variants = prop_names + .iter() + .map(|&name| ident(name.replace('.', "_").to_pascal_case())) + .collect::>(); + + let prop_name_from_str_arms = prop_names + .iter() + .map(|&name| { + let ident = ident(name.replace('.', "_").to_pascal_case()); + quote! { + #name => Some(PropName::#ident), + } + }) + .collect::(); + + let prop_name_to_str_arms = prop_names + .iter() + .map(|&name| { + let ident = ident(name.replace('.', "_").to_pascal_case()); + quote! { + PropName::#ident => #name, + } + }) + .collect::(); + + let prop_name_count = prop_names.len(); + + let prop_values = blocks + .iter() + .flat_map(|b| b.properties.iter().flat_map(|p| &p.values)) + .map(|s| s.as_str()) + .collect::>(); + + let prop_value_variants = prop_values + .iter() + .map(|val| ident(val.replace('.', "_").to_pascal_case())) + .collect::>(); + + let prop_value_from_str_arms = prop_values + .iter() + .map(|val| { + let ident = ident(val.replace('.', "_").to_pascal_case()); + quote! { + #val => Some(PropValue::#ident), + } + }) + .collect::(); + + let prop_value_to_str_arms = prop_values + .iter() + .map(|val| { + let ident = ident(val.replace('.', "_").to_pascal_case()); + quote! { + PropValue::#ident => #val, + } + }) + .collect::(); + + let prop_value_from_u16_arms = prop_values + .iter() + .filter_map(|v| v.parse::().ok()) + .map(|n| { + let ident = ident(n.to_string()); + quote! { + #n => Some(PropValue::#ident), + } + }) + .collect::(); + + let prop_value_to_u16_arms = prop_values + .iter() + .filter_map(|v| v.parse::().ok()) + .map(|n| { + let ident = ident(n.to_string()); + quote! { + PropValue::#ident => Some(#n), + } + }) + .collect::(); + + let prop_value_count = prop_values.len(); + + Ok(quote! { + use valence_math::{Aabb, DVec3}; + + /// Represents the state of a block. This does not include block entity data such as + /// the text on a sign, the design on a banner, or the content of a spawner. + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] + pub struct BlockState(u16); + + impl BlockState { + /// Returns the default block state for a given block type. + pub const fn from_kind(kind: BlockKind) -> Self { + match kind { + #kind_to_state_arms + } + } + + /// Constructs a block state from a raw block state ID. + /// + /// If the given ID is invalid, `None` is returned. + pub const fn from_raw(id: u16) -> Option { + if id <= #max_state_id { + Some(Self(id)) + } else { + None + } + } + + /// Returns the [`BlockKind`] of this block state. + pub const fn to_kind(self) -> BlockKind { + match self.0 { + #state_to_kind_arms + _ => unreachable!(), + } + } + + /// Converts this block state to its underlying raw block state ID. + /// + /// The original block state can be recovered with [`BlockState::from_raw`]. + pub const fn to_raw(self) -> u16 { + self.0 + } + + /// Returns the maximum block state ID. + pub const fn max_raw() -> u16 { + #max_state_id + } + + /// Returns the wall variant of the block state. + /// + /// If the given block state doesn't have a wall variant, `None` is returned. + pub const fn wall_block_id(self) -> Option { + match self { + #state_to_wall_variant_arms + _ => None + } + } + + /// Gets the value of the property with the given name from this block. + /// + /// If this block does not have the property, then `None` is returned. + pub const fn get(self, name: PropName) -> Option { + match self.to_kind() { + #get_arms + _ => None + } + } + + /// Sets the value of a property on this block, returning the modified block. + /// + /// If this block does not have the given property or the property value is invalid, + /// then the original block is returned unchanged. + #[must_use] + pub const fn set(self, name: PropName, val: PropValue) -> Self { + match self.to_kind() { + #set_arms + _ => self, + } + } + + /// If this block is `air`, `cave_air` or `void_air`. + pub const fn is_air(self) -> bool { + matches!( + self, + BlockState::AIR | BlockState::CAVE_AIR | BlockState::VOID_AIR + ) + } + + // TODO: is_solid + + /// If this block is water or lava. + pub const fn is_liquid(self) -> bool { + matches!(self.to_kind(), BlockKind::Water | BlockKind::Lava) + } + + pub const fn is_opaque(self) -> bool { + match self.0 { + #state_to_opaque_arms + _ => true, + } + } + + pub const fn is_replaceable(self) -> bool { + match self.0 { + #state_to_replaceable_arms + _ => false, + } + } + + const SHAPES: [Aabb; #shape_count] = [ + #(#shapes,)* + ]; + + pub fn collision_shapes(self) -> impl ExactSizeIterator + FusedIterator + Clone { + let shape_idxs: &'static [u16] = match self.0 { + #state_to_collision_shapes_arms + _ => &[], + }; + + shape_idxs.into_iter().map(|idx| Self::SHAPES[*idx as usize]) + } + + pub const fn luminance(self) -> u8 { + match self.0 { + #state_to_luminance_arms + _ => 0, + } + } + + pub const fn block_entity_kind(self) -> Option { + let kind = match self.0 { + #state_to_block_entity_type_arms + _ => None + }; + + match kind { + Some(id) => BlockEntityKind::from_id(id), + None => None, + } + } + + #default_block_states + } + + /// An enumeration of all block kinds. + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + pub enum BlockKind { + #(#block_kind_variants,)* + } + + impl BlockKind { + /// Construct a block kind from its snake_case name. + /// + /// Returns `None` if the name is invalid. + pub fn from_str(name: &str) -> Option { + match name { + #block_kind_from_str_arms + _ => None + } + } + + /// Get the snake_case name of this block kind. + pub const fn to_str(self) -> &'static str { + match self { + #block_kind_to_str_arms + } + } + + /// Returns the default block state for a given block kind. + pub const fn to_state(self) -> BlockState { + BlockState::from_kind(self) + } + + /// Returns a slice of all properties this block kind has. + pub const fn props(self) -> &'static [PropName] { + match self { + #block_kind_props_arms + _ => &[], + } + } + + pub const fn translation_key(self) -> &'static str { + match self { + #kind_to_translation_key_arms + } + } + + /// Converts a block kind to its corresponding item kind. + /// + /// [`ItemKind::Air`] is used to indicate the absence of an item. + pub const fn to_item_kind(self) -> ItemKind { + let id = match self { + #block_kind_to_item_kind_arms + }; + + // TODO: unwrap() is not const yet. + match ItemKind::from_raw(id) { + Some(k) => k, + None => unreachable!(), + } + } + + /// Constructs a block kind from an item kind. + /// + /// If the given item does not have a corresponding block, `None` is returned. + pub const fn from_item_kind(item: ItemKind) -> Option { + // The "default" blocks are ordered before the other variants. + // For instance, `torch` comes before `wall_torch` so this match + // should do the correct thing. + #[allow(unreachable_patterns)] + match item.to_raw() { + #block_kind_from_item_kind_arms + _ => None, + } + } + + /// Constructs a block kind from a raw block kind ID. + /// + /// If the given ID is invalid, `None` is returned. + pub const fn from_raw(id: u16) -> Option { + match id { + #block_kind_from_raw_arms + _ => None, + } + } + + /// Converts this block kind to its underlying raw block state ID. + /// + /// The original block kind can be recovered with [`BlockKind::from_raw`]. + pub const fn to_raw(self) -> u16 { + self as u16 + } + + /// An array of all block kinds. + pub const ALL: [Self; #block_kind_count] = [#(Self::#block_kind_variants,)*]; + } + + /// The default block kind is `air`. + impl Default for BlockKind { + fn default() -> Self { + Self::Air + } + } + + /// Contains all possible block state property names. + /// + /// For example, `waterlogged`, `facing`, and `half` are all property names. + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + pub enum PropName { + #(#prop_name_variants,)* + } + + impl PropName { + /// Construct a property name from its snake_case name. + /// + /// Returns `None` if the given name is not valid. + pub fn from_str(name: &str) -> Option { + // TODO: match on str in const fn. + match name { + #prop_name_from_str_arms + _ => None, + } + } + + /// Get the snake_case name of this property name. + pub const fn to_str(self) -> &'static str { + match self { + #prop_name_to_str_arms + } + } + + /// An array of all property names. + pub const ALL: [Self; #prop_name_count] = [#(Self::#prop_name_variants,)*]; + } + + /// Contains all possible values that a block property might have. + /// + /// For example, `upper`, `true`, and `2` are all property values. + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + pub enum PropValue { + #(#prop_value_variants,)* + } + + impl PropValue { + /// Construct a property value from its snake_case name. + /// + /// Returns `None` if the given name is not valid. + pub fn from_str(name: &str) -> Option { + match name { + #prop_value_from_str_arms + _ => None, + } + } + + /// Get the snake_case name of this property value. + pub const fn to_str(self) -> &'static str { + match self { + #prop_value_to_str_arms + } + } + + /// Converts a `u16` into a numeric property value. + /// Returns `None` if the given number does not have a + /// corresponding property value. + pub const fn from_u16(n: u16) -> Option { + match n { + #prop_value_from_u16_arms + _ => None, + } + } + + /// Converts this property value into a `u16` if it is numeric. + /// Returns `None` otherwise. + pub const fn to_u16(self) -> Option { + match self { + #prop_value_to_u16_arms + _ => None, + } + } + + /// Converts a `bool` to a `True` or `False` property value. + pub const fn from_bool(b: bool) -> Self { + if b { + Self::True + } else { + Self::False + } + } + + /// Converts a `True` or `False` property value to a `bool`. + /// + /// Returns `None` if this property value is not `True` or `False` + pub const fn to_bool(self) -> Option { + match self { + Self::True => Some(true), + Self::False => Some(false), + _ => None, + } + } + + /// An array of all property values. + pub const ALL: [Self; #prop_value_count] = [#(Self::#prop_value_variants,)*]; + } + + impl From for PropValue { + fn from(b: bool) -> Self { + Self::from_bool(b) + } + } + + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + pub enum BlockEntityKind { + #block_entity_kind_variants + } + + impl BlockEntityKind { + pub const fn from_id(num: u32) -> Option { + match num { + #block_entity_kind_from_id_arms + _ => None + } + } + + pub const fn id(self) -> u32 { + match self { + #block_entity_kind_to_id_arms + } + } + + pub fn from_ident(ident: Ident<&str>) -> Option { + match ident.as_str() { + #block_entity_kind_from_ident_arms + _ => None + } + } + + pub fn ident(self) -> Ident<&'static str> { + match self { + #block_entity_kind_to_ident_arms + } + } + } + }) +} diff --git a/crates/valence_generated/build/item.rs b/crates/valence_generated/build/item.rs new file mode 100644 index 000000000..d99feefa1 --- /dev/null +++ b/crates/valence_generated/build/item.rs @@ -0,0 +1,303 @@ +use anyhow::Ok; +use heck::ToPascalCase; +use proc_macro2::TokenStream; +use quote::quote; +use serde::Deserialize; +use valence_build_utils::{ident, rerun_if_changed}; + +#[derive(Deserialize, Clone, Debug)] +struct Item { + id: u16, + name: String, + translation_key: String, + max_stack: u8, + max_durability: u16, + enchantability: u8, + fireproof: bool, + food: Option, +} + +#[derive(Deserialize, Clone, Debug)] +struct FoodComponent { + hunger: u16, + saturation: f32, + always_edible: bool, + meat: bool, + snack: bool, + // TODO: effects +} + +pub fn build() -> anyhow::Result { + rerun_if_changed(["../../extracted/items.json"]); + + let items = serde_json::from_str::>(include_str!("../../../extracted/items.json"))?; + + let item_kind_count = items.len(); + + let item_kind_from_raw_id_arms = items + .iter() + .map(|item| { + let id = &item.id; + let name = ident(item.name.replace('.', "_").to_pascal_case()); + + quote! { + #id => Some(Self::#name), + } + }) + .collect::(); + + let item_kind_to_raw_id_arms = items + .iter() + .map(|item| { + let id = &item.id; + let name = ident(item.name.replace('.', "_").to_pascal_case()); + + quote! { + Self::#name => #id, + } + }) + .collect::(); + + let item_kind_from_str_arms = items + .iter() + .map(|item| { + let str_name = &item.name; + let name = ident(str_name.replace('.', "_").to_pascal_case()); + quote! { + #str_name => Some(Self::#name), + } + }) + .collect::(); + + let item_kind_to_str_arms = items + .iter() + .map(|item| { + let str_name = &item.name; + let name = ident(str_name.replace('.', "_").to_pascal_case()); + quote! { + Self::#name => #str_name, + } + }) + .collect::(); + + let item_kind_to_translation_key_arms = items + .iter() + .map(|item| { + let name = ident(item.name.replace('.', "_").to_pascal_case()); + let translation_key = &item.translation_key; + quote! { + Self::#name => #translation_key, + } + }) + .collect::(); + + let item_kind_variants = items + .iter() + .map(|item| ident(item.name.replace('.', "_").to_pascal_case())) + .collect::>(); + + let item_kind_to_max_stack_arms = items + .iter() + .map(|item| { + let name = ident(item.name.replace('.', "_").to_pascal_case()); + let max_stack = item.max_stack; + + quote! { + Self::#name => #max_stack, + } + }) + .collect::(); + + let item_kind_to_food_component_arms = items + .iter() + .map(|item| match &item.food { + Some(food_component) => { + let name = ident(item.name.replace('.', "_").to_pascal_case()); + let hunger = food_component.hunger; + let saturation = food_component.saturation; + let always_edible = food_component.always_edible; + let meat = food_component.meat; + let snack = food_component.snack; + + quote! { + Self::#name => Some(FoodComponent { + hunger: #hunger, + saturation: #saturation, + always_edible: #always_edible, + meat: #meat, + snack: #snack, + } + ), + } + } + None => quote! {}, + }) + .collect::(); + + let item_kind_to_max_durability_arms = items + .iter() + .filter(|item| item.max_durability != 0) + .map(|item| { + let name = ident(item.name.replace('.', "_").to_pascal_case()); + let max_durability = item.max_durability; + + quote! { + Self::#name => #max_durability, + } + }) + .collect::(); + + let item_kind_to_enchantability_arms = items + .iter() + .filter(|item| item.enchantability != 0) + .map(|item| { + let name = ident(item.name.replace('.', "_").to_pascal_case()); + let ench = item.enchantability; + + quote! { + Self::#name => #ench, + } + }) + .collect::(); + + let item_kind_to_fireproof_arms = items + .iter() + .filter(|item| item.fireproof) + .map(|item| { + let name = ident(item.name.replace('.', "_").to_pascal_case()); + + quote! { + Self::#name => true, + } + }) + .collect::(); + + Ok(quote! { + /// Represents an item from the game + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + #[repr(u16)] + pub enum ItemKind { + #(#item_kind_variants,)* + } + + /// Contains food information about an item. + /// + /// Only food items have a food component. + #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] + pub struct FoodComponent { + pub hunger: u16, + pub saturation: f32, + pub always_edible: bool, + pub meat: bool, + pub snack: bool, + } + + impl ItemKind { + /// Constructs a item kind from a raw item ID. + /// + /// If the given ID is invalid, `None` is returned. + pub const fn from_raw(id: u16) -> Option { + match id { + #item_kind_from_raw_id_arms + _ => None + } + } + + /// Gets the raw item ID from the item kind + pub const fn to_raw(self) -> u16 { + match self { + #item_kind_to_raw_id_arms + } + } + + /// Construct an item kind for its snake_case name. + /// + /// Returns `None` if the name is invalid. + #[allow(clippy::should_implement_trait)] + pub fn from_str(name: &str) -> Option { + match name { + #item_kind_from_str_arms + _ => None + } + } + + /// Gets the snake_case name of this item kind. + pub const fn to_str(self) -> &'static str { + match self { + #item_kind_to_str_arms + } + } + + /// Gets the translation key of this item kind. + pub const fn translation_key(self) -> &'static str { + match self { + #item_kind_to_translation_key_arms + } + } + + /// Returns the maximum stack count. + pub const fn max_stack(self) -> u8 { + match self { + #item_kind_to_max_stack_arms + } + } + + /// Returns a food component which stores hunger, saturation etc. + /// + /// If the item kind can't be eaten, `None` will be returned. + pub const fn food_component(self) -> Option { + match self { + #item_kind_to_food_component_arms + _ => None + } + } + + /// Returns the maximum durability before the item will break. + /// + /// If the item doesn't have durability, `0` is returned. + pub const fn max_durability(self) -> u16 { + match self { + #item_kind_to_max_durability_arms + _ => 0, + } + } + + /// Returns the enchantability of the item kind. + /// + /// If the item doesn't have durability, `0` is returned. + pub const fn enchantability(self) -> u8 { + match self { + #item_kind_to_enchantability_arms + _ => 0, + } + } + + /// Returns if the item can survive in fire/lava. + pub const fn fireproof(self) -> bool { + #[allow(clippy::match_like_matches_macro)] + match self { + #item_kind_to_fireproof_arms + _ => false + } + } + + /* + /// Constructs an item kind from a block kind. + /// + /// [`ItemKind::Air`] is used to indicate the absence of an item. + pub const fn from_block_kind(kind: BlockKind) -> Self { + kind.to_item_kind() + } + + /// Constructs a block kind from an item kind. + /// + /// If the given item kind doesn't have a corresponding block kind, `None` is returned. + pub const fn to_block_kind(self) -> Option { + BlockKind::from_item_kind(self) + }*/ + + /// An array of all item kinds. + pub const ALL: [Self; #item_kind_count] = [#(Self::#item_kind_variants,)*]; + } + }) +} diff --git a/crates/valence_generated/build/main.rs b/crates/valence_generated/build/main.rs new file mode 100644 index 000000000..dd2cbcdc5 --- /dev/null +++ b/crates/valence_generated/build/main.rs @@ -0,0 +1,15 @@ +use valence_build_utils::write_generated_file; + +mod block; +mod item; +mod translation_key; +mod sound; + +pub fn main() -> anyhow::Result<()> { + write_generated_file(block::build()?, "block.rs")?; + write_generated_file(translation_key::build()?, "translation_key.rs")?; + write_generated_file(item::build()?, "item.rs")?; + write_generated_file(sound::build()?, "sound.rs")?; + + Ok(()) +} diff --git a/crates/valence_generated/build/sound.rs b/crates/valence_generated/build/sound.rs new file mode 100644 index 000000000..0ea6c46fb --- /dev/null +++ b/crates/valence_generated/build/sound.rs @@ -0,0 +1,124 @@ +use heck::ToPascalCase; +use proc_macro2::TokenStream; +use quote::quote; +use serde::Deserialize; +use valence_build_utils::{ident, rerun_if_changed}; + +#[derive(Deserialize, Debug)] +pub struct Sound { + id: u16, + name: String, +} + +pub fn build() -> anyhow::Result { + rerun_if_changed(["../../extracted/sounds.json"]); + + let sounds = + serde_json::from_str::>(include_str!("../../../extracted/sounds.json"))?; + + let sound_count = sounds.len(); + + let sound_from_raw_id_arms = sounds + .iter() + .map(|sound| { + let id = &sound.id; + let name = ident(sound.name.replace('.', "_").to_pascal_case()); + + quote! { + #id => Some(Self::#name), + } + }) + .collect::(); + + let sound_to_raw_id_arms = sounds + .iter() + .map(|sound| { + let id = &sound.id; + let name = ident(sound.name.replace('.', "_").to_pascal_case()); + + quote! { + Self::#name => #id, + } + }) + .collect::(); + + let sound_from_ident_arms = sounds + .iter() + .map(|sound| { + // TODO: put the full resource identifier in the extracted JSON. + let path_name = &sound.name; + let ident_name = format!("minecraft:{}", &sound.name); + + let name = ident(path_name.replace('.', "_").to_pascal_case()); + quote! { + #ident_name => Some(Self::#name), + } + }) + .collect::(); + + let sound_to_ident_arms = sounds + .iter() + .map(|sound| { + let str_name = &sound.name; + let name = ident(str_name.replace('.', "_").to_pascal_case()); + quote! { + Self::#name => ident!(#str_name), + } + }) + .collect::(); + + let sound_variants = sounds + .iter() + .map(|sound| ident(sound.name.replace('.', "_").to_pascal_case())) + .collect::>(); + + Ok(quote! { + use valence_ident::{Ident, ident}; + + /// Represents a sound from the game + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + pub enum Sound { + #(#sound_variants,)* + } + + impl Sound { + /// Constructs a sound from a raw item ID. + /// + /// If the given ID is invalid, `None` is returned. + pub const fn from_raw(id: u16) -> Option { + match id { + #sound_from_raw_id_arms + _ => None + } + } + + /// Gets the raw sound ID from the sound + pub const fn to_raw(self) -> u16 { + match self { + #sound_to_raw_id_arms + } + } + + /// Construct a sound from its snake_case name. + /// + /// Returns `None` if the name is invalid. + #[allow(clippy::should_implement_trait)] + pub fn from_ident(id: Ident<&str>) -> Option { + match id.as_str() { + #sound_from_ident_arms + _ => None + } + } + + /// Gets the identifier of this sound. + pub const fn to_ident(self) -> Ident<&'static str> { + match self { + #sound_to_ident_arms + } + } + + /// An array of all sounds. + pub const ALL: [Self; #sound_count] = [#(Self::#sound_variants,)*]; + } + }) +} diff --git a/crates/valence_generated/build/translation_key.rs b/crates/valence_generated/build/translation_key.rs new file mode 100644 index 000000000..90f5967eb --- /dev/null +++ b/crates/valence_generated/build/translation_key.rs @@ -0,0 +1,43 @@ +use heck::ToShoutySnakeCase; +use proc_macro2::TokenStream; +use quote::quote; +use serde::Deserialize; +use valence_build_utils::{ident, rerun_if_changed}; + +pub fn build() -> anyhow::Result { + rerun_if_changed(["../../extracted/translation_keys.json"]); + + let translations = serde_json::from_str::>(include_str!( + "../../../extracted/translation_keys.json" + ))?; + + let translation_key_consts = translations + .iter() + .map(|translation| { + let const_id = ident(translation.key.replace('.', "_").to_shouty_snake_case()); + let key = &translation.key; + let english_translation = &translation.english_translation; + let doc = format!("\"{}\"", escape(english_translation)); + + quote! { + #[doc = #doc] + pub const #const_id: &str = #key; + } + }) + .collect::>(); + + Ok(quote! { + #(#translation_key_consts)* + }) +} + +#[derive(Deserialize, Clone, Debug)] +struct Translation { + key: String, + english_translation: String, +} + +/// Escapes characters that have special meaning inside docs. +fn escape(text: &str) -> String { + text.replace('[', "\\[").replace(']', "\\]") +} diff --git a/crates/valence_generated/src/block.rs b/crates/valence_generated/src/block.rs new file mode 100644 index 000000000..2887cedb7 --- /dev/null +++ b/crates/valence_generated/src/block.rs @@ -0,0 +1,82 @@ +#![allow(clippy::all)] // TODO: block build script creates many warnings. + +use std::fmt; +use std::fmt::Display; +use std::iter::FusedIterator; + +use valence_ident::{ident, Ident}; +use crate::item::ItemKind; + +include!(concat!(env!("OUT_DIR"), "/block.rs")); + +impl fmt::Debug for BlockState { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt_block_state(*self, f) + } +} + +impl Display for BlockState { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt_block_state(*self, f) + } +} + +fn fmt_block_state(bs: BlockState, f: &mut fmt::Formatter) -> fmt::Result { + let kind = bs.to_kind(); + + write!(f, "{}", kind.to_str())?; + + let props = kind.props(); + + if !props.is_empty() { + let mut list = f.debug_list(); + for &p in kind.props() { + struct KeyVal<'a>(&'a str, &'a str); + + impl<'a> fmt::Debug for KeyVal<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}={}", self.0, self.1) + } + } + + list.entry(&KeyVal(p.to_str(), bs.get(p).unwrap().to_str())); + } + list.finish() + } else { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn get_set_consistency() { + for kind in BlockKind::ALL { + let block = kind.to_state(); + + for &prop in kind.props() { + let new_block = block.set(prop, block.get(prop).unwrap()); + assert_eq!(new_block, block); + } + } + } + + #[test] + fn blockstate_to_wall() { + assert_eq!(BlockState::STONE.wall_block_id(), None); + assert_eq!( + BlockState::OAK_SIGN.wall_block_id(), + Some(BlockState::OAK_WALL_SIGN) + ); + assert_eq!( + BlockState::GREEN_BANNER.wall_block_id(), + Some(BlockState::GREEN_WALL_BANNER) + ); + assert_ne!( + BlockState::GREEN_BANNER.wall_block_id(), + Some(BlockState::GREEN_BANNER) + ); + } +} diff --git a/crates/valence_generated/src/lib.rs b/crates/valence_generated/src/lib.rs new file mode 100644 index 000000000..6a3ec680e --- /dev/null +++ b/crates/valence_generated/src/lib.rs @@ -0,0 +1,13 @@ +pub mod block; + +pub mod item { + include!(concat!(env!("OUT_DIR"), "/item.rs")); +} + +pub mod translation_key { + include!(concat!(env!("OUT_DIR"), "/translation_key.rs")); +} + +pub mod sound { + include!(concat!(env!("OUT_DIR"), "/sound.rs")); +} From 5caf9ccafae3315d4216e4c2557a810cfaf6071c Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 6 Aug 2023 21:51:27 -0700 Subject: [PATCH 05/17] valence_protocol --- Cargo.toml | 9 +- crates/valence_advancement/Cargo.toml | 1 - crates/valence_anvil/Cargo.toml | 1 - crates/valence_block/Cargo.toml | 19 - crates/valence_block/README.md | 3 - crates/valence_block/build.rs | 970 ------------------ crates/valence_block/src/lib.rs | 135 --- crates/valence_boss_bar/Cargo.toml | 1 - crates/valence_build_utils/src/lib.rs | 1 + crates/valence_client/Cargo.toml | 1 - crates/valence_core/Cargo.toml | 9 - crates/valence_core/build/item.rs | 301 ------ crates/valence_core/build/main.rs | 21 - crates/valence_core/build/sound.rs | 118 --- crates/valence_core/build/translation_key.rs | 42 - crates/valence_core/src/lib.rs | 31 - crates/valence_core/src/protocol.rs | 157 --- crates/valence_core/src/scratch.rs | 8 - crates/valence_core/src/translation_key.rs | 1 - crates/valence_core/src/util.rs | 22 - crates/valence_core_macros/Cargo.toml | 12 - crates/valence_core_macros/src/ident.rs | 35 - crates/valence_dimension/src/lib.rs | 3 +- crates/valence_entity/Cargo.toml | 2 - .../build/chunk_view.rs} | 6 +- crates/valence_generated/build/main.rs | 6 +- .../build/packet_id.rs} | 13 +- crates/valence_generated/build/sound.rs | 1 - crates/valence_generated/src/block.rs | 1 + crates/valence_generated/src/lib.rs | 9 + crates/valence_inventory/Cargo.toml | 1 - crates/valence_layer/Cargo.toml | 2 - crates/valence_network/Cargo.toml | 6 - crates/valence_packet/README.md | 7 - crates/valence_packet/src/lib.rs | 10 - crates/valence_packet/src/packets.rs | 18 - crates/valence_packet/src/protocol.rs | 220 ---- crates/valence_packet_macros/README.md | 3 - crates/valence_packet_macros/src/lib.rs | 40 - crates/valence_player_list/Cargo.toml | 1 - .../Cargo.toml | 41 +- .../src}/array.rs | 4 +- .../src/block_pos.rs | 6 +- .../src}/byte_angle.rs | 2 +- crates/valence_protocol/src/chunk_pos.rs | 74 ++ .../src/chunk_view.rs} | 75 +- .../src}/decode.rs | 5 +- .../src/difficulty.rs | 2 +- .../src/direction.rs | 2 +- .../src}/encode.rs | 7 +- .../src/game_mode.rs | 2 +- .../src}/global_pos.rs | 5 +- .../src/hand.rs | 2 +- .../src}/impls.rs | 99 +- .../src/item.rs | 49 +- crates/valence_protocol/src/lib.rs | 397 +++++++ crates/valence_protocol/src/packets.rs | 18 + .../src/packets/handshaking.rs | 0 .../src/packets/handshaking/handshake_c2s.rs | 0 .../src/packets/login.rs | 0 .../packets/login/login_compression_s2c.rs | 0 .../src/packets/login/login_disconnect_s2c.rs | 0 .../src/packets/login/login_hello_c2s.rs | 0 .../src/packets/login/login_hello_s2c.rs | 0 .../src/packets/login/login_key_c2s.rs | 0 .../packets/login/login_query_request_s2c.rs | 0 .../packets/login/login_query_response_c2s.rs | 0 .../src/packets/login/login_success_s2c.rs | 0 .../src/packets/play.rs | 20 +- .../src/packets/play/advancement_tab_c2s.rs | 0 .../packets/play/advancement_update_s2c.rs | 0 .../play/block_breaking_progress_s2c.rs | 0 .../packets/play/block_entity_update_s2c.rs | 0 .../src/packets/play/block_event_s2c.rs | 0 .../src/packets/play/block_update_s2c.rs | 0 .../src/packets/play/boat_paddle_state_c2s.rs | 0 .../src/packets/play/book_update_c2s.rs | 0 .../src/packets/play/boss_bar_s2c.rs | 0 .../src/packets/play/bundle_splitter_s2c.rs | 0 .../src/packets/play/button_click_c2s.rs | 0 .../src/packets/play/chat_message_c2s.rs | 0 .../src/packets/play/chat_message_s2c.rs | 0 .../src/packets/play/chat_suggestions_s2c.rs | 0 .../src/packets/play/chunk_biome_data_s2c.rs | 0 .../src/packets/play/chunk_data_s2c.rs | 3 +- .../packets/play/chunk_delta_update_s2c.rs | 0 .../packets/play/chunk_load_distance_s2c.rs | 0 .../play/chunk_render_distance_center_s2c.rs | 0 .../src/packets/play/clear_title_s2c.rs | 0 .../src/packets/play/click_slot_c2s.rs | 0 .../src/packets/play/client_command_c2s.rs | 0 .../src/packets/play/client_settings_c2s.rs | 0 .../src/packets/play/client_status_c2s.rs | 0 .../packets/play/close_handled_screen_c2s.rs | 0 .../src/packets/play/close_screen_s2c.rs | 0 .../src/packets/play/command_execution_c2s.rs | 0 .../packets/play/command_suggestions_s2c.rs | 0 .../src/packets/play/command_tree_s2c.rs | 0 .../src/packets/play/cooldown_update_s2c.rs | 0 .../packets/play/craft_failed_response_s2c.rs | 0 .../src/packets/play/craft_request_c2s.rs | 0 .../play/creative_inventory_action_c2s.rs | 0 .../src/packets/play/custom_payload_c2s.rs | 0 .../src/packets/play/custom_payload_s2c.rs | 0 .../src/packets/play/damage_tilt_s2c.rs | 0 .../src/packets/play/death_message_s2c.rs | 0 .../src/packets/play/difficulty_s2c.rs | 0 .../src/packets/play/disconnect_s2c.rs | 0 .../src/packets/play/end_combat_s2c.rs | 0 .../src/packets/play/enter_combat_s2c.rs | 0 .../src/packets/play/entities_destroy_s2c.rs | 0 .../src/packets/play/entity_animation_s2c.rs | 0 .../src/packets/play/entity_attach_s2c.rs | 0 .../src/packets/play/entity_attributes_s2c.rs | 0 .../src/packets/play/entity_damage_s2c.rs | 0 .../play/entity_equipment_update_s2c.rs | 0 .../packets/play/entity_passengers_set_s2c.rs | 0 .../src/packets/play/entity_position_s2c.rs | 0 .../packets/play/entity_set_head_yaw_s2c.rs | 0 .../src/packets/play/entity_spawn_s2c.rs | 0 .../packets/play/entity_status_effect_s2c.rs | 0 .../src/packets/play/entity_status_s2c.rs | 0 .../packets/play/entity_tracker_update_s2c.rs | 0 .../play/entity_velocity_update_s2c.rs | 0 .../packets/play/experience_bar_update_s2c.rs | 0 .../packets/play/experience_orb_spawn_s2c.rs | 0 .../src/packets/play/explosion_s2c.rs | 0 .../src/packets/play/features_s2c.rs | 0 .../src/packets/play/full_c2s.rs | 0 .../src/packets/play/game_join_s2c.rs | 0 .../src/packets/play/game_message_s2c.rs | 0 .../src/packets/play/game_state_change_s2c.rs | 0 .../src/packets/play/hand_swing_c2s.rs | 0 .../src/packets/play/health_update_s2c.rs | 0 .../src/packets/play/inventory_s2c.rs | 0 .../packets/play/item_pickup_animation_s2c.rs | 0 .../src/packets/play/jigsaw_generating_c2s.rs | 0 .../src/packets/play/keep_alive_c2s.rs | 0 .../src/packets/play/keep_alive_s2c.rs | 0 .../src/packets/play/light_update_s2c.rs | 3 +- .../packets/play/look_and_on_ground_c2s.rs | 0 .../src/packets/play/look_at_s2c.rs | 0 .../src/packets/play/map_update_s2c.rs | 0 .../play/message_acknowledgment_c2s.rs | 0 .../src/packets/play/move_relative_s2c.rs | 0 .../packets/play/nbt_query_response_s2c.rs | 0 .../src/packets/play/on_ground_only_c2s.rs | 0 .../src/packets/play/open_horse_screen_s2c.rs | 0 .../src/packets/play/open_screen_s2c.rs | 0 .../src/packets/play/open_written_book_s2c.rs | 0 .../src/packets/play/overlay_message_s2c.rs | 0 .../src/packets/play/particle_s2c.rs | 19 +- .../packets/play/pick_from_inventory_c2s.rs | 0 .../src/packets/play/play_ping_s2c.rs | 0 .../src/packets/play/play_pong_c2s.rs | 0 .../play/play_sound_from_entity_s2c.rs | 3 +- .../src/packets/play/play_sound_s2c.rs | 3 +- .../src/packets/play/player_abilities_s2c.rs | 0 .../src/packets/play/player_action_c2s.rs | 0 .../play/player_action_response_s2c.rs | 0 .../src/packets/play/player_input_c2s.rs | 0 .../packets/play/player_interact_block_c2s.rs | 0 .../play/player_interact_entity_c2s.rs | 0 .../packets/play/player_interact_item_c2s.rs | 0 .../packets/play/player_list_header_s2c.rs | 0 .../src/packets/play/player_list_s2c.rs | 0 .../packets/play/player_position_look_s2c.rs | 0 .../src/packets/play/player_remove_s2c.rs | 0 .../src/packets/play/player_respawn_s2c.rs | 0 .../src/packets/play/player_session_c2s.rs | 0 .../packets/play/player_spawn_position_s2c.rs | 0 .../src/packets/play/player_spawn_s2c.rs | 0 .../play/position_and_on_ground_c2s.rs | 0 .../play/profileless_chat_message_s2c.rs | 0 .../src/packets/play/query_block_nbt_c2s.rs | 0 .../src/packets/play/query_entity_nbt_c2s.rs | 0 .../src/packets/play/recipe_book_data_c2s.rs | 0 .../play/recipe_category_options_c2s.rs | 0 .../play/remove_entity_status_effect_s2c.rs | 0 .../src/packets/play/remove_message_s2c.rs | 0 .../src/packets/play/rename_item_c2s.rs | 0 .../play/request_command_completions_c2s.rs | 0 .../packets/play/resource_pack_send_s2c.rs | 0 .../packets/play/resource_pack_status_c2s.rs | 0 .../play/rotate_and_move_relative_s2c.rs | 0 .../src/packets/play/rotate_s2c.rs | 0 .../packets/play/scoreboard_display_s2c.rs | 0 .../play/scoreboard_objective_update_s2c.rs | 0 .../play/scoreboard_player_update_s2c.rs | 0 .../screen_handler_property_update_s2c.rs | 0 .../play/screen_handler_slot_update_s2c.rs | 0 .../play/select_advancement_tab_s2c.rs | 0 .../packets/play/select_merchant_trade_c2s.rs | 0 .../src/packets/play/server_metadata_s2c.rs | 0 .../src/packets/play/set_camera_entity_s2c.rs | 0 .../src/packets/play/set_trade_offers_s2c.rs | 0 .../src/packets/play/sign_editor_open_s2c.rs | 0 .../packets/play/simulation_distance_s2c.rs | 0 .../packets/play/spectator_teleport_c2s.rs | 0 .../src/packets/play/statistics_s2c.rs | 0 .../src/packets/play/stop_sound_s2c.rs | 3 +- .../src/packets/play/subtitle_s2c.rs | 0 .../packets/play/synchronize_recipes_s2c.rs | 0 .../src/packets/play/synchronize_tags_s2c.rs | 0 .../src/packets/play/team_s2c.rs | 0 .../src/packets/play/teleport_confirm_c2s.rs | 0 .../src/packets/play/title_fade_s2c.rs | 0 .../src/packets/play/title_s2c.rs | 0 .../src/packets/play/unload_chunk_s2c.rs | 0 .../src/packets/play/unlock_recipes_s2c.rs | 0 .../src/packets/play/update_beacon_c2s.rs | 0 .../packets/play/update_command_block_c2s.rs | 0 .../play/update_command_block_minecart_c2s.rs | 0 .../src/packets/play/update_difficulty_c2s.rs | 0 .../play/update_difficulty_lock_c2s.rs | 0 .../src/packets/play/update_jigsaw_c2s.rs | 0 .../play/update_player_abilities_c2s.rs | 0 .../packets/play/update_selected_slot_c2s.rs | 0 .../packets/play/update_selected_slot_s2c.rs | 0 .../src/packets/play/update_sign_c2s.rs | 0 .../play/update_structure_block_c2s.rs | 0 .../src/packets/play/vehicle_move_c2s.rs | 0 .../src/packets/play/vehicle_move_s2c.rs | 0 .../play/world_border_center_changed_s2c.rs | 0 .../play/world_border_initialize_s2c.rs | 0 .../play/world_border_interpolate_size_s2c.rs | 0 .../play/world_border_size_changed_s2c.rs | 0 ...world_border_warning_blocks_changed_s2c.rs | 0 .../world_border_warning_time_changed_s2c.rs | 0 .../src/packets/play/world_event_s2c.rs | 0 .../src/packets/play/world_time_update_s2c.rs | 0 .../src/packets/status.rs | 0 .../src/packets/status/query_ping_c2s.rs | 0 .../src/packets/status/query_pong_s2c.rs | 0 .../src/packets/status/query_request_c2s.rs | 0 .../src/packets/status/query_response_s2c.rs | 0 .../src/player_textures.rs | 0 .../src/property.rs | 2 +- .../protocol => valence_protocol/src}/raw.rs | 2 +- .../src/sound.rs | 46 +- .../src}/var_int.rs | 2 +- .../src}/var_long.rs | 2 +- .../Cargo.toml | 3 +- .../README.md | 0 .../src/decode.rs | 16 +- .../src/encode.rs | 14 +- .../src/lib.rs | 8 +- .../src/packet.rs | 12 +- crates/valence_registry/Cargo.toml | 1 - crates/valence_scoreboard/Cargo.toml | 1 - crates/valence_text/Cargo.toml | 14 +- crates/valence_text/build.rs | 49 - crates/valence_text/src/lib.rs | 4 +- crates/valence_text/src/tests.rs | 2 +- crates/valence_text/src/translate.rs | 3 - crates/valence_weather/Cargo.toml | 1 - crates/valence_world_border/Cargo.toml | 1 - tools/stresser/Cargo.toml | 3 +- 258 files changed, 740 insertions(+), 2537 deletions(-) delete mode 100644 crates/valence_block/Cargo.toml delete mode 100644 crates/valence_block/README.md delete mode 100644 crates/valence_block/build.rs delete mode 100644 crates/valence_block/src/lib.rs delete mode 100644 crates/valence_core/build/item.rs delete mode 100644 crates/valence_core/build/main.rs delete mode 100644 crates/valence_core/build/sound.rs delete mode 100644 crates/valence_core/build/translation_key.rs delete mode 100644 crates/valence_core/src/protocol.rs delete mode 100644 crates/valence_core/src/scratch.rs delete mode 100644 crates/valence_core/src/translation_key.rs delete mode 100644 crates/valence_core/src/util.rs delete mode 100644 crates/valence_core_macros/Cargo.toml delete mode 100644 crates/valence_core_macros/src/ident.rs rename crates/{valence_core/build/chunk_pos.rs => valence_generated/build/chunk_view.rs} (80%) rename crates/{valence_packet/build.rs => valence_generated/build/packet_id.rs} (74%) delete mode 100644 crates/valence_packet/README.md delete mode 100644 crates/valence_packet/src/lib.rs delete mode 100644 crates/valence_packet/src/packets.rs delete mode 100644 crates/valence_packet/src/protocol.rs delete mode 100644 crates/valence_packet_macros/README.md delete mode 100644 crates/valence_packet_macros/src/lib.rs rename crates/{valence_packet => valence_protocol}/Cargo.toml (51%) rename crates/{valence_core/src/protocol => valence_protocol/src}/array.rs (93%) rename crates/{valence_core => valence_protocol}/src/block_pos.rs (97%) rename crates/{valence_core/src/protocol => valence_protocol/src}/byte_angle.rs (95%) create mode 100644 crates/valence_protocol/src/chunk_pos.rs rename crates/{valence_core/src/chunk_pos.rs => valence_protocol/src/chunk_view.rs} (61%) rename crates/{valence_packet/src/protocol => valence_protocol/src}/decode.rs (97%) rename crates/{valence_core => valence_protocol}/src/difficulty.rs (77%) rename crates/{valence_core => valence_protocol}/src/direction.rs (86%) rename crates/{valence_packet/src/protocol => valence_protocol/src}/encode.rs (98%) rename crates/{valence_core => valence_protocol}/src/game_mode.rs (83%) rename crates/{valence_core/src/protocol => valence_protocol/src}/global_pos.rs (76%) rename crates/{valence_core => valence_protocol}/src/hand.rs (75%) rename crates/{valence_core/src/protocol => valence_protocol/src}/impls.rs (87%) rename crates/{valence_core => valence_protocol}/src/item.rs (69%) create mode 100644 crates/valence_protocol/src/lib.rs create mode 100644 crates/valence_protocol/src/packets.rs rename crates/{valence_packet => valence_protocol}/src/packets/handshaking.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/handshaking/handshake_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_compression_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_disconnect_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_hello_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_hello_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_key_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_query_request_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_query_response_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/login/login_success_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play.rs (96%) rename crates/{valence_packet => valence_protocol}/src/packets/play/advancement_tab_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/advancement_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/block_breaking_progress_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/block_entity_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/block_event_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/block_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/boat_paddle_state_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/book_update_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/boss_bar_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/bundle_splitter_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/button_click_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chat_message_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chat_message_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chat_suggestions_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chunk_biome_data_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chunk_data_s2c.rs (93%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chunk_delta_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chunk_load_distance_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/chunk_render_distance_center_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/clear_title_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/click_slot_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/client_command_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/client_settings_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/client_status_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/close_handled_screen_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/close_screen_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/command_execution_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/command_suggestions_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/command_tree_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/cooldown_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/craft_failed_response_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/craft_request_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/creative_inventory_action_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/custom_payload_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/custom_payload_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/damage_tilt_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/death_message_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/difficulty_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/disconnect_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/end_combat_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/enter_combat_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entities_destroy_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_animation_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_attach_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_attributes_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_damage_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_equipment_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_passengers_set_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_position_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_set_head_yaw_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_spawn_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_status_effect_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_status_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_tracker_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/entity_velocity_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/experience_bar_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/experience_orb_spawn_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/explosion_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/features_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/full_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/game_join_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/game_message_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/game_state_change_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/hand_swing_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/health_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/inventory_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/item_pickup_animation_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/jigsaw_generating_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/keep_alive_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/keep_alive_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/light_update_s2c.rs (89%) rename crates/{valence_packet => valence_protocol}/src/packets/play/look_and_on_ground_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/look_at_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/map_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/message_acknowledgment_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/move_relative_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/nbt_query_response_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/on_ground_only_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/open_horse_screen_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/open_screen_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/open_written_book_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/overlay_message_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/particle_s2c.rs (95%) rename crates/{valence_packet => valence_protocol}/src/packets/play/pick_from_inventory_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/play_ping_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/play_pong_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/play_sound_from_entity_s2c.rs (88%) rename crates/{valence_packet => valence_protocol}/src/packets/play/play_sound_s2c.rs (84%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_abilities_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_action_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_action_response_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_input_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_interact_block_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_interact_entity_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_interact_item_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_list_header_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_list_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_position_look_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_remove_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_respawn_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_session_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_spawn_position_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/player_spawn_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/position_and_on_ground_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/profileless_chat_message_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/query_block_nbt_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/query_entity_nbt_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/recipe_book_data_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/recipe_category_options_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/remove_entity_status_effect_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/remove_message_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/rename_item_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/request_command_completions_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/resource_pack_send_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/resource_pack_status_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/rotate_and_move_relative_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/rotate_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/scoreboard_display_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/scoreboard_objective_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/scoreboard_player_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/screen_handler_property_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/screen_handler_slot_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/select_advancement_tab_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/select_merchant_trade_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/server_metadata_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/set_camera_entity_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/set_trade_offers_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/sign_editor_open_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/simulation_distance_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/spectator_teleport_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/statistics_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/stop_sound_s2c.rs (97%) rename crates/{valence_packet => valence_protocol}/src/packets/play/subtitle_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/synchronize_recipes_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/synchronize_tags_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/team_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/teleport_confirm_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/title_fade_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/title_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/unload_chunk_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/unlock_recipes_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_beacon_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_command_block_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_command_block_minecart_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_difficulty_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_difficulty_lock_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_jigsaw_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_player_abilities_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_selected_slot_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_selected_slot_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_sign_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/update_structure_block_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/vehicle_move_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/vehicle_move_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_border_center_changed_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_border_initialize_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_border_interpolate_size_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_border_size_changed_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_border_warning_blocks_changed_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_border_warning_time_changed_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_event_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/play/world_time_update_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/status.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/status/query_ping_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/status/query_pong_s2c.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/status/query_request_c2s.rs (100%) rename crates/{valence_packet => valence_protocol}/src/packets/status/query_response_s2c.rs (100%) rename crates/{valence_core => valence_protocol}/src/player_textures.rs (100%) rename crates/{valence_core => valence_protocol}/src/property.rs (85%) rename crates/{valence_core/src/protocol => valence_protocol/src}/raw.rs (96%) rename crates/{valence_core => valence_protocol}/src/sound.rs (78%) rename crates/{valence_core/src/protocol => valence_protocol/src}/var_int.rs (99%) rename crates/{valence_core/src/protocol => valence_protocol/src}/var_long.rs (99%) rename crates/{valence_packet_macros => valence_protocol_macros}/Cargo.toml (77%) rename crates/{valence_core_macros => valence_protocol_macros}/README.md (100%) rename crates/{valence_core_macros => valence_protocol_macros}/src/decode.rs (90%) rename crates/{valence_core_macros => valence_protocol_macros}/src/encode.rs (92%) rename crates/{valence_core_macros => valence_protocol_macros}/src/lib.rs (95%) rename crates/{valence_packet_macros => valence_protocol_macros}/src/packet.rs (86%) delete mode 100644 crates/valence_text/build.rs delete mode 100644 crates/valence_text/src/translate.rs diff --git a/Cargo.toml b/Cargo.toml index b36948d03..25976b8ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,6 @@ rand.workspace = true valence_advancement = { workspace = true, optional = true } valence_anvil = { workspace = true, optional = true } valence_biome.workspace = true -valence_block.workspace = true valence_boss_bar = { workspace = true, optional = true } valence_client.workspace = true valence_core.workspace = true @@ -57,12 +56,12 @@ valence_layer.workspace = true valence_math = { workspace = true } valence_nbt.workspace = true valence_network = { workspace = true, optional = true } -valence_packet.workspace = true valence_player_list = { workspace = true, optional = true } valence_registry.workspace = true valence_scoreboard = { workspace = true, optional = true } valence_weather = { workspace = true, optional = true } valence_world_border = { workspace = true, optional = true } +valence_text.workspace = true valence_ident.workspace = true [dev-dependencies] @@ -172,10 +171,8 @@ uuid = "1.3.1" valence_advancement.path = "crates/valence_advancement" valence_anvil.path = "crates/valence_anvil" valence_biome.path = "crates/valence_biome" -valence_block.path = "crates/valence_block" valence_build_utils.path = "crates/valence_build_utils" valence_client.path = "crates/valence_client" -valence_core_macros.path = "crates/valence_core_macros" valence_packet_macros.path = "crates/valence_packet_macros" valence_core.path = "crates/valence_core" valence_dimension.path = "crates/valence_dimension" @@ -189,10 +186,12 @@ valence_registry.path = "crates/valence_registry" valence_scoreboard.path = "crates/valence_scoreboard" valence_world_border.path = "crates/valence_world_border" valence_boss_bar.path = "crates/valence_boss_bar" -valence_packet.path = "crates/valence_packet" valence_weather.path = "crates/valence_weather" valence_math.path = "crates/valence_math" valence_ident.path = "crates/valence_ident" valence_ident_macros.path = "crates/valence_ident_macros" +valence_generated.path = "crates/valence_generated" +valence_text.path = "crates/valence_text" +valence_protocol_macros.path = "crates/valence_protocol_macros" valence.path = "." zip = "0.6.3" diff --git a/crates/valence_advancement/Cargo.toml b/crates/valence_advancement/Cargo.toml index 5a8514e8c..76d0aebd0 100644 --- a/crates/valence_advancement/Cargo.toml +++ b/crates/valence_advancement/Cargo.toml @@ -6,7 +6,6 @@ edition.workspace = true [dependencies] valence_core.workspace = true valence_client.workspace = true -valence_packet.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true bevy_hierarchy.workspace = true diff --git a/crates/valence_anvil/Cargo.toml b/crates/valence_anvil/Cargo.toml index b8db1e3ef..777bb92e7 100644 --- a/crates/valence_anvil/Cargo.toml +++ b/crates/valence_anvil/Cargo.toml @@ -20,7 +20,6 @@ num-integer.workspace = true thiserror.workspace = true tracing.workspace = true valence_biome.workspace = true -valence_block.workspace = true valence_client.workspace = true valence_core.workspace = true valence_entity.workspace = true diff --git a/crates/valence_block/Cargo.toml b/crates/valence_block/Cargo.toml deleted file mode 100644 index 971b4f3ff..000000000 --- a/crates/valence_block/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "valence_block" -version.workspace = true -edition.workspace = true - -[dependencies] -anyhow.workspace = true -valence_core.workspace = true -valence_math.workspace = true - -[build-dependencies] -anyhow.workspace = true -heck.workspace = true -proc-macro2.workspace = true -quote.workspace = true -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true -valence_build_utils.workspace = true -valence_core.workspace = true diff --git a/crates/valence_block/README.md b/crates/valence_block/README.md deleted file mode 100644 index e4db85b6b..000000000 --- a/crates/valence_block/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# valence_block - -Everything related to Minecraft blocks. Primarily concerned with the [`BlockState`] type. diff --git a/crates/valence_block/build.rs b/crates/valence_block/build.rs deleted file mode 100644 index 3e8a6eed0..000000000 --- a/crates/valence_block/build.rs +++ /dev/null @@ -1,970 +0,0 @@ -use std::collections::BTreeSet; - -use heck::{ToPascalCase, ToShoutySnakeCase}; -use proc_macro2::TokenStream; -use quote::{quote, ToTokens}; -use serde::Deserialize; -use valence_build_utils::{ident, rerun_if_changed, write_generated_file}; - -#[derive(Deserialize, Clone, Debug)] -struct TopLevel { - blocks: Vec, - shapes: Vec, - block_entity_types: Vec, -} - -#[derive(Deserialize, Clone, Debug)] -struct Block { - id: u16, - item_id: u16, - wall_variant_id: Option, - translation_key: String, - name: String, - properties: Vec, - default_state_id: u16, - states: Vec, -} - -impl Block { - pub fn min_state_id(&self) -> u16 { - self.states.iter().map(|s| s.id).min().unwrap() - } - - pub fn max_state_id(&self) -> u16 { - self.states.iter().map(|s| s.id).max().unwrap() - } -} - -#[derive(Deserialize, Clone, Debug)] -struct BlockEntityKind { - id: u32, - ident: String, - name: String, -} - -#[derive(Deserialize, Clone, Debug)] -struct Property { - name: String, - values: Vec, -} - -#[derive(Deserialize, Clone, Debug)] -struct State { - id: u16, - luminance: u8, - opaque: bool, - replaceable: bool, - collision_shapes: Vec, - block_entity_type: Option, -} - -#[derive(Deserialize, Clone, Debug)] -struct Shape { - min_x: f64, - min_y: f64, - min_z: f64, - max_x: f64, - max_y: f64, - max_z: f64, -} - -pub fn main() -> anyhow::Result<()> { - rerun_if_changed(["../../extracted/blocks.json"]); - - write_generated_file(build()?, "block.rs") -} - -fn build() -> anyhow::Result { - let TopLevel { - blocks, - shapes, - block_entity_types, - } = serde_json::from_str(include_str!("../../extracted/blocks.json"))?; - - let max_state_id = blocks.iter().map(|b| b.max_state_id()).max().unwrap(); - - let kind_to_translation_key_arms = blocks - .iter() - .map(|b| { - let kind = ident(b.name.replace('.', "_").to_pascal_case()); - let translation_key = &b.translation_key; - quote! { - Self::#kind => #translation_key, - } - }) - .collect::(); - - let state_to_kind_arms = blocks - .iter() - .map(|b| { - let name = ident(b.name.replace('.', "_").to_pascal_case()); - let mut token_stream = TokenStream::new(); - - let min_id = b.min_state_id(); - let max_id = b.max_state_id(); - - if min_id == max_id { - quote!(#min_id).to_tokens(&mut token_stream); - } else { - for id in min_id..max_id { - quote!(#id | ).to_tokens(&mut token_stream); - } - quote!(#max_id).to_tokens(&mut token_stream); - } - quote!(=> BlockKind::#name,).to_tokens(&mut token_stream); - token_stream - }) - .collect::(); - - let state_to_luminance_arms = blocks - .iter() - .flat_map(|b| { - b.states.iter().filter(|s| s.luminance != 0).map(|s| { - let id = s.id; - let luminance = s.luminance; - quote! { - #id => #luminance, - } - }) - }) - .collect::(); - - let state_to_opaque_arms = blocks - .iter() - .flat_map(|b| { - b.states.iter().filter(|s| !s.opaque).map(|s| { - let id = s.id; - quote! { - #id => false, - } - }) - }) - .collect::(); - - let state_to_replaceable_arms = blocks - .iter() - .flat_map(|b| { - b.states.iter().filter(|s| s.replaceable).map(|s| { - let id = s.id; - quote! { - #id => true, - } - }) - }) - .collect::(); - - let shapes = shapes.iter().map(|s| { - let min_x = s.min_x; - let min_y = s.min_y; - let min_z = s.min_z; - let max_x = s.max_x; - let max_y = s.max_y; - let max_z = s.max_z; - quote! { - Aabb::new_unchecked( - DVec3::new(#min_x, #min_y, #min_z), - DVec3::new(#max_x, #max_y, #max_z), - ) - } - }); - - let shape_count = shapes.len(); - - let state_to_collision_shapes_arms = blocks - .iter() - .flat_map(|b| { - b.states.iter().map(|s| { - let id = s.id; - let collision_shapes = &s.collision_shapes; - quote! { - #id => &[#(#collision_shapes),*], - } - }) - }) - .collect::(); - - let get_arms = blocks - .iter() - .filter(|&b| !b.properties.is_empty()) - .map(|b| { - let block_kind_name = ident(b.name.replace('.', "_").to_pascal_case()); - - let arms = b - .properties - .iter() - .map(|p| { - let prop_name = ident(p.name.replace('.', "_").to_pascal_case()); - let min_state_id = b.min_state_id(); - let product: u16 = b - .properties - .iter() - .rev() - .take_while(|&other| p.name != other.name) - .map(|p| p.values.len() as u16) - .product(); - - let values_count = p.values.len() as u16; - - let arms = p.values.iter().enumerate().map(|(i, v)| { - let value_idx = i as u16; - let value_name = ident(v.replace('.', "_").to_pascal_case()); - quote! { - #value_idx => Some(PropValue::#value_name), - } - }).collect::(); - - quote! { - PropName::#prop_name => match (self.0 - #min_state_id) / #product % #values_count { - #arms - _ => unreachable!(), - }, - } - }) - .collect::(); - - quote! { - BlockKind::#block_kind_name => match name { - #arms - _ => None, - }, - } - }) - .collect::(); - - let set_arms = blocks - .iter() - .filter(|&b| !b.properties.is_empty()) - .map(|b| { - let block_kind_name = ident(b.name.replace('.', "_").to_pascal_case()); - - let arms = b - .properties - .iter() - .map(|p| { - let prop_name = ident(p.name.replace('.', "_").to_pascal_case()); - let min_state_id = b.min_state_id(); - let product: u16 = b - .properties - .iter() - .rev() - .take_while(|&other| p.name != other.name) - .map(|p| p.values.len() as u16) - .product(); - - let values_count = p.values.len() as u16; - - let arms = p - .values - .iter() - .enumerate() - .map(|(i, v)| { - let val_idx = i as u16; - let val_name = ident(v.replace('.', "_").to_pascal_case()); - quote! { - PropValue::#val_name => - Self(self.0 - (self.0 - #min_state_id) / #product % #values_count * #product - + #val_idx * #product), - } - }) - .collect::(); - - quote! { - PropName::#prop_name => match val { - #arms - _ => self, - }, - } - }) - .collect::(); - - quote! { - BlockKind::#block_kind_name => match name { - #arms - _ => self, - }, - } - }) - .collect::(); - - let default_block_states = blocks - .iter() - .map(|b| { - let name = ident(b.name.replace('.', "_").to_shouty_snake_case()); - let state = b.default_state_id; - let doc = format!("The default block state for `{}`.", b.name); - quote! { - #[doc = #doc] - pub const #name: BlockState = BlockState(#state); - } - }) - .collect::(); - - let state_to_wall_variant_arms = blocks - .iter() - .filter(|b| b.wall_variant_id.is_some()) - .map(|b| { - let block_name = ident(b.name.replace('.', "_").to_shouty_snake_case()); - let wall_block_name = ident( - blocks[b.wall_variant_id.unwrap() as usize] - .name - .replace('.', "_") - .to_shouty_snake_case(), - ); - quote! { - BlockState::#block_name => Some(BlockState::#wall_block_name), - } - }) - .collect::(); - - let state_to_block_entity_type_arms = blocks - .iter() - .flat_map(|b| { - b.states.iter().filter_map(|s| { - let id = s.id; - let block_entity_type = s.block_entity_type?; - Some(quote! { - #id => Some(#block_entity_type), - }) - }) - }) - .collect::(); - - let kind_to_state_arms = blocks - .iter() - .map(|b| { - let kind = ident(b.name.replace('.', "_").to_pascal_case()); - let state = ident(b.name.replace('.', "_").to_shouty_snake_case()); - quote! { - BlockKind::#kind => BlockState::#state, - } - }) - .collect::(); - - let block_kind_variants = blocks - .iter() - .map(|b| ident(b.name.replace('.', "_").to_pascal_case())) - .collect::>(); - - let block_kind_from_str_arms = blocks - .iter() - .map(|b| { - let name = &b.name; - let name_ident = ident(name.replace('.', "_").to_pascal_case()); - quote! { - #name => Some(BlockKind::#name_ident), - } - }) - .collect::(); - - let block_kind_to_str_arms = blocks - .iter() - .map(|b| { - let name = &b.name; - let name_ident = ident(name.replace('.', "_").to_pascal_case()); - quote! { - BlockKind::#name_ident => #name, - } - }) - .collect::(); - - let block_kind_props_arms = blocks - .iter() - .filter(|&b| !b.properties.is_empty()) - .map(|b| { - let name = ident(b.name.replace('.', "_").to_pascal_case()); - let prop_names = b - .properties - .iter() - .map(|p| ident(p.name.replace('.', "_").to_pascal_case())); - - quote! { - Self::#name => &[#(PropName::#prop_names,)*], - } - }) - .collect::(); - - let block_kind_to_item_kind_arms = blocks - .iter() - .map(|block| { - let name = ident(block.name.replace('.', "_").to_pascal_case()); - let item_id = block.item_id; - - quote! { - BlockKind::#name => #item_id, - } - }) - .collect::(); - - let block_kind_from_item_kind_arms = blocks - .iter() - .filter(|block| block.item_id != 0) - .map(|block| { - let name = ident(block.name.replace('.', "_").to_pascal_case()); - let item_id = block.item_id; - - quote! { - #item_id => Some(BlockKind::#name), - } - }) - .collect::(); - - let block_kind_from_raw_arms = blocks - .iter() - .map(|block| { - let name = ident(block.name.replace('.', "_").to_pascal_case()); - let id = block.id; - - quote! { - #id => Some(BlockKind::#name), - } - }) - .collect::(); - - let block_entity_kind_variants = block_entity_types - .iter() - .map(|block_entity| { - let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); - let doc = format!( - "The block entity type `{}` (ID {}).", - block_entity.name, block_entity.id - ); - quote! { - #[doc = #doc] - #name, - } - }) - .collect::(); - - let block_entity_kind_from_id_arms = block_entity_types - .iter() - .map(|block_entity| { - let id = block_entity.id; - let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); - - quote! { - #id => Some(Self::#name), - } - }) - .collect::(); - - let block_entity_kind_to_id_arms = block_entity_types - .iter() - .map(|block_entity| { - let id = block_entity.id; - let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); - - quote! { - Self::#name => #id, - } - }) - .collect::(); - - let block_entity_kind_from_ident_arms = block_entity_types - .iter() - .map(|block_entity| { - let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); - let ident = &block_entity.ident; - - quote! { - #ident => Some(Self::#name), - } - }) - .collect::(); - - let block_entity_kind_to_ident_arms = block_entity_types - .iter() - .map(|block_entity| { - let name = ident(block_entity.name.replace('.', "_").to_pascal_case()); - let ident = &block_entity.ident; - - quote! { - Self::#name => ident!(#ident), - } - }) - .collect::(); - - let block_kind_count = blocks.len(); - - let prop_names = blocks - .iter() - .flat_map(|b| b.properties.iter().map(|p| p.name.as_str())) - .collect::>(); - - let prop_name_variants = prop_names - .iter() - .map(|&name| ident(name.replace('.', "_").to_pascal_case())) - .collect::>(); - - let prop_name_from_str_arms = prop_names - .iter() - .map(|&name| { - let ident = ident(name.replace('.', "_").to_pascal_case()); - quote! { - #name => Some(PropName::#ident), - } - }) - .collect::(); - - let prop_name_to_str_arms = prop_names - .iter() - .map(|&name| { - let ident = ident(name.replace('.', "_").to_pascal_case()); - quote! { - PropName::#ident => #name, - } - }) - .collect::(); - - let prop_name_count = prop_names.len(); - - let prop_values = blocks - .iter() - .flat_map(|b| b.properties.iter().flat_map(|p| &p.values)) - .map(|s| s.as_str()) - .collect::>(); - - let prop_value_variants = prop_values - .iter() - .map(|val| ident(val.replace('.', "_").to_pascal_case())) - .collect::>(); - - let prop_value_from_str_arms = prop_values - .iter() - .map(|val| { - let ident = ident(val.replace('.', "_").to_pascal_case()); - quote! { - #val => Some(PropValue::#ident), - } - }) - .collect::(); - - let prop_value_to_str_arms = prop_values - .iter() - .map(|val| { - let ident = ident(val.replace('.', "_").to_pascal_case()); - quote! { - PropValue::#ident => #val, - } - }) - .collect::(); - - let prop_value_from_u16_arms = prop_values - .iter() - .filter_map(|v| v.parse::().ok()) - .map(|n| { - let ident = ident(n.to_string()); - quote! { - #n => Some(PropValue::#ident), - } - }) - .collect::(); - - let prop_value_to_u16_arms = prop_values - .iter() - .filter_map(|v| v.parse::().ok()) - .map(|n| { - let ident = ident(n.to_string()); - quote! { - PropValue::#ident => Some(#n), - } - }) - .collect::(); - - let prop_value_count = prop_values.len(); - - Ok(quote! { - use valence_math::{Aabb, DVec3}; - - /// Represents the state of a block. This does not include block entity data such as - /// the text on a sign, the design on a banner, or the content of a spawner. - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] - pub struct BlockState(u16); - - impl BlockState { - /// Returns the default block state for a given block type. - pub const fn from_kind(kind: BlockKind) -> Self { - match kind { - #kind_to_state_arms - } - } - - /// Constructs a block state from a raw block state ID. - /// - /// If the given ID is invalid, `None` is returned. - pub const fn from_raw(id: u16) -> Option { - if id <= #max_state_id { - Some(Self(id)) - } else { - None - } - } - - /// Returns the [`BlockKind`] of this block state. - pub const fn to_kind(self) -> BlockKind { - match self.0 { - #state_to_kind_arms - _ => unreachable!(), - } - } - - /// Converts this block state to its underlying raw block state ID. - /// - /// The original block state can be recovered with [`BlockState::from_raw`]. - pub const fn to_raw(self) -> u16 { - self.0 - } - - /// Returns the maximum block state ID. - pub const fn max_raw() -> u16 { - #max_state_id - } - - /// Returns the wall variant of the block state. - /// - /// If the given block state doesn't have a wall variant, `None` is returned. - pub const fn wall_block_id(self) -> Option { - match self { - #state_to_wall_variant_arms - _ => None - } - } - - /// Gets the value of the property with the given name from this block. - /// - /// If this block does not have the property, then `None` is returned. - pub const fn get(self, name: PropName) -> Option { - match self.to_kind() { - #get_arms - _ => None - } - } - - /// Sets the value of a property on this block, returning the modified block. - /// - /// If this block does not have the given property or the property value is invalid, - /// then the original block is returned unchanged. - #[must_use] - pub const fn set(self, name: PropName, val: PropValue) -> Self { - match self.to_kind() { - #set_arms - _ => self, - } - } - - /// If this block is `air`, `cave_air` or `void_air`. - pub const fn is_air(self) -> bool { - matches!( - self, - BlockState::AIR | BlockState::CAVE_AIR | BlockState::VOID_AIR - ) - } - - // TODO: is_solid - - /// If this block is water or lava. - pub const fn is_liquid(self) -> bool { - matches!(self.to_kind(), BlockKind::Water | BlockKind::Lava) - } - - pub const fn is_opaque(self) -> bool { - match self.0 { - #state_to_opaque_arms - _ => true, - } - } - - pub const fn is_replaceable(self) -> bool { - match self.0 { - #state_to_replaceable_arms - _ => false, - } - } - - const SHAPES: [Aabb; #shape_count] = [ - #(#shapes,)* - ]; - - pub fn collision_shapes(self) -> impl ExactSizeIterator + FusedIterator + Clone { - let shape_idxs: &'static [u16] = match self.0 { - #state_to_collision_shapes_arms - _ => &[], - }; - - shape_idxs.into_iter().map(|idx| Self::SHAPES[*idx as usize]) - } - - pub const fn luminance(self) -> u8 { - match self.0 { - #state_to_luminance_arms - _ => 0, - } - } - - pub const fn block_entity_kind(self) -> Option { - let kind = match self.0 { - #state_to_block_entity_type_arms - _ => None - }; - - match kind { - Some(id) => BlockEntityKind::from_id(id), - None => None, - } - } - - #default_block_states - } - - /// An enumeration of all block kinds. - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - pub enum BlockKind { - #(#block_kind_variants,)* - } - - impl BlockKind { - /// Construct a block kind from its snake_case name. - /// - /// Returns `None` if the name is invalid. - pub fn from_str(name: &str) -> Option { - match name { - #block_kind_from_str_arms - _ => None - } - } - - /// Get the snake_case name of this block kind. - pub const fn to_str(self) -> &'static str { - match self { - #block_kind_to_str_arms - } - } - - /// Returns the default block state for a given block kind. - pub const fn to_state(self) -> BlockState { - BlockState::from_kind(self) - } - - /// Returns a slice of all properties this block kind has. - pub const fn props(self) -> &'static [PropName] { - match self { - #block_kind_props_arms - _ => &[], - } - } - - pub const fn translation_key(self) -> &'static str { - match self { - #kind_to_translation_key_arms - } - } - - /// Converts a block kind to its corresponding item kind. - /// - /// [`ItemKind::Air`] is used to indicate the absence of an item. - pub const fn to_item_kind(self) -> ItemKind { - let id = match self { - #block_kind_to_item_kind_arms - }; - - // TODO: unwrap() is not const yet. - match ItemKind::from_raw(id) { - Some(k) => k, - None => unreachable!(), - } - } - - /// Constructs a block kind from an item kind. - /// - /// If the given item does not have a corresponding block, `None` is returned. - pub const fn from_item_kind(item: ItemKind) -> Option { - // The "default" blocks are ordered before the other variants. - // For instance, `torch` comes before `wall_torch` so this match - // should do the correct thing. - #[allow(unreachable_patterns)] - match item.to_raw() { - #block_kind_from_item_kind_arms - _ => None, - } - } - - /// Constructs a block kind from a raw block kind ID. - /// - /// If the given ID is invalid, `None` is returned. - pub const fn from_raw(id: u16) -> Option { - match id { - #block_kind_from_raw_arms - _ => None, - } - } - - /// Converts this block kind to its underlying raw block state ID. - /// - /// The original block kind can be recovered with [`BlockKind::from_raw`]. - pub const fn to_raw(self) -> u16 { - self as u16 - } - - /// An array of all block kinds. - pub const ALL: [Self; #block_kind_count] = [#(Self::#block_kind_variants,)*]; - } - - /// The default block kind is `air`. - impl Default for BlockKind { - fn default() -> Self { - Self::Air - } - } - - /// Contains all possible block state property names. - /// - /// For example, `waterlogged`, `facing`, and `half` are all property names. - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - pub enum PropName { - #(#prop_name_variants,)* - } - - impl PropName { - /// Construct a property name from its snake_case name. - /// - /// Returns `None` if the given name is not valid. - pub fn from_str(name: &str) -> Option { - // TODO: match on str in const fn. - match name { - #prop_name_from_str_arms - _ => None, - } - } - - /// Get the snake_case name of this property name. - pub const fn to_str(self) -> &'static str { - match self { - #prop_name_to_str_arms - } - } - - /// An array of all property names. - pub const ALL: [Self; #prop_name_count] = [#(Self::#prop_name_variants,)*]; - } - - /// Contains all possible values that a block property might have. - /// - /// For example, `upper`, `true`, and `2` are all property values. - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - pub enum PropValue { - #(#prop_value_variants,)* - } - - impl PropValue { - /// Construct a property value from its snake_case name. - /// - /// Returns `None` if the given name is not valid. - pub fn from_str(name: &str) -> Option { - match name { - #prop_value_from_str_arms - _ => None, - } - } - - /// Get the snake_case name of this property value. - pub const fn to_str(self) -> &'static str { - match self { - #prop_value_to_str_arms - } - } - - /// Converts a `u16` into a numeric property value. - /// Returns `None` if the given number does not have a - /// corresponding property value. - pub const fn from_u16(n: u16) -> Option { - match n { - #prop_value_from_u16_arms - _ => None, - } - } - - /// Converts this property value into a `u16` if it is numeric. - /// Returns `None` otherwise. - pub const fn to_u16(self) -> Option { - match self { - #prop_value_to_u16_arms - _ => None, - } - } - - /// Converts a `bool` to a `True` or `False` property value. - pub const fn from_bool(b: bool) -> Self { - if b { - Self::True - } else { - Self::False - } - } - - /// Converts a `True` or `False` property value to a `bool`. - /// - /// Returns `None` if this property value is not `True` or `False` - pub const fn to_bool(self) -> Option { - match self { - Self::True => Some(true), - Self::False => Some(false), - _ => None, - } - } - - /// An array of all property values. - pub const ALL: [Self; #prop_value_count] = [#(Self::#prop_value_variants,)*]; - } - - impl From for PropValue { - fn from(b: bool) -> Self { - Self::from_bool(b) - } - } - - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - pub enum BlockEntityKind { - #block_entity_kind_variants - } - - impl BlockEntityKind { - pub const fn from_id(num: u32) -> Option { - match num { - #block_entity_kind_from_id_arms - _ => None - } - } - - pub const fn id(self) -> u32 { - match self { - #block_entity_kind_to_id_arms - } - } - - pub fn from_ident(ident: Ident<&str>) -> Option { - match ident.as_str() { - #block_entity_kind_from_ident_arms - _ => None - } - } - - pub fn ident(self) -> Ident<&'static str> { - match self { - #block_entity_kind_to_ident_arms - } - } - } - - impl Encode for BlockEntityKind { - fn encode(&self, w: impl Write) -> anyhow::Result<()> { - VarInt(self.id() as i32).encode(w) - } - } - - impl<'a> Decode<'a> for BlockEntityKind { - fn decode(r: &mut &'a [u8]) -> anyhow::Result { - let id = VarInt::decode(r)?; - Self::from_id(id.0 as u32).with_context(|| format!("id {}", id.0)) - } - } - }) -} diff --git a/crates/valence_block/src/lib.rs b/crates/valence_block/src/lib.rs deleted file mode 100644 index 0673f9700..000000000 --- a/crates/valence_block/src/lib.rs +++ /dev/null @@ -1,135 +0,0 @@ -#![doc = include_str!("../README.md")] -#![allow(clippy::all)] // TODO: block build script creates many warnings. -#![deny( - rustdoc::broken_intra_doc_links, - rustdoc::private_intra_doc_links, - rustdoc::missing_crate_level_docs, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_rust_codeblocks, - rustdoc::bare_urls, - rustdoc::invalid_html_tags -)] -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_lifetimes, - unused_import_braces, - unreachable_pub, - clippy::dbg_macro -)] - -use std::fmt; -use std::fmt::Display; -use std::io::Write; -use std::iter::FusedIterator; - -use anyhow::Context; -use valence_core::ident; -use valence_core::ident::Ident; -use valence_core::item::ItemKind; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::{Decode, Encode}; - -include!(concat!(env!("OUT_DIR"), "/block.rs")); - -impl fmt::Debug for BlockState { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt_block_state(*self, f) - } -} - -impl Display for BlockState { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt_block_state(*self, f) - } -} - -fn fmt_block_state(bs: BlockState, f: &mut fmt::Formatter) -> fmt::Result { - let kind = bs.to_kind(); - - write!(f, "{}", kind.to_str())?; - - let props = kind.props(); - - if !props.is_empty() { - let mut list = f.debug_list(); - for &p in kind.props() { - struct KeyVal<'a>(&'a str, &'a str); - - impl<'a> fmt::Debug for KeyVal<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}={}", self.0, self.1) - } - } - - list.entry(&KeyVal(p.to_str(), bs.get(p).unwrap().to_str())); - } - list.finish() - } else { - Ok(()) - } -} - -impl Encode for BlockState { - fn encode(&self, w: impl Write) -> anyhow::Result<()> { - VarInt(self.to_raw() as i32).encode(w) - } -} - -impl Decode<'_> for BlockState { - fn decode(r: &mut &[u8]) -> anyhow::Result { - let id = VarInt::decode(r)?.0; - let errmsg = "invalid block state ID"; - - BlockState::from_raw(id.try_into().context(errmsg)?).context(errmsg) - } -} - -impl Encode for BlockKind { - fn encode(&self, w: impl Write) -> anyhow::Result<()> { - VarInt(self.to_raw() as i32).encode(w) - } -} - -impl Decode<'_> for BlockKind { - fn decode(r: &mut &[u8]) -> anyhow::Result { - let id = VarInt::decode(r)?.0; - let errmsg = "invalid block kind ID"; - - BlockKind::from_raw(id.try_into().context(errmsg)?).context(errmsg) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn get_set_consistency() { - for kind in BlockKind::ALL { - let block = kind.to_state(); - - for &prop in kind.props() { - let new_block = block.set(prop, block.get(prop).unwrap()); - assert_eq!(new_block, block); - } - } - } - - #[test] - fn blockstate_to_wall() { - assert_eq!(BlockState::STONE.wall_block_id(), None); - assert_eq!( - BlockState::OAK_SIGN.wall_block_id(), - Some(BlockState::OAK_WALL_SIGN) - ); - assert_eq!( - BlockState::GREEN_BANNER.wall_block_id(), - Some(BlockState::GREEN_WALL_BANNER) - ); - assert_ne!( - BlockState::GREEN_BANNER.wall_block_id(), - Some(BlockState::GREEN_BANNER) - ); - } -} diff --git a/crates/valence_boss_bar/Cargo.toml b/crates/valence_boss_bar/Cargo.toml index a2d669157..efe5fdfee 100644 --- a/crates/valence_boss_bar/Cargo.toml +++ b/crates/valence_boss_bar/Cargo.toml @@ -12,7 +12,6 @@ valence_core.workspace = true valence_network.workspace = true valence_entity.workspace = true valence_client.workspace = true -valence_packet.workspace = true uuid.workspace = true bitfield-struct.workspace = true bevy_app.workspace = true diff --git a/crates/valence_build_utils/src/lib.rs b/crates/valence_build_utils/src/lib.rs index 2b2d6046e..775f82a75 100644 --- a/crates/valence_build_utils/src/lib.rs +++ b/crates/valence_build_utils/src/lib.rs @@ -49,6 +49,7 @@ pub fn ident(s: impl AsRef) -> Ident { .unwrap_or_else(|_| Ident::new(format!("_{s}").as_str(), Span::call_site())) } +#[track_caller] pub fn rerun_if_changed(files: [&str; N]) { for file in files { assert!( diff --git a/crates/valence_client/Cargo.toml b/crates/valence_client/Cargo.toml index b8a891702..845d544a0 100644 --- a/crates/valence_client/Cargo.toml +++ b/crates/valence_client/Cargo.toml @@ -19,7 +19,6 @@ valence_biome.workspace = true valence_core.workspace = true valence_dimension.workspace = true valence_entity.workspace = true -valence_packet.workspace = true valence_layer.workspace = true valence_nbt.workspace = true valence_registry.workspace = true diff --git a/crates/valence_core/Cargo.toml b/crates/valence_core/Cargo.toml index f06a28df1..7af30306c 100644 --- a/crates/valence_core/Cargo.toml +++ b/crates/valence_core/Cargo.toml @@ -25,7 +25,6 @@ thiserror.workspace = true tracing.workspace = true uuid = { workspace = true, features = ["serde"] } valence_nbt = { workspace = true, features = ["binary"] } -valence_core_macros.workspace = true url.workspace = true base64.workspace = true rand.workspace = true @@ -34,11 +33,3 @@ rand.workspace = true rand.workspace = true # valence_core = { workspace = true, features = ["compression"] } -[build-dependencies] -anyhow.workspace = true -heck.workspace = true -proc-macro2.workspace = true -quote.workspace = true -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true -valence_build_utils.workspace = true diff --git a/crates/valence_core/build/item.rs b/crates/valence_core/build/item.rs deleted file mode 100644 index e8ebc1583..000000000 --- a/crates/valence_core/build/item.rs +++ /dev/null @@ -1,301 +0,0 @@ -use anyhow::Ok; -use heck::ToPascalCase; -use proc_macro2::TokenStream; -use quote::quote; -use serde::Deserialize; -use valence_build_utils::ident; - -#[derive(Deserialize, Clone, Debug)] -struct Item { - id: u16, - name: String, - translation_key: String, - max_stack: u8, - max_durability: u16, - enchantability: u8, - fireproof: bool, - food: Option, -} - -#[derive(Deserialize, Clone, Debug)] -struct FoodComponent { - hunger: u16, - saturation: f32, - always_edible: bool, - meat: bool, - snack: bool, - // TODO: effects -} - -pub fn build() -> anyhow::Result { - let items = serde_json::from_str::>(include_str!("../../../extracted/items.json"))?; - - let item_kind_count = items.len(); - - let item_kind_from_raw_id_arms = items - .iter() - .map(|item| { - let id = &item.id; - let name = ident(item.name.replace('.', "_").to_pascal_case()); - - quote! { - #id => Some(Self::#name), - } - }) - .collect::(); - - let item_kind_to_raw_id_arms = items - .iter() - .map(|item| { - let id = &item.id; - let name = ident(item.name.replace('.', "_").to_pascal_case()); - - quote! { - Self::#name => #id, - } - }) - .collect::(); - - let item_kind_from_str_arms = items - .iter() - .map(|item| { - let str_name = &item.name; - let name = ident(str_name.replace('.', "_").to_pascal_case()); - quote! { - #str_name => Some(Self::#name), - } - }) - .collect::(); - - let item_kind_to_str_arms = items - .iter() - .map(|item| { - let str_name = &item.name; - let name = ident(str_name.replace('.', "_").to_pascal_case()); - quote! { - Self::#name => #str_name, - } - }) - .collect::(); - - let item_kind_to_translation_key_arms = items - .iter() - .map(|item| { - let name = ident(item.name.replace('.', "_").to_pascal_case()); - let translation_key = &item.translation_key; - quote! { - Self::#name => #translation_key, - } - }) - .collect::(); - - let item_kind_variants = items - .iter() - .map(|item| ident(item.name.replace('.', "_").to_pascal_case())) - .collect::>(); - - let item_kind_to_max_stack_arms = items - .iter() - .map(|item| { - let name = ident(item.name.replace('.', "_").to_pascal_case()); - let max_stack = item.max_stack; - - quote! { - Self::#name => #max_stack, - } - }) - .collect::(); - - let item_kind_to_food_component_arms = items - .iter() - .map(|item| match &item.food { - Some(food_component) => { - let name = ident(item.name.replace('.', "_").to_pascal_case()); - let hunger = food_component.hunger; - let saturation = food_component.saturation; - let always_edible = food_component.always_edible; - let meat = food_component.meat; - let snack = food_component.snack; - - quote! { - Self::#name => Some(FoodComponent { - hunger: #hunger, - saturation: #saturation, - always_edible: #always_edible, - meat: #meat, - snack: #snack, - } - ), - } - } - None => quote! {}, - }) - .collect::(); - - let item_kind_to_max_durability_arms = items - .iter() - .filter(|item| item.max_durability != 0) - .map(|item| { - let name = ident(item.name.replace('.', "_").to_pascal_case()); - let max_durability = item.max_durability; - - quote! { - Self::#name => #max_durability, - } - }) - .collect::(); - - let item_kind_to_enchantability_arms = items - .iter() - .filter(|item| item.enchantability != 0) - .map(|item| { - let name = ident(item.name.replace('.', "_").to_pascal_case()); - let ench = item.enchantability; - - quote! { - Self::#name => #ench, - } - }) - .collect::(); - - let item_kind_to_fireproof_arms = items - .iter() - .filter(|item| item.fireproof) - .map(|item| { - let name = ident(item.name.replace('.', "_").to_pascal_case()); - - quote! { - Self::#name => true, - } - }) - .collect::(); - - Ok(quote! { - /// Represents an item from the game - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - #[repr(u16)] - pub enum ItemKind { - #(#item_kind_variants,)* - } - - /// Contains food information about an item. - /// - /// Only food items have a food component. - #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] - pub struct FoodComponent { - pub hunger: u16, - pub saturation: f32, - pub always_edible: bool, - pub meat: bool, - pub snack: bool, - } - - impl ItemKind { - /// Constructs a item kind from a raw item ID. - /// - /// If the given ID is invalid, `None` is returned. - pub const fn from_raw(id: u16) -> Option { - match id { - #item_kind_from_raw_id_arms - _ => None - } - } - - /// Gets the raw item ID from the item kind - pub const fn to_raw(self) -> u16 { - match self { - #item_kind_to_raw_id_arms - } - } - - /// Construct an item kind for its snake_case name. - /// - /// Returns `None` if the name is invalid. - #[allow(clippy::should_implement_trait)] - pub fn from_str(name: &str) -> Option { - match name { - #item_kind_from_str_arms - _ => None - } - } - - /// Gets the snake_case name of this item kind. - pub const fn to_str(self) -> &'static str { - match self { - #item_kind_to_str_arms - } - } - - /// Gets the translation key of this item kind. - pub const fn translation_key(self) -> &'static str { - match self { - #item_kind_to_translation_key_arms - } - } - - /// Returns the maximum stack count. - pub const fn max_stack(self) -> u8 { - match self { - #item_kind_to_max_stack_arms - } - } - - /// Returns a food component which stores hunger, saturation etc. - /// - /// If the item kind can't be eaten, `None` will be returned. - pub const fn food_component(self) -> Option { - match self { - #item_kind_to_food_component_arms - _ => None - } - } - - /// Returns the maximum durability before the item will break. - /// - /// If the item doesn't have durability, `0` is returned. - pub const fn max_durability(self) -> u16 { - match self { - #item_kind_to_max_durability_arms - _ => 0, - } - } - - /// Returns the enchantability of the item kind. - /// - /// If the item doesn't have durability, `0` is returned. - pub const fn enchantability(self) -> u8 { - match self { - #item_kind_to_enchantability_arms - _ => 0, - } - } - - /// Returns if the item can survive in fire/lava. - pub const fn fireproof(self) -> bool { - #[allow(clippy::match_like_matches_macro)] - match self { - #item_kind_to_fireproof_arms - _ => false - } - } - - /* - /// Constructs an item kind from a block kind. - /// - /// [`ItemKind::Air`] is used to indicate the absence of an item. - pub const fn from_block_kind(kind: BlockKind) -> Self { - kind.to_item_kind() - } - - /// Constructs a block kind from an item kind. - /// - /// If the given item kind doesn't have a corresponding block kind, `None` is returned. - pub const fn to_block_kind(self) -> Option { - BlockKind::from_item_kind(self) - }*/ - - /// An array of all item kinds. - pub const ALL: [Self; #item_kind_count] = [#(Self::#item_kind_variants,)*]; - } - }) -} diff --git a/crates/valence_core/build/main.rs b/crates/valence_core/build/main.rs deleted file mode 100644 index f77de4bb3..000000000 --- a/crates/valence_core/build/main.rs +++ /dev/null @@ -1,21 +0,0 @@ -use valence_build_utils::{rerun_if_changed, write_generated_file}; - -mod chunk_pos; -mod item; -mod sound; -mod translation_key; - -pub fn main() -> anyhow::Result<()> { - rerun_if_changed([ - "../../extracted/items.json", - "../../extracted/sounds.json", - "../../extracted/translation_keys.json", - ]); - - write_generated_file(item::build()?, "item.rs")?; - write_generated_file(sound::build()?, "sound.rs")?; - write_generated_file(translation_key::build()?, "translation_key.rs")?; - write_generated_file(chunk_pos::build(), "chunk_pos.rs")?; - - Ok(()) -} diff --git a/crates/valence_core/build/sound.rs b/crates/valence_core/build/sound.rs deleted file mode 100644 index e4e260e92..000000000 --- a/crates/valence_core/build/sound.rs +++ /dev/null @@ -1,118 +0,0 @@ -use heck::ToPascalCase; -use proc_macro2::TokenStream; -use quote::quote; -use serde::Deserialize; -use valence_build_utils::ident; - -#[derive(Deserialize, Debug)] -pub struct Sound { - id: u16, - name: String, -} - -pub fn build() -> anyhow::Result { - let sounds = - serde_json::from_str::>(include_str!("../../../extracted/sounds.json"))?; - - let sound_count = sounds.len(); - - let sound_from_raw_id_arms = sounds - .iter() - .map(|sound| { - let id = &sound.id; - let name = ident(sound.name.replace('.', "_").to_pascal_case()); - - quote! { - #id => Some(Self::#name), - } - }) - .collect::(); - - let sound_to_raw_id_arms = sounds - .iter() - .map(|sound| { - let id = &sound.id; - let name = ident(sound.name.replace('.', "_").to_pascal_case()); - - quote! { - Self::#name => #id, - } - }) - .collect::(); - - let sound_from_str_arms = sounds - .iter() - .map(|sound| { - let str_name = &sound.name; - let name = ident(str_name.replace('.', "_").to_pascal_case()); - quote! { - #str_name => Some(Self::#name), - } - }) - .collect::(); - - let sound_to_str_arms = sounds - .iter() - .map(|sound| { - let str_name = &sound.name; - let name = ident(str_name.replace('.', "_").to_pascal_case()); - quote! { - Self::#name => ident!(#str_name), - } - }) - .collect::(); - - let sound_variants = sounds - .iter() - .map(|sound| ident(sound.name.replace('.', "_").to_pascal_case())) - .collect::>(); - - Ok(quote! { - /// Represents a sound from the game - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - #[repr(u16)] - pub enum Sound { - #(#sound_variants,)* - } - - impl Sound { - /// Constructs a sound from a raw item ID. - /// - /// If the given ID is invalid, `None` is returned. - pub const fn from_raw(id: u16) -> Option { - match id { - #sound_from_raw_id_arms - _ => None - } - } - - /// Gets the raw sound ID from the sound - pub const fn to_raw(self) -> u16 { - match self { - #sound_to_raw_id_arms - } - } - - /// Construct a sound from its snake_case name. - /// - /// Returns `None` if the name is invalid. - #[allow(clippy::should_implement_trait)] - pub fn from_str(name: &str) -> Option { - match name { - #sound_from_str_arms - _ => None - } - } - - /// Gets the identifier of this sound. - pub const fn to_ident(self) -> Ident<&'static str> { - match self { - #sound_to_str_arms - } - } - - /// An array of all sounds. - pub const ALL: [Self; #sound_count] = [#(Self::#sound_variants,)*]; - } - }) -} diff --git a/crates/valence_core/build/translation_key.rs b/crates/valence_core/build/translation_key.rs deleted file mode 100644 index d0f4e36c9..000000000 --- a/crates/valence_core/build/translation_key.rs +++ /dev/null @@ -1,42 +0,0 @@ -use anyhow::Ok; -use heck::ToShoutySnakeCase; -use proc_macro2::TokenStream; -use quote::quote; -use serde::Deserialize; -use valence_build_utils::ident; - -#[derive(Deserialize, Clone, Debug)] -struct Translation { - key: String, - english_translation: String, -} - -/// Escapes characters that have special meaning inside docs. -fn escape(text: &str) -> String { - text.replace('[', "\\[").replace(']', "\\]") -} - -pub fn build() -> anyhow::Result { - let translations = serde_json::from_str::>(include_str!( - "../../../extracted/translation_keys.json" - ))?; - - let translation_key_consts = translations - .iter() - .map(|translation| { - let const_id = ident(translation.key.replace('.', "_").to_shouty_snake_case()); - let key = &translation.key; - let english_translation = &translation.english_translation; - let doc = format!("\"{}\"", escape(english_translation)); - - quote! { - #[doc = #doc] - pub const #const_id: &str = #key; - } - }) - .collect::>(); - - Ok(quote! { - #(#translation_key_consts)* - }) -} diff --git a/crates/valence_core/src/lib.rs b/crates/valence_core/src/lib.rs index 55eca6a5d..4ff1faacd 100644 --- a/crates/valence_core/src/lib.rs +++ b/crates/valence_core/src/lib.rs @@ -18,22 +18,7 @@ )] #![allow(clippy::unusual_byte_groupings)] -pub mod block_pos; -pub mod chunk_pos; pub mod despawn; -pub mod difficulty; -pub mod direction; -pub mod game_mode; -pub mod hand; -pub mod ident; -pub mod item; -pub mod player_textures; -pub mod property; -pub mod protocol; -pub mod scratch; -pub mod sound; -pub mod text; -pub mod translation_key; pub mod uuid; use std::num::NonZeroU32; @@ -45,25 +30,9 @@ use bevy_ecs::prelude::*; use crate::despawn::despawn_marked_entities; -/// Used only by macros. Not public API. -#[doc(hidden)] -pub mod __private { - pub use anyhow::{anyhow, bail, ensure, Context, Result}; - - pub use crate::protocol::var_int::VarInt; - pub use crate::protocol::{Decode, Encode}; -} - // Needed to make proc macros work. extern crate self as valence_core; -/// The Minecraft protocol version this library currently targets. -pub const PROTOCOL_VERSION: i32 = 763; - -/// The stringified name of the Minecraft version this library currently -/// targets. -pub const MINECRAFT_VERSION: &str = "1.20.1"; - /// Minecraft's standard ticks per second (TPS). pub const DEFAULT_TPS: NonZeroU32 = match NonZeroU32::new(20) { Some(n) => n, diff --git a/crates/valence_core/src/protocol.rs b/crates/valence_core/src/protocol.rs deleted file mode 100644 index 3b15c8e67..000000000 --- a/crates/valence_core/src/protocol.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! Minecraft's protocol. - -pub mod array; -pub mod byte_angle; -pub mod global_pos; -pub mod impls; -pub mod raw; -pub mod var_int; -pub mod var_long; - -use std::io::Write; - -pub use valence_core_macros::{Decode, Encode}; - -/// The maximum number of bytes in a single Minecraft packet. -pub const MAX_PACKET_SIZE: i32 = 2097152; - -/// The `Encode` trait allows objects to be written to the Minecraft protocol. -/// It is the inverse of [`Decode`]. -/// -/// # Deriving -/// -/// This trait can be implemented automatically for structs and enums by using -/// the [`Encode`][macro] derive macro. All components of the type must -/// implement `Encode`. Components are encoded in the order they appear in the -/// type definition. -/// -/// For enums, the variant to encode is marked by a leading [`VarInt`] -/// discriminant (tag). The discriminant value can be changed using the `#[tag = -/// ...]` attribute on the variant in question. Discriminant values are assigned -/// to variants using rules similar to regular enum discriminants. -/// -/// ``` -/// use valence_core::protocol::Encode; -/// -/// #[derive(Encode)] -/// struct MyStruct<'a> { -/// first: i32, -/// second: &'a str, -/// third: [f64; 3], -/// } -/// -/// #[derive(Encode)] -/// enum MyEnum { -/// First, // tag = 0 -/// Second, // tag = 1 -/// #[packet(tag = 25)] -/// Third, // tag = 25 -/// Fourth, // tag = 26 -/// } -/// -/// let value = MyStruct { -/// first: 10, -/// second: "hello", -/// third: [1.5, 3.14, 2.718], -/// }; -/// -/// let mut buf = vec![]; -/// value.encode(&mut buf).unwrap(); -/// -/// println!("{buf:?}"); -/// ``` -/// -/// [macro]: valence_core_macros::Encode -/// [`VarInt`]: var_int::VarInt -pub trait Encode { - /// Writes this object to the provided writer. - /// - /// If this type also implements [`Decode`] then successful calls to this - /// function returning `Ok(())` must always successfully [`decode`] using - /// the data that was written to the writer. The exact number of bytes - /// that were originally written must be consumed during the decoding. - /// - /// [`decode`]: Decode::decode - fn encode(&self, w: impl Write) -> anyhow::Result<()>; - - /// Like [`Encode::encode`], except that a whole slice of values is encoded. - /// - /// This method must be semantically equivalent to encoding every element of - /// the slice in sequence with no leading length prefix (which is exactly - /// what the default implementation does), but a more efficient - /// implementation may be used. - /// - /// This optimization is very important for some types like `u8` where - /// [`write_all`] is used. Because impl specialization is unavailable in - /// stable Rust, we must make the slice specialization part of this trait. - /// - /// [`write_all`]: Write::write_all - fn encode_slice(slice: &[Self], mut w: impl Write) -> anyhow::Result<()> - where - Self: Sized, - { - for value in slice { - value.encode(&mut w)?; - } - - Ok(()) - } -} - -/// The `Decode` trait allows objects to be read from the Minecraft protocol. It -/// is the inverse of [`Encode`]. -/// -/// `Decode` is parameterized by a lifetime. This allows the decoded value to -/// borrow data from the byte slice it was read from. -/// -/// # Deriving -/// -/// This trait can be implemented automatically for structs and enums by using -/// the [`Decode`][macro] derive macro. All components of the type must -/// implement `Decode`. Components are decoded in the order they appear in the -/// type definition. -/// -/// For enums, the variant to decode is determined by a leading [`VarInt`] -/// discriminant (tag). The discriminant value can be changed using the `#[tag = -/// ...]` attribute on the variant in question. Discriminant values are assigned -/// to variants using rules similar to regular enum discriminants. -/// -/// ``` -/// use valence_core::protocol::Decode; -/// -/// #[derive(PartialEq, Debug, Decode)] -/// struct MyStruct { -/// first: i32, -/// second: MyEnum, -/// } -/// -/// #[derive(PartialEq, Debug, Decode)] -/// enum MyEnum { -/// First, // tag = 0 -/// Second, // tag = 1 -/// #[packet(tag = 25)] -/// Third, // tag = 25 -/// Fourth, // tag = 26 -/// } -/// -/// let mut r: &[u8] = &[0, 0, 0, 0, 26]; -/// -/// let value = MyStruct::decode(&mut r).unwrap(); -/// let expected = MyStruct { -/// first: 0, -/// second: MyEnum::Fourth, -/// }; -/// -/// assert_eq!(value, expected); -/// assert!(r.is_empty()); -/// ``` -/// -/// [macro]: valence_core_macros::Decode -/// [`VarInt`]: var_int::VarInt -pub trait Decode<'a>: Sized { - /// Reads this object from the provided byte slice. - /// - /// Implementations of `Decode` are expected to shrink the slice from the - /// front as bytes are read. - fn decode(r: &mut &'a [u8]) -> anyhow::Result; -} diff --git a/crates/valence_core/src/scratch.rs b/crates/valence_core/src/scratch.rs deleted file mode 100644 index 6d48629c2..000000000 --- a/crates/valence_core/src/scratch.rs +++ /dev/null @@ -1,8 +0,0 @@ -use bevy_ecs::prelude::*; - -/// General-purpose reusable byte buffer. -/// -/// No guarantees are made about the buffer's contents between systems. -/// Therefore, the inner `Vec` should be cleared before use. -#[derive(Component, Default, Debug)] -pub struct ScratchBuf(pub Vec); diff --git a/crates/valence_core/src/translation_key.rs b/crates/valence_core/src/translation_key.rs deleted file mode 100644 index 04f3f4505..000000000 --- a/crates/valence_core/src/translation_key.rs +++ /dev/null @@ -1 +0,0 @@ -include!(concat!(env!("OUT_DIR"), "/translation_key.rs")); diff --git a/crates/valence_core/src/util.rs b/crates/valence_core/src/util.rs deleted file mode 100644 index 349d428a4..000000000 --- a/crates/valence_core/src/util.rs +++ /dev/null @@ -1,22 +0,0 @@ -pub use glam::*; - -#[cfg(test)] -mod tests { - use approx::assert_relative_eq; - use rand::random; - - use super::*; - - #[test] - fn yaw_pitch_round_trip() { - for _ in 0..=100 { - let d = (Vec3::new(random(), random(), random()) * 2.0 - 1.0).normalize(); - - let (yaw, pitch) = to_yaw_and_pitch(d); - let d_new = from_yaw_and_pitch(yaw, pitch); - - assert_relative_eq!(d, d_new, epsilon = f32::EPSILON * 100.0); - } - } -} - diff --git a/crates/valence_core_macros/Cargo.toml b/crates/valence_core_macros/Cargo.toml deleted file mode 100644 index 4e7ef88aa..000000000 --- a/crates/valence_core_macros/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "valence_core_macros" -version.workspace = true -edition.workspace = true - -[lib] -proc-macro = true - -[dependencies] -proc-macro2.workspace = true -quote.workspace = true -syn = { workspace = true, features = ["full"] } diff --git a/crates/valence_core_macros/src/ident.rs b/crates/valence_core_macros/src/ident.rs deleted file mode 100644 index d5d34f7dc..000000000 --- a/crates/valence_core_macros/src/ident.rs +++ /dev/null @@ -1,35 +0,0 @@ -use proc_macro2::TokenStream; -use quote::quote; -use syn::{parse2, LitStr, Result}; - -fn check_namespace(s: &str) -> bool { - !s.is_empty() - && s.chars() - .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '.' | '-')) -} - -fn check_path(s: &str) -> bool { - !s.is_empty() - && s.chars() - .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '.' | '-' | '/')) -} - -pub(super) fn parse_ident_str(item: TokenStream) -> Result { - let ident_lit: LitStr = parse2(item)?; - let mut ident = ident_lit.value(); - - match ident.split_once(':') { - Some((namespace, path)) if check_namespace(namespace) && check_path(path) => {} - None if check_path(&ident) => { - ident = format!("minecraft:{ident}"); - } - _ => { - return Err(syn::Error::new( - ident_lit.span(), - "string cannot be parsed as a resource identifier", - )) - } - } - - Ok(quote!(#ident)) -} diff --git a/crates/valence_dimension/src/lib.rs b/crates/valence_dimension/src/lib.rs index 36c34a657..78c4e7bfe 100644 --- a/crates/valence_dimension/src/lib.rs +++ b/crates/valence_dimension/src/lib.rs @@ -28,7 +28,6 @@ use valence_core::ident::Ident; use valence_nbt::serde::CompoundSerializer; use valence_registry::codec::{RegistryCodec, RegistryValue}; use valence_registry::{Registry, RegistryIdx, RegistrySet}; - pub struct DimensionPlugin; impl Plugin for DimensionPlugin { @@ -150,7 +149,7 @@ pub struct DimensionType { impl Default for DimensionType { fn default() -> Self { Self { - ambient_light: 1.0, + ambient_light: 0.0, bed_works: true, coordinate_scale: 1.0, effects: DimensionEffects::default(), diff --git a/crates/valence_entity/Cargo.toml b/crates/valence_entity/Cargo.toml index 0649df315..d547792c1 100644 --- a/crates/valence_entity/Cargo.toml +++ b/crates/valence_entity/Cargo.toml @@ -13,10 +13,8 @@ paste.workspace = true rustc-hash.workspace = true tracing.workspace = true uuid.workspace = true -valence_block.workspace = true valence_core.workspace = true valence_nbt.workspace = true -valence_packet.workspace = true [build-dependencies] anyhow.workspace = true diff --git a/crates/valence_core/build/chunk_pos.rs b/crates/valence_generated/build/chunk_view.rs similarity index 80% rename from crates/valence_core/build/chunk_pos.rs rename to crates/valence_generated/build/chunk_view.rs index 82f75dff6..0fa73fe21 100644 --- a/crates/valence_core/build/chunk_pos.rs +++ b/crates/valence_generated/build/chunk_view.rs @@ -1,7 +1,7 @@ use proc_macro2::TokenStream; use quote::quote; -const MAX_VIEW_DIST: u8 = 32; // This can be increased to 64 if we want. +const MAX_VIEW_DIST: u8 = 32; const EXTRA_VIEW_RADIUS: i32 = 2; pub fn build() -> TokenStream { @@ -33,8 +33,8 @@ pub fn build() -> TokenStream { /// The maximum view distance for a [`ChunkView`]. pub const MAX_VIEW_DIST: u8 = #MAX_VIEW_DIST; - const EXTRA_VIEW_RADIUS: i32 = #EXTRA_VIEW_RADIUS; + pub const EXTRA_VIEW_RADIUS: i32 = #EXTRA_VIEW_RADIUS; - static CHUNK_VIEW_LUT: [&[(i8, i8)]; #array_len] = [ #(#entries),* ]; + pub static CHUNK_VIEW_LUT: [&[(i8, i8)]; #array_len] = [ #(#entries),* ]; } } diff --git a/crates/valence_generated/build/main.rs b/crates/valence_generated/build/main.rs index dd2cbcdc5..c84c4046f 100644 --- a/crates/valence_generated/build/main.rs +++ b/crates/valence_generated/build/main.rs @@ -1,15 +1,19 @@ use valence_build_utils::write_generated_file; mod block; +mod chunk_view; mod item; -mod translation_key; +mod packet_id; mod sound; +mod translation_key; pub fn main() -> anyhow::Result<()> { write_generated_file(block::build()?, "block.rs")?; write_generated_file(translation_key::build()?, "translation_key.rs")?; write_generated_file(item::build()?, "item.rs")?; write_generated_file(sound::build()?, "sound.rs")?; + write_generated_file(packet_id::build()?, "packet_id.rs")?; + write_generated_file(chunk_view::build(), "chunk_view.rs")?; Ok(()) } diff --git a/crates/valence_packet/build.rs b/crates/valence_generated/build/packet_id.rs similarity index 74% rename from crates/valence_packet/build.rs rename to crates/valence_generated/build/packet_id.rs index 9edf33f51..5555bd2f9 100644 --- a/crates/valence_packet/build.rs +++ b/crates/valence_generated/build/packet_id.rs @@ -2,7 +2,7 @@ use heck::ToShoutySnakeCase; use proc_macro2::TokenStream; use quote::quote; use serde::Deserialize; -use valence_build_utils::{ident, rerun_if_changed, write_generated_file}; +use valence_build_utils::{ident, rerun_if_changed}; #[derive(Deserialize)] struct Packet { @@ -12,16 +12,11 @@ struct Packet { id: i32, } -pub fn main() -> anyhow::Result<()> { +pub fn build() -> anyhow::Result { rerun_if_changed(["../../extracted/packets.json"]); - write_generated_file(build()?, "packet_id.rs")?; - - Ok(()) -} - -pub fn build() -> anyhow::Result { - let packets: Vec = serde_json::from_str(include_str!("../../extracted/packets.json"))?; + let packets: Vec = + serde_json::from_str(include_str!("../../../extracted/packets.json"))?; let mut consts = TokenStream::new(); diff --git a/crates/valence_generated/build/sound.rs b/crates/valence_generated/build/sound.rs index 0ea6c46fb..9deb14d5b 100644 --- a/crates/valence_generated/build/sound.rs +++ b/crates/valence_generated/build/sound.rs @@ -102,7 +102,6 @@ pub fn build() -> anyhow::Result { /// Construct a sound from its snake_case name. /// /// Returns `None` if the name is invalid. - #[allow(clippy::should_implement_trait)] pub fn from_ident(id: Ident<&str>) -> Option { match id.as_str() { #sound_from_ident_arms diff --git a/crates/valence_generated/src/block.rs b/crates/valence_generated/src/block.rs index 2887cedb7..500757097 100644 --- a/crates/valence_generated/src/block.rs +++ b/crates/valence_generated/src/block.rs @@ -5,6 +5,7 @@ use std::fmt::Display; use std::iter::FusedIterator; use valence_ident::{ident, Ident}; + use crate::item::ItemKind; include!(concat!(env!("OUT_DIR"), "/block.rs")); diff --git a/crates/valence_generated/src/lib.rs b/crates/valence_generated/src/lib.rs index 6a3ec680e..2d62541a9 100644 --- a/crates/valence_generated/src/lib.rs +++ b/crates/valence_generated/src/lib.rs @@ -11,3 +11,12 @@ pub mod translation_key { pub mod sound { include!(concat!(env!("OUT_DIR"), "/sound.rs")); } + +/// Contains constants for every vanilla packet ID. +pub mod packet_id { + include!(concat!(env!("OUT_DIR"), "/packet_id.rs")); +} + +pub mod chunk_view { + include!(concat!(env!("OUT_DIR"), "/chunk_view.rs")); +} diff --git a/crates/valence_inventory/Cargo.toml b/crates/valence_inventory/Cargo.toml index 2128f02ab..4e0a8d70a 100644 --- a/crates/valence_inventory/Cargo.toml +++ b/crates/valence_inventory/Cargo.toml @@ -10,4 +10,3 @@ bevy_ecs.workspace = true tracing.workspace = true valence_client.workspace = true valence_core.workspace = true -valence_packet.workspace = true diff --git a/crates/valence_layer/Cargo.toml b/crates/valence_layer/Cargo.toml index 67d2994db..15c501279 100644 --- a/crates/valence_layer/Cargo.toml +++ b/crates/valence_layer/Cargo.toml @@ -14,11 +14,9 @@ parking_lot.workspace = true rand.workspace = true rustc-hash.workspace = true valence_biome.workspace = true -valence_block.workspace = true valence_core.workspace = true valence_dimension.workspace = true valence_entity.workspace = true valence_nbt.workspace = true valence_registry.workspace = true -valence_packet.workspace = true tracing.workspace = true diff --git a/crates/valence_network/Cargo.toml b/crates/valence_network/Cargo.toml index 68be203f7..05fd8466e 100644 --- a/crates/valence_network/Cargo.toml +++ b/crates/valence_network/Cargo.toml @@ -3,11 +3,6 @@ name = "valence_network" version.workspace = true edition.workspace = true -[features] -default = ["encryption", "compression"] # TODO: remove this. -encryption = ["valence_packet/encryption"] -compression = ["valence_packet/compression"] - [dependencies] anyhow.workspace = true async-trait.workspace = true @@ -32,7 +27,6 @@ uuid.workspace = true valence_client.workspace = true valence_core.workspace = true valence_entity.workspace = true -valence_packet.workspace = true [dependencies.reqwest] workspace = true diff --git a/crates/valence_packet/README.md b/crates/valence_packet/README.md deleted file mode 100644 index c4c1c616f..000000000 --- a/crates/valence_packet/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# valence_packet - -This contain all (some) the packets structures of the minecraft protocol #763. - -## Naming - -Tha naming of the struct are based on the yarn mapping name and the packet side, for that reason it can be a bit different from the [wiki.vg](https://wiki.vg) name. diff --git a/crates/valence_packet/src/lib.rs b/crates/valence_packet/src/lib.rs deleted file mode 100644 index 666794a87..000000000 --- a/crates/valence_packet/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -pub mod packets; -pub mod protocol; - -/// Used only by macros. Not public API. -#[doc(hidden)] -pub mod __private { - pub use crate::protocol::Packet; -} - -extern crate self as valence_packet; diff --git a/crates/valence_packet/src/packets.rs b/crates/valence_packet/src/packets.rs deleted file mode 100644 index 5f5befbd9..000000000 --- a/crates/valence_packet/src/packets.rs +++ /dev/null @@ -1,18 +0,0 @@ -use std::borrow::Cow; -use std::io::Write; - -use anyhow::bail; -use uuid::Uuid; -use valence_core::ident::Ident; -use valence_core::property::Property; -use valence_core::protocol::raw::RawBytes; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::{Decode, Encode}; -use valence_core::text::Text; - -use crate::protocol::{packet_id, Packet, PacketState}; - -pub mod handshaking; -pub mod login; -pub mod play; -pub mod status; diff --git a/crates/valence_packet/src/protocol.rs b/crates/valence_packet/src/protocol.rs deleted file mode 100644 index bee997831..000000000 --- a/crates/valence_packet/src/protocol.rs +++ /dev/null @@ -1,220 +0,0 @@ -pub mod decode; -pub mod encode; - -use std::io::Write; - -use anyhow::Context; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::*; -pub use valence_packet_macros::Packet; - -/// Types considered to be Minecraft packets. -/// -/// In serialized form, a packet begins with a [`VarInt`] packet ID followed by -/// the body of the packet. If present, the implementations of [`Encode`] and -/// [`Decode`] on `Self` are expected to only encode/decode the _body_ of this -/// packet without the leading ID. -pub trait Packet: std::fmt::Debug { - /// The leading VarInt ID of this packet. - const ID: i32; - /// The name of this packet for debugging purposes. - const NAME: &'static str; - /// The side this packet is intended for - const SIDE: PacketSide; - /// The state which this packet is used - const STATE: PacketState; - - /// Encodes this packet's VarInt ID first, followed by the packet's body. - fn encode_with_id(&self, mut w: impl Write) -> anyhow::Result<()> - where - Self: Encode, - { - VarInt(Self::ID) - .encode(&mut w) - .context("failed to encode packet ID")?; - self.encode(w) - } -} - -/// The side a packet is intended for -#[derive(Copy, Clone, PartialEq, Eq)] -pub enum PacketSide { - /// Server -> Client - Clientbound, - /// Client -> Server - Serverbound, -} - -/// The state which a packet is used -#[derive(Copy, Clone, PartialEq, Eq)] -pub enum PacketState { - Handshaking, - Status, - Login, - Play, -} - -/// Contains constants for every vanilla packet ID. -pub mod packet_id { - include!(concat!(env!("OUT_DIR"), "/packet_id.rs")); -} - -#[allow(dead_code)] -#[cfg(test)] -mod tests { - use std::borrow::Cow; - - use bytes::BytesMut; - - use super::*; - use crate::protocol::decode::PacketDecoder; - use crate::protocol::encode::PacketEncoder; - - #[derive(Encode, Decode, Packet, Debug)] - #[packet(id = 1, side = PacketSide::Clientbound)] - struct RegularStruct { - foo: i32, - bar: bool, - baz: f64, - } - - #[derive(Encode, Decode, Packet, Debug)] - #[packet(id = 2, side = PacketSide::Clientbound)] - struct UnitStruct; - - #[derive(Encode, Decode, Packet, Debug)] - #[packet(id = 3, side = PacketSide::Clientbound)] - struct EmptyStruct {} - - #[derive(Encode, Decode, Packet, Debug)] - #[packet(id = 4, side = PacketSide::Clientbound)] - struct TupleStruct(i32, bool, f64); - - #[derive(Encode, Decode, Packet, Debug)] - #[packet(id = 5, side = PacketSide::Clientbound)] - struct StructWithGenerics<'z, T = ()> { - foo: &'z str, - bar: T, - } - - #[derive(Encode, Decode, Packet, Debug)] - #[packet(id = 6, side = PacketSide::Clientbound)] - struct TupleStructWithGenerics<'z, T = ()>(&'z str, i32, T); - - #[allow(unconditional_recursion, clippy::extra_unused_type_parameters)] - fn assert_has_impls<'a, T>() - where - T: Encode + Decode<'a> + Packet, - { - assert_has_impls::(); - assert_has_impls::(); - assert_has_impls::(); - assert_has_impls::(); - assert_has_impls::(); - assert_has_impls::(); - } - - #[test] - fn packet_name() { - assert_eq!(RegularStruct::NAME, "RegularStruct"); - assert_eq!(UnitStruct::NAME, "UnitStruct"); - assert_eq!(StructWithGenerics::<()>::NAME, "StructWithGenerics"); - } - - use valence_core::block_pos::BlockPos; - use valence_core::hand::Hand; - use valence_core::ident::Ident; - use valence_core::item::{ItemKind, ItemStack}; - use valence_core::protocol::var_int::VarInt; - use valence_core::protocol::var_long::VarLong; - use valence_core::text::{IntoText, Text}; - - #[cfg(feature = "encryption")] - const CRYPT_KEY: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; - - #[derive(PartialEq, Debug, Encode, Decode, Packet)] - #[packet(id = 42, side = PacketSide::Clientbound)] - struct TestPacket<'a> { - a: bool, - b: u8, - c: i32, - d: f32, - e: f64, - f: BlockPos, - g: Hand, - h: Ident>, - i: Option, - j: Text, - k: VarInt, - l: VarLong, - m: &'a str, - n: &'a [u8; 10], - o: [u128; 3], - } - - impl<'a> TestPacket<'a> { - fn new(string: &'a str) -> Self { - Self { - a: true, - b: 12, - c: -999, - d: 5.001, - e: 1e10, - f: BlockPos::new(1, 2, 3), - g: Hand::Off, - h: Ident::new("minecraft:whatever").unwrap(), - i: Some(ItemStack::new(ItemKind::WoodenSword, 12, None)), - j: "my ".into_text() + "fancy".italic() + " text", - k: VarInt(123), - l: VarLong(456), - m: string, - n: &[7; 10], - o: [123456789; 3], - } - } - } - - fn check_test_packet(dec: &mut PacketDecoder, string: &str) { - let frame = dec.try_next_packet().unwrap().unwrap(); - - let pkt = frame.decode::().unwrap(); - - assert_eq!(&pkt, &TestPacket::new(string)); - } - - #[test] - fn packets_round_trip() { - let mut buf = BytesMut::new(); - - let mut enc = PacketEncoder::new(); - - enc.append_packet(&TestPacket::new("first")).unwrap(); - #[cfg(feature = "compression")] - enc.set_compression(Some(0)); - enc.append_packet(&TestPacket::new("second")).unwrap(); - buf.unsplit(enc.take()); - #[cfg(feature = "encryption")] - enc.enable_encryption(&CRYPT_KEY); - enc.append_packet(&TestPacket::new("third")).unwrap(); - enc.prepend_packet(&TestPacket::new("fourth")).unwrap(); - - buf.unsplit(enc.take()); - - let mut dec = PacketDecoder::new(); - - dec.queue_bytes(buf); - - check_test_packet(&mut dec, "first"); - - #[cfg(feature = "compression")] - dec.set_compression(Some(0)); - - check_test_packet(&mut dec, "second"); - - #[cfg(feature = "encryption")] - dec.enable_encryption(&CRYPT_KEY); - - check_test_packet(&mut dec, "fourth"); - check_test_packet(&mut dec, "third"); - } -} diff --git a/crates/valence_packet_macros/README.md b/crates/valence_packet_macros/README.md deleted file mode 100644 index 5c1cd2b74..000000000 --- a/crates/valence_packet_macros/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# valence_packet_macros - -Procedural macros for `valence_packet` diff --git a/crates/valence_packet_macros/src/lib.rs b/crates/valence_packet_macros/src/lib.rs deleted file mode 100644 index d55edec1b..000000000 --- a/crates/valence_packet_macros/src/lib.rs +++ /dev/null @@ -1,40 +0,0 @@ -#![doc = include_str!("../README.md")] -#![deny( - rustdoc::broken_intra_doc_links, - rustdoc::private_intra_doc_links, - rustdoc::missing_crate_level_docs, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_rust_codeblocks, - rustdoc::bare_urls, - rustdoc::invalid_html_tags -)] -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_lifetimes, - unused_import_braces, - unreachable_pub, - clippy::dbg_macro -)] - -use proc_macro::TokenStream as StdTokenStream; -use proc_macro2::TokenStream; -use syn::{parse_quote, GenericParam, Generics}; - -mod packet; - -#[proc_macro_derive(Packet, attributes(packet))] -pub fn derive_packet(item: StdTokenStream) -> StdTokenStream { - match packet::derive_packet(item.into()) { - Ok(tokens) => tokens.into(), - Err(e) => e.into_compile_error().into(), - } -} - -fn add_trait_bounds(generics: &mut Generics, trait_: TokenStream) { - for param in &mut generics.params { - if let GenericParam::Type(type_param) = param { - type_param.bounds.push(parse_quote!(#trait_)) - } - } -} diff --git a/crates/valence_player_list/Cargo.toml b/crates/valence_player_list/Cargo.toml index d08cc184e..baf933fb1 100644 --- a/crates/valence_player_list/Cargo.toml +++ b/crates/valence_player_list/Cargo.toml @@ -12,4 +12,3 @@ valence_core.workspace = true valence_client.workspace = true valence_layer.workspace = true uuid.workspace = true -valence_packet.workspace = true diff --git a/crates/valence_packet/Cargo.toml b/crates/valence_protocol/Cargo.toml similarity index 51% rename from crates/valence_packet/Cargo.toml rename to crates/valence_protocol/Cargo.toml index 93c7ffe0c..322fc699a 100644 --- a/crates/valence_packet/Cargo.toml +++ b/crates/valence_protocol/Cargo.toml @@ -1,38 +1,37 @@ [package] -name = "valence_packet" +name = "valence_protocol" version.workspace = true edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true [features] encryption = ["dep:aes", "dep:cfb8"] -compression = ["dep:flate2"] +compression = ["dep:flate2"] [dependencies] -valence_core.workspace = true -valence_nbt.workspace = true -valence_build_utils.workspace = true -valence_packet_macros.workspace = true +bevy_ecs.workspace = true # TODO: make this optional +valence_math.workspace = true +valence_generated.workspace = true +valence_text.workspace = true +valence_nbt = { workspace = true, features = ["binary"] } +valence_protocol_macros.workspace = true anyhow.workspace = true -bitfield-struct.workspace = true +thiserror.workspace = true +serde = { workspace = true, features = ["derive"] } byteorder.workspace = true -valence_math.workspace = true -uuid = { workspace = true, features = ["serde"] } -bytes.workspace = true +uuid.workspace = true +valence_ident.workspace = true +base64.workspace = true +url.workspace = true +serde_json.workspace = true tracing.workspace = true -bevy_ecs.workspace = true -serde = { workspace = true, features = ["derive"] } +bytes.workspace = true +bitfield-struct.workspace = true cfb8 = { workspace = true, optional = true } flate2 = { workspace = true, optional = true } aes = { workspace = true, optional = true } [dev-dependencies] rand.workspace = true - -[build-dependencies] -anyhow.workspace = true -heck.workspace = true -proc-macro2.workspace = true -quote.workspace = true -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true -valence_build_utils.workspace = true diff --git a/crates/valence_core/src/protocol/array.rs b/crates/valence_protocol/src/array.rs similarity index 93% rename from crates/valence_core/src/protocol/array.rs rename to crates/valence_protocol/src/array.rs index 957eee997..c2253fd1a 100644 --- a/crates/valence_core/src/protocol/array.rs +++ b/crates/valence_protocol/src/array.rs @@ -2,8 +2,8 @@ use std::io::Write; use anyhow::ensure; -use crate::protocol::var_int::VarInt; -use crate::protocol::{Decode, Encode}; +use crate::var_int::VarInt; +use crate::{Decode, Encode}; /// A fixed-size array encoded and decoded with a [`VarInt`] length prefix. /// diff --git a/crates/valence_core/src/block_pos.rs b/crates/valence_protocol/src/block_pos.rs similarity index 97% rename from crates/valence_core/src/block_pos.rs rename to crates/valence_protocol/src/block_pos.rs index 8cac7b13d..4d016917e 100644 --- a/crates/valence_core/src/block_pos.rs +++ b/crates/valence_protocol/src/block_pos.rs @@ -6,7 +6,7 @@ use valence_math::DVec3; use crate::chunk_pos::ChunkPos; use crate::direction::Direction; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; /// Represents an absolute block position in world space. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] @@ -39,8 +39,8 @@ impl BlockPos { /// direction. /// /// ``` - /// use valence_core::block_pos::BlockPos; - /// use valence_core::direction::Direction; + /// use valence_protocol::block_pos::BlockPos; + /// use valence_protocol::direction::Direction; /// /// let pos = BlockPos::new(0, 0, 0); /// let adj = pos.get_in_direction(Direction::South); diff --git a/crates/valence_core/src/protocol/byte_angle.rs b/crates/valence_protocol/src/byte_angle.rs similarity index 95% rename from crates/valence_core/src/protocol/byte_angle.rs rename to crates/valence_protocol/src/byte_angle.rs index c65b3c675..ff91e8a88 100644 --- a/crates/valence_core/src/protocol/byte_angle.rs +++ b/crates/valence_protocol/src/byte_angle.rs @@ -1,7 +1,7 @@ use std::f32::consts::TAU; use std::io::Write; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; /// Represents an angle in steps of 1/256 of a full turn. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] diff --git a/crates/valence_protocol/src/chunk_pos.rs b/crates/valence_protocol/src/chunk_pos.rs new file mode 100644 index 000000000..99ab8cf7b --- /dev/null +++ b/crates/valence_protocol/src/chunk_pos.rs @@ -0,0 +1,74 @@ +use valence_math::DVec3; + +use crate::block_pos::BlockPos; +use crate::{Decode, Encode}; + +/// The X and Z position of a chunk. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug, Encode, Decode)] +pub struct ChunkPos { + /// The X position of the chunk. + pub x: i32, + /// The Z position of the chunk. + pub z: i32, +} + +impl ChunkPos { + /// Constructs a new chunk position. + pub const fn new(x: i32, z: i32) -> Self { + Self { x, z } + } + + /// Constructs a chunk position from a position in world space. Only the `x` + /// and `z` components are used. + pub fn from_pos(pos: DVec3) -> Self { + Self::new((pos.x / 16.0).floor() as i32, (pos.z / 16.0).floor() as i32) + } + + pub const fn from_block_pos(pos: BlockPos) -> Self { + Self::new(pos.x.div_euclid(16), pos.z.div_euclid(16)) + } + + pub const fn distance_squared(self, other: Self) -> u64 { + let diff_x = other.x as i64 - self.x as i64; + let diff_z = other.z as i64 - self.z as i64; + + (diff_x * diff_x + diff_z * diff_z) as u64 + } +} + +impl From<(i32, i32)> for ChunkPos { + fn from((x, z): (i32, i32)) -> Self { + Self { x, z } + } +} + +impl From for (i32, i32) { + fn from(pos: ChunkPos) -> Self { + (pos.x, pos.z) + } +} + +impl From<[i32; 2]> for ChunkPos { + fn from([x, z]: [i32; 2]) -> Self { + Self { x, z } + } +} + +impl From for [i32; 2] { + fn from(pos: ChunkPos) -> Self { + [pos.x, pos.z] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chunk_pos_round_trip_conv() { + let p = ChunkPos::new(rand::random(), rand::random()); + + assert_eq!(ChunkPos::from(<(i32, i32)>::from(p)), p); + assert_eq!(ChunkPos::from(<[i32; 2]>::from(p)), p); + } +} diff --git a/crates/valence_core/src/chunk_pos.rs b/crates/valence_protocol/src/chunk_view.rs similarity index 61% rename from crates/valence_core/src/chunk_pos.rs rename to crates/valence_protocol/src/chunk_view.rs index 0d7c5601d..9d1b43e71 100644 --- a/crates/valence_core/src/chunk_pos.rs +++ b/crates/valence_protocol/src/chunk_view.rs @@ -1,66 +1,8 @@ -use valence_math::DVec3; +// TODO: move this module out of `valence_protocol`. -use crate::block_pos::BlockPos; -use crate::protocol::{Decode, Encode}; +use valence_generated::chunk_view::{CHUNK_VIEW_LUT, EXTRA_VIEW_RADIUS, MAX_VIEW_DIST}; -/// The X and Z position of a chunk. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug, Encode, Decode)] -pub struct ChunkPos { - /// The X position of the chunk. - pub x: i32, - /// The Z position of the chunk. - pub z: i32, -} - -impl ChunkPos { - /// Constructs a new chunk position. - pub const fn new(x: i32, z: i32) -> Self { - Self { x, z } - } - - /// Constructs a chunk position from a position in world space. Only the `x` - /// and `z` components are used. - pub fn from_pos(pos: DVec3) -> Self { - Self::new((pos.x / 16.0).floor() as i32, (pos.z / 16.0).floor() as i32) - } - - pub const fn from_block_pos(pos: BlockPos) -> Self { - Self::new(pos.x.div_euclid(16), pos.z.div_euclid(16)) - } - - pub const fn distance_squared(self, other: Self) -> u64 { - let diff_x = other.x as i64 - self.x as i64; - let diff_z = other.z as i64 - self.z as i64; - - (diff_x * diff_x + diff_z * diff_z) as u64 - } -} - -impl From<(i32, i32)> for ChunkPos { - fn from((x, z): (i32, i32)) -> Self { - Self { x, z } - } -} - -impl From for (i32, i32) { - fn from(pos: ChunkPos) -> Self { - (pos.x, pos.z) - } -} - -impl From<[i32; 2]> for ChunkPos { - fn from([x, z]: [i32; 2]) -> Self { - Self { x, z } - } -} - -impl From for [i32; 2] { - fn from(pos: ChunkPos) -> Self { - [pos.x, pos.z] - } -} - -include!(concat!(env!("OUT_DIR"), "/chunk_pos.rs")); +use crate::chunk_pos::ChunkPos; /// Represents the set of all chunk positions that a client can see, defined by /// a center chunk position `pos` and view distance `dist`. @@ -123,7 +65,8 @@ impl ChunkView { /// # Examples /// /// ``` - /// use valence_core::chunk_pos::{ChunkPos, ChunkView}; + /// use valence_protocol::chunk_pos::ChunkPos; + /// use valence_protocol::chunk_view::ChunkView; /// /// let view = ChunkView::new(ChunkPos::new(5, -4), 16); /// let (min, max) = view.bounding_box(); @@ -160,12 +103,4 @@ mod tests { } } } - - #[test] - fn chunk_pos_round_trip_conv() { - let p = ChunkPos::new(rand::random(), rand::random()); - - assert_eq!(ChunkPos::from(<(i32, i32)>::from(p)), p); - assert_eq!(ChunkPos::from(<[i32; 2]>::from(p)), p); - } } diff --git a/crates/valence_packet/src/protocol/decode.rs b/crates/valence_protocol/src/decode.rs similarity index 97% rename from crates/valence_packet/src/protocol/decode.rs rename to crates/valence_protocol/src/decode.rs index bbdcec8cb..1b73da61a 100644 --- a/crates/valence_packet/src/protocol/decode.rs +++ b/crates/valence_protocol/src/decode.rs @@ -4,10 +4,9 @@ use aes::cipher::generic_array::GenericArray; use aes::cipher::{BlockDecryptMut, BlockSizeUser, KeyIvInit}; use anyhow::{bail, ensure, Context}; use bytes::{Buf, BytesMut}; -use valence_core::protocol::Decode; -use crate::protocol::var_int::{VarInt, VarIntDecodeError}; -use crate::protocol::{Packet, MAX_PACKET_SIZE}; +use crate::var_int::{VarInt, VarIntDecodeError}; +use crate::{Decode, Packet, MAX_PACKET_SIZE}; /// The AES block cipher with a 128 bit key, using the CFB-8 mode of /// operation. diff --git a/crates/valence_core/src/difficulty.rs b/crates/valence_protocol/src/difficulty.rs similarity index 77% rename from crates/valence_core/src/difficulty.rs rename to crates/valence_protocol/src/difficulty.rs index b3d3d7c95..e61fa42b5 100644 --- a/crates/valence_core/src/difficulty.rs +++ b/crates/valence_protocol/src/difficulty.rs @@ -1,4 +1,4 @@ -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Encode, Decode)] pub enum Difficulty { diff --git a/crates/valence_core/src/direction.rs b/crates/valence_protocol/src/direction.rs similarity index 86% rename from crates/valence_core/src/direction.rs rename to crates/valence_protocol/src/direction.rs index 8562d8fed..faa454bc2 100644 --- a/crates/valence_core/src/direction.rs +++ b/crates/valence_protocol/src/direction.rs @@ -1,6 +1,6 @@ use bevy_ecs::prelude::*; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Encode, Decode, Component)] pub enum Direction { diff --git a/crates/valence_packet/src/protocol/encode.rs b/crates/valence_protocol/src/encode.rs similarity index 98% rename from crates/valence_packet/src/protocol/encode.rs rename to crates/valence_protocol/src/encode.rs index 5e21a2380..5b958a193 100644 --- a/crates/valence_packet/src/protocol/encode.rs +++ b/crates/valence_protocol/src/encode.rs @@ -5,12 +5,11 @@ use aes::cipher::generic_array::GenericArray; #[cfg(feature = "encryption")] use aes::cipher::{BlockEncryptMut, BlockSizeUser, KeyIvInit}; use anyhow::ensure; -use bevy_ecs::world::Mut; use bytes::{BufMut, BytesMut}; use tracing::warn; -use crate::protocol::var_int::VarInt; -use crate::protocol::{Encode, Packet, MAX_PACKET_SIZE}; +use crate::var_int::VarInt; +use crate::{Encode, Packet, MAX_PACKET_SIZE}; /// The AES block cipher with a 128 bit key, using the CFB-8 mode of /// operation. @@ -216,7 +215,7 @@ impl WritePacket for &mut W { } } -impl WritePacket for Mut<'_, T> { +impl WritePacket for bevy_ecs::world::Mut<'_, T> { fn write_packet_fallible

(&mut self, packet: &P) -> anyhow::Result<()> where P: Packet + Encode, diff --git a/crates/valence_core/src/game_mode.rs b/crates/valence_protocol/src/game_mode.rs similarity index 83% rename from crates/valence_core/src/game_mode.rs rename to crates/valence_protocol/src/game_mode.rs index c23c2a6a8..b6f061364 100644 --- a/crates/valence_core/src/game_mode.rs +++ b/crates/valence_protocol/src/game_mode.rs @@ -1,6 +1,6 @@ use bevy_ecs::prelude::*; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Encode, Decode, Component)] pub enum GameMode { diff --git a/crates/valence_core/src/protocol/global_pos.rs b/crates/valence_protocol/src/global_pos.rs similarity index 76% rename from crates/valence_core/src/protocol/global_pos.rs rename to crates/valence_protocol/src/global_pos.rs index 2136b941b..37ae89956 100644 --- a/crates/valence_core/src/protocol/global_pos.rs +++ b/crates/valence_protocol/src/global_pos.rs @@ -1,8 +1,9 @@ use std::borrow::Cow; +use valence_ident::Ident; + use crate::block_pos::BlockPos; -use crate::ident::Ident; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)] pub struct GlobalPos<'a> { diff --git a/crates/valence_core/src/hand.rs b/crates/valence_protocol/src/hand.rs similarity index 75% rename from crates/valence_core/src/hand.rs rename to crates/valence_protocol/src/hand.rs index 957a01cf5..b2536ddf2 100644 --- a/crates/valence_core/src/hand.rs +++ b/crates/valence_protocol/src/hand.rs @@ -1,4 +1,4 @@ -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; #[derive(Copy, Clone, PartialEq, Eq, Default, Debug, Encode, Decode)] pub enum Hand { diff --git a/crates/valence_core/src/protocol/impls.rs b/crates/valence_protocol/src/impls.rs similarity index 87% rename from crates/valence_core/src/protocol/impls.rs rename to crates/valence_protocol/src/impls.rs index 3a026f6c2..857634693 100644 --- a/crates/valence_core/src/protocol/impls.rs +++ b/crates/valence_protocol/src/impls.rs @@ -1,4 +1,4 @@ -//! [`Encode`] and [`Decode`] impls on foreign types. +//! Implementations of [`Encode`] and [`Decode`] on foreign types. use core::slice; use std::borrow::Cow; @@ -8,13 +8,18 @@ use std::io::Write; use std::mem; use std::mem::MaybeUninit; use std::rc::Rc; +use std::str::FromStr; use std::sync::Arc; -use anyhow::{ensure, Result}; +use anyhow::{ensure, Context, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use uuid::Uuid; +use valence_generated::block::{BlockEntityKind, BlockKind, BlockState}; +use valence_generated::item::ItemKind; +use valence_ident::{Ident, IdentError}; use valence_math::*; use valence_nbt::Compound; +use valence_text::Text; use super::var_int::VarInt; use super::{Decode, Encode, MAX_PACKET_SIZE}; @@ -777,3 +782,93 @@ impl Decode<'_> for Compound { Ok(Self::from_binary(r)?.0) } } + +impl Encode for Ident { + fn encode(&self, w: impl Write) -> anyhow::Result<()> { + self.as_ref().encode(w) + } +} + +impl<'a, S> Decode<'a> for Ident +where + S: Decode<'a>, + Ident: TryFrom, +{ + fn decode(r: &mut &'a [u8]) -> anyhow::Result { + Ok(Ident::try_from(S::decode(r)?)?) + } +} + +impl Encode for Text { + fn encode(&self, w: impl Write) -> anyhow::Result<()> { + serde_json::to_string(self) + .context("encoding text JSON")? + .encode(w) + } +} + +impl Decode<'_> for Text { + fn decode(r: &mut &[u8]) -> anyhow::Result { + let str = <&str>::decode(r)?; + + Self::from_str(str).context("decoding text JSON") + } +} + +impl Encode for BlockState { + fn encode(&self, w: impl Write) -> anyhow::Result<()> { + VarInt(self.to_raw() as i32).encode(w) + } +} + +impl Decode<'_> for BlockState { + fn decode(r: &mut &[u8]) -> anyhow::Result { + let id = VarInt::decode(r)?.0; + let errmsg = "invalid block state ID"; + + BlockState::from_raw(id.try_into().context(errmsg)?).context(errmsg) + } +} + +impl Encode for BlockKind { + fn encode(&self, w: impl Write) -> anyhow::Result<()> { + VarInt(self.to_raw() as i32).encode(w) + } +} + +impl Decode<'_> for BlockKind { + fn decode(r: &mut &[u8]) -> anyhow::Result { + let id = VarInt::decode(r)?.0; + let errmsg = "invalid block kind ID"; + + BlockKind::from_raw(id.try_into().context(errmsg)?).context(errmsg) + } +} + +impl Encode for BlockEntityKind { + fn encode(&self, w: impl Write) -> anyhow::Result<()> { + VarInt(self.id() as i32).encode(w) + } +} + +impl<'a> Decode<'a> for BlockEntityKind { + fn decode(r: &mut &'a [u8]) -> anyhow::Result { + let id = VarInt::decode(r)?; + Self::from_id(id.0 as u32).with_context(|| format!("id {}", id.0)) + } +} + +impl Encode for ItemKind { + fn encode(&self, w: impl Write) -> anyhow::Result<()> { + VarInt(self.to_raw() as i32).encode(w) + } +} + +impl Decode<'_> for ItemKind { + fn decode(r: &mut &[u8]) -> anyhow::Result { + let id = VarInt::decode(r)?.0; + let errmsg = "invalid item ID"; + + ItemKind::from_raw(id.try_into().context(errmsg)?).context(errmsg) + } +} diff --git a/crates/valence_core/src/item.rs b/crates/valence_protocol/src/item.rs similarity index 69% rename from crates/valence_core/src/item.rs rename to crates/valence_protocol/src/item.rs index 9d3814a28..d9e3936cc 100644 --- a/crates/valence_core/src/item.rs +++ b/crates/valence_protocol/src/item.rs @@ -1,12 +1,10 @@ use std::io::Write; -use anyhow::{ensure, Context}; +use anyhow::ensure; +pub use valence_generated::item::ItemKind; use valence_nbt::Compound; -use crate::protocol::var_int::VarInt; -use crate::protocol::{Decode, Encode}; - -include!(concat!(env!("OUT_DIR"), "/item.rs")); +use crate::{Decode, Encode}; #[derive(Clone, PartialEq, Debug)] pub struct ItemStack { @@ -115,52 +113,15 @@ impl Decode<'_> for Option { } } -impl Encode for ItemKind { - fn encode(&self, w: impl Write) -> anyhow::Result<()> { - VarInt(self.to_raw() as i32).encode(w) - } -} - -impl Decode<'_> for ItemKind { - fn decode(r: &mut &[u8]) -> anyhow::Result { - let id = VarInt::decode(r)?.0; - let errmsg = "invalid item ID"; - - ItemKind::from_raw(id.try_into().context(errmsg)?).context(errmsg) - } -} - -/* #[cfg(test)] mod tests { use super::*; - use crate::block::BlockKind; - - #[test] - fn item_kind_to_block_kind() { - assert_eq!( - ItemKind::Cauldron.to_block_kind(), - Some(BlockKind::Cauldron) - ); - } - - #[test] - fn block_state_to_item() { - assert_eq!(BlockKind::Torch.to_item_kind(), ItemKind::Torch); - assert_eq!(BlockKind::WallTorch.to_item_kind(), ItemKind::Torch); - - assert_eq!(BlockKind::Cauldron.to_item_kind(), ItemKind::Cauldron); - assert_eq!(BlockKind::LavaCauldron.to_item_kind(), ItemKind::Cauldron); - - assert_eq!(BlockKind::NetherPortal.to_item_kind(), ItemKind::Air); - } #[test] fn item_stack_clamps_count() { let mut stack = ItemStack::new(ItemKind::Stone, 200, None); - assert_eq!(stack.count, STACK_MAX); + assert_eq!(stack.count, ItemStack::STACK_MAX); stack.set_count(201); - assert_eq!(stack.count, STACK_MAX); + assert_eq!(stack.count, ItemStack::STACK_MAX); } } -*/ diff --git a/crates/valence_protocol/src/lib.rs b/crates/valence_protocol/src/lib.rs new file mode 100644 index 000000000..3a5fa94bc --- /dev/null +++ b/crates/valence_protocol/src/lib.rs @@ -0,0 +1,397 @@ +use std::io::Write; + +use anyhow::Context; +pub use valence_protocol_macros::{Decode, Encode, Packet}; +use var_int::VarInt; + +/// Used only by macros. Not public API. +#[doc(hidden)] +pub mod __private { + pub use anyhow::{anyhow, bail, ensure, Context, Result}; + + pub use crate::var_int::VarInt; + pub use crate::{Decode, Encode, Packet}; +} + +// This allows us to use our own proc macros internally. +extern crate self as valence_protocol; + +pub mod array; +pub mod block_pos; +pub mod byte_angle; +pub mod chunk_pos; +pub mod chunk_view; +pub mod decode; +pub mod difficulty; +pub mod direction; +pub mod encode; +pub mod game_mode; +pub mod global_pos; +pub mod hand; +mod impls; +pub mod item; +pub mod player_textures; +pub mod property; +pub mod raw; +pub mod sound; +pub mod var_int; +pub mod var_long; +pub use {valence_ident as ident, valence_math as math, valence_text as text}; +pub mod packets; + +/// The maximum number of bytes in a single Minecraft packet. +pub const MAX_PACKET_SIZE: i32 = 2097152; + +/// The Minecraft protocol version this library currently targets. +pub const PROTOCOL_VERSION: i32 = 763; + +/// The stringified name of the Minecraft version this library currently +/// targets. +pub const MINECRAFT_VERSION: &str = "1.20.1"; + +/// The `Encode` trait allows objects to be written to the Minecraft protocol. +/// It is the inverse of [`Decode`]. +/// +/// # Deriving +/// +/// This trait can be implemented automatically for structs and enums by using +/// the [`Encode`][macro] derive macro. All components of the type must +/// implement `Encode`. Components are encoded in the order they appear in the +/// type definition. +/// +/// For enums, the variant to encode is marked by a leading [`VarInt`] +/// discriminant (tag). The discriminant value can be changed using the `#[tag = +/// ...]` attribute on the variant in question. Discriminant values are assigned +/// to variants using rules similar to regular enum discriminants. +/// +/// ``` +/// use valence_protocol::Encode; +/// +/// #[derive(Encode)] +/// struct MyStruct<'a> { +/// first: i32, +/// second: &'a str, +/// third: [f64; 3], +/// } +/// +/// #[derive(Encode)] +/// enum MyEnum { +/// First, // tag = 0 +/// Second, // tag = 1 +/// #[packet(tag = 25)] +/// Third, // tag = 25 +/// Fourth, // tag = 26 +/// } +/// +/// let value = MyStruct { +/// first: 10, +/// second: "hello", +/// third: [1.5, 3.14, 2.718], +/// }; +/// +/// let mut buf = vec![]; +/// value.encode(&mut buf).unwrap(); +/// +/// println!("{buf:?}"); +/// ``` +/// +/// [macro]: valence_core_macros::Encode +/// [`VarInt`]: var_int::VarInt +pub trait Encode { + /// Writes this object to the provided writer. + /// + /// If this type also implements [`Decode`] then successful calls to this + /// function returning `Ok(())` must always successfully [`decode`] using + /// the data that was written to the writer. The exact number of bytes + /// that were originally written must be consumed during the decoding. + /// + /// [`decode`]: Decode::decode + fn encode(&self, w: impl Write) -> anyhow::Result<()>; + + /// Like [`Encode::encode`], except that a whole slice of values is encoded. + /// + /// This method must be semantically equivalent to encoding every element of + /// the slice in sequence with no leading length prefix (which is exactly + /// what the default implementation does), but a more efficient + /// implementation may be used. + /// + /// This optimization is very important for some types like `u8` where + /// [`write_all`] is used. Because impl specialization is unavailable in + /// stable Rust, we must make the slice specialization part of this trait. + /// + /// [`write_all`]: Write::write_all + fn encode_slice(slice: &[Self], mut w: impl Write) -> anyhow::Result<()> + where + Self: Sized, + { + for value in slice { + value.encode(&mut w)?; + } + + Ok(()) + } +} + +/// The `Decode` trait allows objects to be read from the Minecraft protocol. It +/// is the inverse of [`Encode`]. +/// +/// `Decode` is parameterized by a lifetime. This allows the decoded value to +/// borrow data from the byte slice it was read from. +/// +/// # Deriving +/// +/// This trait can be implemented automatically for structs and enums by using +/// the [`Decode`][macro] derive macro. All components of the type must +/// implement `Decode`. Components are decoded in the order they appear in the +/// type definition. +/// +/// For enums, the variant to decode is determined by a leading [`VarInt`] +/// discriminant (tag). The discriminant value can be changed using the `#[tag = +/// ...]` attribute on the variant in question. Discriminant values are assigned +/// to variants using rules similar to regular enum discriminants. +/// +/// ``` +/// use valence_protocol::Decode; +/// +/// #[derive(PartialEq, Debug, Decode)] +/// struct MyStruct { +/// first: i32, +/// second: MyEnum, +/// } +/// +/// #[derive(PartialEq, Debug, Decode)] +/// enum MyEnum { +/// First, // tag = 0 +/// Second, // tag = 1 +/// #[packet(tag = 25)] +/// Third, // tag = 25 +/// Fourth, // tag = 26 +/// } +/// +/// let mut r: &[u8] = &[0, 0, 0, 0, 26]; +/// +/// let value = MyStruct::decode(&mut r).unwrap(); +/// let expected = MyStruct { +/// first: 0, +/// second: MyEnum::Fourth, +/// }; +/// +/// assert_eq!(value, expected); +/// assert!(r.is_empty()); +/// ``` +/// +/// [macro]: valence_core_macros::Decode +/// [`VarInt`]: var_int::VarInt +pub trait Decode<'a>: Sized { + /// Reads this object from the provided byte slice. + /// + /// Implementations of `Decode` are expected to shrink the slice from the + /// front as bytes are read. + fn decode(r: &mut &'a [u8]) -> anyhow::Result; +} + +/// Types considered to be Minecraft packets. +/// +/// In serialized form, a packet begins with a [`VarInt`] packet ID followed by +/// the body of the packet. If present, the implementations of [`Encode`] and +/// [`Decode`] on `Self` are expected to only encode/decode the _body_ of this +/// packet without the leading ID. +pub trait Packet: std::fmt::Debug { + /// The leading VarInt ID of this packet. + const ID: i32; + /// The name of this packet for debugging purposes. + const NAME: &'static str; + /// The side this packet is intended for. + const SIDE: PacketSide; + /// The state in which this packet is used. + const STATE: PacketState; + + /// Encodes this packet's VarInt ID first, followed by the packet's body. + fn encode_with_id(&self, mut w: impl Write) -> anyhow::Result<()> + where + Self: Encode, + { + VarInt(Self::ID) + .encode(&mut w) + .context("failed to encode packet ID")?; + + self.encode(w) + } +} + +/// The side a packet is intended for +#[derive(Copy, Clone, PartialEq, Eq)] +pub enum PacketSide { + /// Server -> Client + Clientbound, + /// Client -> Server + Serverbound, +} + +/// The state which a packet is used +#[derive(Copy, Clone, PartialEq, Eq)] +pub enum PacketState { + Handshaking, + Status, + Login, + Play, +} + +#[allow(dead_code)] +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use bytes::BytesMut; + + use super::*; + use crate::block_pos::BlockPos; + use crate::decode::PacketDecoder; + use crate::encode::PacketEncoder; + use crate::hand::Hand; + use crate::ident::Ident; + use crate::item::{ItemKind, ItemStack}; + use crate::text::{IntoText, Text}; + use crate::var_int::VarInt; + use crate::var_long::VarLong; + + #[derive(Encode, Decode, Packet, Debug)] + #[packet(id = 1, side = PacketSide::Clientbound)] + struct RegularStruct { + foo: i32, + bar: bool, + baz: f64, + } + + #[derive(Encode, Decode, Packet, Debug)] + #[packet(id = 2, side = PacketSide::Clientbound)] + struct UnitStruct; + + #[derive(Encode, Decode, Packet, Debug)] + #[packet(id = 3, side = PacketSide::Clientbound)] + struct EmptyStruct {} + + #[derive(Encode, Decode, Packet, Debug)] + #[packet(id = 4, side = PacketSide::Clientbound)] + struct TupleStruct(i32, bool, f64); + + #[derive(Encode, Decode, Packet, Debug)] + #[packet(id = 5, side = PacketSide::Clientbound)] + struct StructWithGenerics<'z, T = ()> { + foo: &'z str, + bar: T, + } + + #[derive(Encode, Decode, Packet, Debug)] + #[packet(id = 6, side = PacketSide::Clientbound)] + struct TupleStructWithGenerics<'z, T = ()>(&'z str, i32, T); + + #[allow(unconditional_recursion, clippy::extra_unused_type_parameters)] + fn assert_has_impls<'a, T>() + where + T: Encode + Decode<'a> + Packet, + { + assert_has_impls::(); + assert_has_impls::(); + assert_has_impls::(); + assert_has_impls::(); + assert_has_impls::(); + assert_has_impls::(); + } + + #[test] + fn packet_name() { + assert_eq!(RegularStruct::NAME, "RegularStruct"); + assert_eq!(UnitStruct::NAME, "UnitStruct"); + assert_eq!(StructWithGenerics::<()>::NAME, "StructWithGenerics"); + } + + #[cfg(feature = "encryption")] + const CRYPT_KEY: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + + #[derive(PartialEq, Debug, Encode, Decode, Packet)] + #[packet(id = 42, side = PacketSide::Clientbound)] + struct TestPacket<'a> { + a: bool, + b: u8, + c: i32, + d: f32, + e: f64, + f: BlockPos, + g: Hand, + h: Ident>, + i: Option, + j: Text, + k: VarInt, + l: VarLong, + m: &'a str, + n: &'a [u8; 10], + o: [u128; 3], + } + + impl<'a> TestPacket<'a> { + fn new(string: &'a str) -> Self { + Self { + a: true, + b: 12, + c: -999, + d: 5.001, + e: 1e10, + f: BlockPos::new(1, 2, 3), + g: Hand::Off, + h: Ident::new("minecraft:whatever").unwrap(), + i: Some(ItemStack::new(ItemKind::WoodenSword, 12, None)), + j: "my ".into_text() + "fancy".italic() + " text", + k: VarInt(123), + l: VarLong(456), + m: string, + n: &[7; 10], + o: [123456789; 3], + } + } + } + + fn check_test_packet(dec: &mut PacketDecoder, string: &str) { + let frame = dec.try_next_packet().unwrap().unwrap(); + + let pkt = frame.decode::().unwrap(); + + assert_eq!(&pkt, &TestPacket::new(string)); + } + + #[test] + fn packets_round_trip() { + let mut buf = BytesMut::new(); + + let mut enc = PacketEncoder::new(); + + enc.append_packet(&TestPacket::new("first")).unwrap(); + #[cfg(feature = "compression")] + enc.set_compression(Some(0)); + enc.append_packet(&TestPacket::new("second")).unwrap(); + buf.unsplit(enc.take()); + #[cfg(feature = "encryption")] + enc.enable_encryption(&CRYPT_KEY); + enc.append_packet(&TestPacket::new("third")).unwrap(); + enc.prepend_packet(&TestPacket::new("fourth")).unwrap(); + + buf.unsplit(enc.take()); + + let mut dec = PacketDecoder::new(); + + dec.queue_bytes(buf); + + check_test_packet(&mut dec, "first"); + + #[cfg(feature = "compression")] + dec.set_compression(Some(0)); + + check_test_packet(&mut dec, "second"); + + #[cfg(feature = "encryption")] + dec.enable_encryption(&CRYPT_KEY); + + check_test_packet(&mut dec, "fourth"); + check_test_packet(&mut dec, "third"); + } +} diff --git a/crates/valence_protocol/src/packets.rs b/crates/valence_protocol/src/packets.rs new file mode 100644 index 000000000..1a3072dc1 --- /dev/null +++ b/crates/valence_protocol/src/packets.rs @@ -0,0 +1,18 @@ +use std::borrow::Cow; +use std::io::Write; + +use anyhow::bail; +use uuid::Uuid; +use valence_generated::packet_id; + +use crate::ident::Ident; +use crate::property::Property; +use crate::raw::RawBytes; +use crate::text::Text; +use crate::var_int::VarInt; +use crate::{Decode, Encode, Packet, PacketState}; + +pub mod handshaking; +pub mod login; +pub mod play; +pub mod status; diff --git a/crates/valence_packet/src/packets/handshaking.rs b/crates/valence_protocol/src/packets/handshaking.rs similarity index 100% rename from crates/valence_packet/src/packets/handshaking.rs rename to crates/valence_protocol/src/packets/handshaking.rs diff --git a/crates/valence_packet/src/packets/handshaking/handshake_c2s.rs b/crates/valence_protocol/src/packets/handshaking/handshake_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/handshaking/handshake_c2s.rs rename to crates/valence_protocol/src/packets/handshaking/handshake_c2s.rs diff --git a/crates/valence_packet/src/packets/login.rs b/crates/valence_protocol/src/packets/login.rs similarity index 100% rename from crates/valence_packet/src/packets/login.rs rename to crates/valence_protocol/src/packets/login.rs diff --git a/crates/valence_packet/src/packets/login/login_compression_s2c.rs b/crates/valence_protocol/src/packets/login/login_compression_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_compression_s2c.rs rename to crates/valence_protocol/src/packets/login/login_compression_s2c.rs diff --git a/crates/valence_packet/src/packets/login/login_disconnect_s2c.rs b/crates/valence_protocol/src/packets/login/login_disconnect_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_disconnect_s2c.rs rename to crates/valence_protocol/src/packets/login/login_disconnect_s2c.rs diff --git a/crates/valence_packet/src/packets/login/login_hello_c2s.rs b/crates/valence_protocol/src/packets/login/login_hello_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_hello_c2s.rs rename to crates/valence_protocol/src/packets/login/login_hello_c2s.rs diff --git a/crates/valence_packet/src/packets/login/login_hello_s2c.rs b/crates/valence_protocol/src/packets/login/login_hello_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_hello_s2c.rs rename to crates/valence_protocol/src/packets/login/login_hello_s2c.rs diff --git a/crates/valence_packet/src/packets/login/login_key_c2s.rs b/crates/valence_protocol/src/packets/login/login_key_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_key_c2s.rs rename to crates/valence_protocol/src/packets/login/login_key_c2s.rs diff --git a/crates/valence_packet/src/packets/login/login_query_request_s2c.rs b/crates/valence_protocol/src/packets/login/login_query_request_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_query_request_s2c.rs rename to crates/valence_protocol/src/packets/login/login_query_request_s2c.rs diff --git a/crates/valence_packet/src/packets/login/login_query_response_c2s.rs b/crates/valence_protocol/src/packets/login/login_query_response_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_query_response_c2s.rs rename to crates/valence_protocol/src/packets/login/login_query_response_c2s.rs diff --git a/crates/valence_packet/src/packets/login/login_success_s2c.rs b/crates/valence_protocol/src/packets/login/login_success_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/login/login_success_s2c.rs rename to crates/valence_protocol/src/packets/login/login_success_s2c.rs diff --git a/crates/valence_packet/src/packets/play.rs b/crates/valence_protocol/src/packets/play.rs similarity index 96% rename from crates/valence_packet/src/packets/play.rs rename to crates/valence_protocol/src/packets/play.rs index 7d83b50d8..ed5f7dbd4 100644 --- a/crates/valence_packet/src/packets/play.rs +++ b/crates/valence_protocol/src/packets/play.rs @@ -1,19 +1,19 @@ use bitfield_struct::bitfield; use byteorder::WriteBytesExt; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::ChunkPos; -use valence_core::difficulty::Difficulty; -use valence_core::direction::Direction; -use valence_core::game_mode::GameMode; -use valence_core::hand::Hand; -use valence_core::item::ItemStack; -use valence_core::protocol::byte_angle::ByteAngle; -use valence_core::protocol::global_pos::GlobalPos; -use valence_core::protocol::var_long::VarLong; use valence_math::{DVec3, IVec3, Vec3}; use valence_nbt::Compound; use super::*; +use crate::block_pos::BlockPos; +use crate::byte_angle::ByteAngle; +use crate::chunk_pos::ChunkPos; +use crate::difficulty::Difficulty; +use crate::direction::Direction; +use crate::game_mode::GameMode; +use crate::global_pos::GlobalPos; +use crate::hand::Hand; +use crate::item::ItemStack; +use crate::var_long::VarLong; pub mod advancement_tab_c2s; pub use advancement_tab_c2s::AdvancementTabC2s; diff --git a/crates/valence_packet/src/packets/play/advancement_tab_c2s.rs b/crates/valence_protocol/src/packets/play/advancement_tab_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/advancement_tab_c2s.rs rename to crates/valence_protocol/src/packets/play/advancement_tab_c2s.rs diff --git a/crates/valence_packet/src/packets/play/advancement_update_s2c.rs b/crates/valence_protocol/src/packets/play/advancement_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/advancement_update_s2c.rs rename to crates/valence_protocol/src/packets/play/advancement_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/block_breaking_progress_s2c.rs b/crates/valence_protocol/src/packets/play/block_breaking_progress_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/block_breaking_progress_s2c.rs rename to crates/valence_protocol/src/packets/play/block_breaking_progress_s2c.rs diff --git a/crates/valence_packet/src/packets/play/block_entity_update_s2c.rs b/crates/valence_protocol/src/packets/play/block_entity_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/block_entity_update_s2c.rs rename to crates/valence_protocol/src/packets/play/block_entity_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/block_event_s2c.rs b/crates/valence_protocol/src/packets/play/block_event_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/block_event_s2c.rs rename to crates/valence_protocol/src/packets/play/block_event_s2c.rs diff --git a/crates/valence_packet/src/packets/play/block_update_s2c.rs b/crates/valence_protocol/src/packets/play/block_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/block_update_s2c.rs rename to crates/valence_protocol/src/packets/play/block_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/boat_paddle_state_c2s.rs b/crates/valence_protocol/src/packets/play/boat_paddle_state_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/boat_paddle_state_c2s.rs rename to crates/valence_protocol/src/packets/play/boat_paddle_state_c2s.rs diff --git a/crates/valence_packet/src/packets/play/book_update_c2s.rs b/crates/valence_protocol/src/packets/play/book_update_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/book_update_c2s.rs rename to crates/valence_protocol/src/packets/play/book_update_c2s.rs diff --git a/crates/valence_packet/src/packets/play/boss_bar_s2c.rs b/crates/valence_protocol/src/packets/play/boss_bar_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/boss_bar_s2c.rs rename to crates/valence_protocol/src/packets/play/boss_bar_s2c.rs diff --git a/crates/valence_packet/src/packets/play/bundle_splitter_s2c.rs b/crates/valence_protocol/src/packets/play/bundle_splitter_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/bundle_splitter_s2c.rs rename to crates/valence_protocol/src/packets/play/bundle_splitter_s2c.rs diff --git a/crates/valence_packet/src/packets/play/button_click_c2s.rs b/crates/valence_protocol/src/packets/play/button_click_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/button_click_c2s.rs rename to crates/valence_protocol/src/packets/play/button_click_c2s.rs diff --git a/crates/valence_packet/src/packets/play/chat_message_c2s.rs b/crates/valence_protocol/src/packets/play/chat_message_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chat_message_c2s.rs rename to crates/valence_protocol/src/packets/play/chat_message_c2s.rs diff --git a/crates/valence_packet/src/packets/play/chat_message_s2c.rs b/crates/valence_protocol/src/packets/play/chat_message_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chat_message_s2c.rs rename to crates/valence_protocol/src/packets/play/chat_message_s2c.rs diff --git a/crates/valence_packet/src/packets/play/chat_suggestions_s2c.rs b/crates/valence_protocol/src/packets/play/chat_suggestions_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chat_suggestions_s2c.rs rename to crates/valence_protocol/src/packets/play/chat_suggestions_s2c.rs diff --git a/crates/valence_packet/src/packets/play/chunk_biome_data_s2c.rs b/crates/valence_protocol/src/packets/play/chunk_biome_data_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chunk_biome_data_s2c.rs rename to crates/valence_protocol/src/packets/play/chunk_biome_data_s2c.rs diff --git a/crates/valence_packet/src/packets/play/chunk_data_s2c.rs b/crates/valence_protocol/src/packets/play/chunk_data_s2c.rs similarity index 93% rename from crates/valence_packet/src/packets/play/chunk_data_s2c.rs rename to crates/valence_protocol/src/packets/play/chunk_data_s2c.rs index 6d7226fc2..91617359b 100644 --- a/crates/valence_packet/src/packets/play/chunk_data_s2c.rs +++ b/crates/valence_protocol/src/packets/play/chunk_data_s2c.rs @@ -1,6 +1,5 @@ -use valence_core::protocol::array::LengthPrefixedArray; - use super::*; +use crate::array::LengthPrefixedArray; #[derive(Clone, Debug, Encode, Decode, Packet)] #[packet(id = packet_id::CHUNK_DATA_S2C)] diff --git a/crates/valence_packet/src/packets/play/chunk_delta_update_s2c.rs b/crates/valence_protocol/src/packets/play/chunk_delta_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chunk_delta_update_s2c.rs rename to crates/valence_protocol/src/packets/play/chunk_delta_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/chunk_load_distance_s2c.rs b/crates/valence_protocol/src/packets/play/chunk_load_distance_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chunk_load_distance_s2c.rs rename to crates/valence_protocol/src/packets/play/chunk_load_distance_s2c.rs diff --git a/crates/valence_packet/src/packets/play/chunk_render_distance_center_s2c.rs b/crates/valence_protocol/src/packets/play/chunk_render_distance_center_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/chunk_render_distance_center_s2c.rs rename to crates/valence_protocol/src/packets/play/chunk_render_distance_center_s2c.rs diff --git a/crates/valence_packet/src/packets/play/clear_title_s2c.rs b/crates/valence_protocol/src/packets/play/clear_title_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/clear_title_s2c.rs rename to crates/valence_protocol/src/packets/play/clear_title_s2c.rs diff --git a/crates/valence_packet/src/packets/play/click_slot_c2s.rs b/crates/valence_protocol/src/packets/play/click_slot_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/click_slot_c2s.rs rename to crates/valence_protocol/src/packets/play/click_slot_c2s.rs diff --git a/crates/valence_packet/src/packets/play/client_command_c2s.rs b/crates/valence_protocol/src/packets/play/client_command_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/client_command_c2s.rs rename to crates/valence_protocol/src/packets/play/client_command_c2s.rs diff --git a/crates/valence_packet/src/packets/play/client_settings_c2s.rs b/crates/valence_protocol/src/packets/play/client_settings_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/client_settings_c2s.rs rename to crates/valence_protocol/src/packets/play/client_settings_c2s.rs diff --git a/crates/valence_packet/src/packets/play/client_status_c2s.rs b/crates/valence_protocol/src/packets/play/client_status_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/client_status_c2s.rs rename to crates/valence_protocol/src/packets/play/client_status_c2s.rs diff --git a/crates/valence_packet/src/packets/play/close_handled_screen_c2s.rs b/crates/valence_protocol/src/packets/play/close_handled_screen_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/close_handled_screen_c2s.rs rename to crates/valence_protocol/src/packets/play/close_handled_screen_c2s.rs diff --git a/crates/valence_packet/src/packets/play/close_screen_s2c.rs b/crates/valence_protocol/src/packets/play/close_screen_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/close_screen_s2c.rs rename to crates/valence_protocol/src/packets/play/close_screen_s2c.rs diff --git a/crates/valence_packet/src/packets/play/command_execution_c2s.rs b/crates/valence_protocol/src/packets/play/command_execution_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/command_execution_c2s.rs rename to crates/valence_protocol/src/packets/play/command_execution_c2s.rs diff --git a/crates/valence_packet/src/packets/play/command_suggestions_s2c.rs b/crates/valence_protocol/src/packets/play/command_suggestions_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/command_suggestions_s2c.rs rename to crates/valence_protocol/src/packets/play/command_suggestions_s2c.rs diff --git a/crates/valence_packet/src/packets/play/command_tree_s2c.rs b/crates/valence_protocol/src/packets/play/command_tree_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/command_tree_s2c.rs rename to crates/valence_protocol/src/packets/play/command_tree_s2c.rs diff --git a/crates/valence_packet/src/packets/play/cooldown_update_s2c.rs b/crates/valence_protocol/src/packets/play/cooldown_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/cooldown_update_s2c.rs rename to crates/valence_protocol/src/packets/play/cooldown_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/craft_failed_response_s2c.rs b/crates/valence_protocol/src/packets/play/craft_failed_response_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/craft_failed_response_s2c.rs rename to crates/valence_protocol/src/packets/play/craft_failed_response_s2c.rs diff --git a/crates/valence_packet/src/packets/play/craft_request_c2s.rs b/crates/valence_protocol/src/packets/play/craft_request_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/craft_request_c2s.rs rename to crates/valence_protocol/src/packets/play/craft_request_c2s.rs diff --git a/crates/valence_packet/src/packets/play/creative_inventory_action_c2s.rs b/crates/valence_protocol/src/packets/play/creative_inventory_action_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/creative_inventory_action_c2s.rs rename to crates/valence_protocol/src/packets/play/creative_inventory_action_c2s.rs diff --git a/crates/valence_packet/src/packets/play/custom_payload_c2s.rs b/crates/valence_protocol/src/packets/play/custom_payload_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/custom_payload_c2s.rs rename to crates/valence_protocol/src/packets/play/custom_payload_c2s.rs diff --git a/crates/valence_packet/src/packets/play/custom_payload_s2c.rs b/crates/valence_protocol/src/packets/play/custom_payload_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/custom_payload_s2c.rs rename to crates/valence_protocol/src/packets/play/custom_payload_s2c.rs diff --git a/crates/valence_packet/src/packets/play/damage_tilt_s2c.rs b/crates/valence_protocol/src/packets/play/damage_tilt_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/damage_tilt_s2c.rs rename to crates/valence_protocol/src/packets/play/damage_tilt_s2c.rs diff --git a/crates/valence_packet/src/packets/play/death_message_s2c.rs b/crates/valence_protocol/src/packets/play/death_message_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/death_message_s2c.rs rename to crates/valence_protocol/src/packets/play/death_message_s2c.rs diff --git a/crates/valence_packet/src/packets/play/difficulty_s2c.rs b/crates/valence_protocol/src/packets/play/difficulty_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/difficulty_s2c.rs rename to crates/valence_protocol/src/packets/play/difficulty_s2c.rs diff --git a/crates/valence_packet/src/packets/play/disconnect_s2c.rs b/crates/valence_protocol/src/packets/play/disconnect_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/disconnect_s2c.rs rename to crates/valence_protocol/src/packets/play/disconnect_s2c.rs diff --git a/crates/valence_packet/src/packets/play/end_combat_s2c.rs b/crates/valence_protocol/src/packets/play/end_combat_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/end_combat_s2c.rs rename to crates/valence_protocol/src/packets/play/end_combat_s2c.rs diff --git a/crates/valence_packet/src/packets/play/enter_combat_s2c.rs b/crates/valence_protocol/src/packets/play/enter_combat_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/enter_combat_s2c.rs rename to crates/valence_protocol/src/packets/play/enter_combat_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entities_destroy_s2c.rs b/crates/valence_protocol/src/packets/play/entities_destroy_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entities_destroy_s2c.rs rename to crates/valence_protocol/src/packets/play/entities_destroy_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_animation_s2c.rs b/crates/valence_protocol/src/packets/play/entity_animation_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_animation_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_animation_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_attach_s2c.rs b/crates/valence_protocol/src/packets/play/entity_attach_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_attach_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_attach_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_attributes_s2c.rs b/crates/valence_protocol/src/packets/play/entity_attributes_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_attributes_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_attributes_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_damage_s2c.rs b/crates/valence_protocol/src/packets/play/entity_damage_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_damage_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_damage_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_equipment_update_s2c.rs b/crates/valence_protocol/src/packets/play/entity_equipment_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_equipment_update_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_equipment_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_passengers_set_s2c.rs b/crates/valence_protocol/src/packets/play/entity_passengers_set_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_passengers_set_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_passengers_set_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_position_s2c.rs b/crates/valence_protocol/src/packets/play/entity_position_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_position_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_position_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_set_head_yaw_s2c.rs b/crates/valence_protocol/src/packets/play/entity_set_head_yaw_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_set_head_yaw_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_set_head_yaw_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_spawn_s2c.rs b/crates/valence_protocol/src/packets/play/entity_spawn_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_spawn_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_spawn_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_status_effect_s2c.rs b/crates/valence_protocol/src/packets/play/entity_status_effect_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_status_effect_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_status_effect_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_status_s2c.rs b/crates/valence_protocol/src/packets/play/entity_status_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_status_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_status_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_tracker_update_s2c.rs b/crates/valence_protocol/src/packets/play/entity_tracker_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_tracker_update_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_tracker_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/entity_velocity_update_s2c.rs b/crates/valence_protocol/src/packets/play/entity_velocity_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/entity_velocity_update_s2c.rs rename to crates/valence_protocol/src/packets/play/entity_velocity_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/experience_bar_update_s2c.rs b/crates/valence_protocol/src/packets/play/experience_bar_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/experience_bar_update_s2c.rs rename to crates/valence_protocol/src/packets/play/experience_bar_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/experience_orb_spawn_s2c.rs b/crates/valence_protocol/src/packets/play/experience_orb_spawn_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/experience_orb_spawn_s2c.rs rename to crates/valence_protocol/src/packets/play/experience_orb_spawn_s2c.rs diff --git a/crates/valence_packet/src/packets/play/explosion_s2c.rs b/crates/valence_protocol/src/packets/play/explosion_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/explosion_s2c.rs rename to crates/valence_protocol/src/packets/play/explosion_s2c.rs diff --git a/crates/valence_packet/src/packets/play/features_s2c.rs b/crates/valence_protocol/src/packets/play/features_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/features_s2c.rs rename to crates/valence_protocol/src/packets/play/features_s2c.rs diff --git a/crates/valence_packet/src/packets/play/full_c2s.rs b/crates/valence_protocol/src/packets/play/full_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/full_c2s.rs rename to crates/valence_protocol/src/packets/play/full_c2s.rs diff --git a/crates/valence_packet/src/packets/play/game_join_s2c.rs b/crates/valence_protocol/src/packets/play/game_join_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/game_join_s2c.rs rename to crates/valence_protocol/src/packets/play/game_join_s2c.rs diff --git a/crates/valence_packet/src/packets/play/game_message_s2c.rs b/crates/valence_protocol/src/packets/play/game_message_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/game_message_s2c.rs rename to crates/valence_protocol/src/packets/play/game_message_s2c.rs diff --git a/crates/valence_packet/src/packets/play/game_state_change_s2c.rs b/crates/valence_protocol/src/packets/play/game_state_change_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/game_state_change_s2c.rs rename to crates/valence_protocol/src/packets/play/game_state_change_s2c.rs diff --git a/crates/valence_packet/src/packets/play/hand_swing_c2s.rs b/crates/valence_protocol/src/packets/play/hand_swing_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/hand_swing_c2s.rs rename to crates/valence_protocol/src/packets/play/hand_swing_c2s.rs diff --git a/crates/valence_packet/src/packets/play/health_update_s2c.rs b/crates/valence_protocol/src/packets/play/health_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/health_update_s2c.rs rename to crates/valence_protocol/src/packets/play/health_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/inventory_s2c.rs b/crates/valence_protocol/src/packets/play/inventory_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/inventory_s2c.rs rename to crates/valence_protocol/src/packets/play/inventory_s2c.rs diff --git a/crates/valence_packet/src/packets/play/item_pickup_animation_s2c.rs b/crates/valence_protocol/src/packets/play/item_pickup_animation_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/item_pickup_animation_s2c.rs rename to crates/valence_protocol/src/packets/play/item_pickup_animation_s2c.rs diff --git a/crates/valence_packet/src/packets/play/jigsaw_generating_c2s.rs b/crates/valence_protocol/src/packets/play/jigsaw_generating_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/jigsaw_generating_c2s.rs rename to crates/valence_protocol/src/packets/play/jigsaw_generating_c2s.rs diff --git a/crates/valence_packet/src/packets/play/keep_alive_c2s.rs b/crates/valence_protocol/src/packets/play/keep_alive_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/keep_alive_c2s.rs rename to crates/valence_protocol/src/packets/play/keep_alive_c2s.rs diff --git a/crates/valence_packet/src/packets/play/keep_alive_s2c.rs b/crates/valence_protocol/src/packets/play/keep_alive_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/keep_alive_s2c.rs rename to crates/valence_protocol/src/packets/play/keep_alive_s2c.rs diff --git a/crates/valence_packet/src/packets/play/light_update_s2c.rs b/crates/valence_protocol/src/packets/play/light_update_s2c.rs similarity index 89% rename from crates/valence_packet/src/packets/play/light_update_s2c.rs rename to crates/valence_protocol/src/packets/play/light_update_s2c.rs index b265f76f1..6b5a6e936 100644 --- a/crates/valence_packet/src/packets/play/light_update_s2c.rs +++ b/crates/valence_protocol/src/packets/play/light_update_s2c.rs @@ -1,6 +1,5 @@ -use valence_core::protocol::array::LengthPrefixedArray; - use super::*; +use crate::array::LengthPrefixedArray; #[derive(Clone, Debug, Encode, Decode, Packet)] #[packet(id = packet_id::LIGHT_UPDATE_S2C)] diff --git a/crates/valence_packet/src/packets/play/look_and_on_ground_c2s.rs b/crates/valence_protocol/src/packets/play/look_and_on_ground_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/look_and_on_ground_c2s.rs rename to crates/valence_protocol/src/packets/play/look_and_on_ground_c2s.rs diff --git a/crates/valence_packet/src/packets/play/look_at_s2c.rs b/crates/valence_protocol/src/packets/play/look_at_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/look_at_s2c.rs rename to crates/valence_protocol/src/packets/play/look_at_s2c.rs diff --git a/crates/valence_packet/src/packets/play/map_update_s2c.rs b/crates/valence_protocol/src/packets/play/map_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/map_update_s2c.rs rename to crates/valence_protocol/src/packets/play/map_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/message_acknowledgment_c2s.rs b/crates/valence_protocol/src/packets/play/message_acknowledgment_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/message_acknowledgment_c2s.rs rename to crates/valence_protocol/src/packets/play/message_acknowledgment_c2s.rs diff --git a/crates/valence_packet/src/packets/play/move_relative_s2c.rs b/crates/valence_protocol/src/packets/play/move_relative_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/move_relative_s2c.rs rename to crates/valence_protocol/src/packets/play/move_relative_s2c.rs diff --git a/crates/valence_packet/src/packets/play/nbt_query_response_s2c.rs b/crates/valence_protocol/src/packets/play/nbt_query_response_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/nbt_query_response_s2c.rs rename to crates/valence_protocol/src/packets/play/nbt_query_response_s2c.rs diff --git a/crates/valence_packet/src/packets/play/on_ground_only_c2s.rs b/crates/valence_protocol/src/packets/play/on_ground_only_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/on_ground_only_c2s.rs rename to crates/valence_protocol/src/packets/play/on_ground_only_c2s.rs diff --git a/crates/valence_packet/src/packets/play/open_horse_screen_s2c.rs b/crates/valence_protocol/src/packets/play/open_horse_screen_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/open_horse_screen_s2c.rs rename to crates/valence_protocol/src/packets/play/open_horse_screen_s2c.rs diff --git a/crates/valence_packet/src/packets/play/open_screen_s2c.rs b/crates/valence_protocol/src/packets/play/open_screen_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/open_screen_s2c.rs rename to crates/valence_protocol/src/packets/play/open_screen_s2c.rs diff --git a/crates/valence_packet/src/packets/play/open_written_book_s2c.rs b/crates/valence_protocol/src/packets/play/open_written_book_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/open_written_book_s2c.rs rename to crates/valence_protocol/src/packets/play/open_written_book_s2c.rs diff --git a/crates/valence_packet/src/packets/play/overlay_message_s2c.rs b/crates/valence_protocol/src/packets/play/overlay_message_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/overlay_message_s2c.rs rename to crates/valence_protocol/src/packets/play/overlay_message_s2c.rs diff --git a/crates/valence_packet/src/packets/play/particle_s2c.rs b/crates/valence_protocol/src/packets/play/particle_s2c.rs similarity index 95% rename from crates/valence_packet/src/packets/play/particle_s2c.rs rename to crates/valence_protocol/src/packets/play/particle_s2c.rs index ce73c4576..c74b020ef 100644 --- a/crates/valence_packet/src/packets/play/particle_s2c.rs +++ b/crates/valence_protocol/src/packets/play/particle_s2c.rs @@ -1,3 +1,4 @@ +use valence_generated::block::BlockState; use valence_math::Vec3; use super::*; @@ -50,8 +51,8 @@ impl<'a> Decode<'a> for ParticleS2c<'a> { pub enum Particle { AmbientEntityEffect, AngryVillager, - Block(i32), // TODO: use BlockState type. - BlockMarker(i32), // TODO: use BlockState type. + Block(BlockState), + BlockMarker(BlockState), Bubble, Cloud, Crit, @@ -80,7 +81,7 @@ pub enum Particle { ExplosionEmitter, Explosion, SonicBoom, - FallingDust(i32), // TODO: use BlockState type. + FallingDust(BlockState), Firework, Fishing, Flame, @@ -273,8 +274,8 @@ impl Particle { Ok(match particle_id { 0 => Particle::AmbientEntityEffect, 1 => Particle::AngryVillager, - 2 => Particle::Block(VarInt::decode(r)?.0), - 3 => Particle::BlockMarker(VarInt::decode(r)?.0), + 2 => Particle::Block(BlockState::decode(r)?), + 3 => Particle::BlockMarker(BlockState::decode(r)?), 4 => Particle::Bubble, 5 => Particle::Cloud, 6 => Particle::Crit, @@ -303,7 +304,7 @@ impl Particle { 22 => Particle::ExplosionEmitter, 23 => Particle::Explosion, 24 => Particle::SonicBoom, - 25 => Particle::FallingDust(VarInt::decode(r)?.0), + 25 => Particle::FallingDust(BlockState::decode(r)?), 26 => Particle::Firework, 27 => Particle::Fishing, 28 => Particle::Flame, @@ -397,8 +398,8 @@ impl Particle { impl Encode for Particle { fn encode(&self, mut w: impl Write) -> anyhow::Result<()> { match self { - Particle::Block(block_state) => VarInt(*block_state).encode(w), - Particle::BlockMarker(block_state) => VarInt(*block_state).encode(w), + Particle::Block(block_state) => block_state.encode(w), + Particle::BlockMarker(block_state) => block_state.encode(w), Particle::Dust { rgb, scale } => { rgb.encode(&mut w)?; scale.encode(w) @@ -412,7 +413,7 @@ impl Encode for Particle { scale.encode(&mut w)?; to_rgb.encode(w) } - Particle::FallingDust(block_state) => VarInt(*block_state).encode(w), + Particle::FallingDust(block_state) => block_state.encode(w), Particle::SculkCharge { roll } => roll.encode(w), Particle::Item(stack) => stack.encode(w), Particle::VibrationBlock { block_pos, ticks } => { diff --git a/crates/valence_packet/src/packets/play/pick_from_inventory_c2s.rs b/crates/valence_protocol/src/packets/play/pick_from_inventory_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/pick_from_inventory_c2s.rs rename to crates/valence_protocol/src/packets/play/pick_from_inventory_c2s.rs diff --git a/crates/valence_packet/src/packets/play/play_ping_s2c.rs b/crates/valence_protocol/src/packets/play/play_ping_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/play_ping_s2c.rs rename to crates/valence_protocol/src/packets/play/play_ping_s2c.rs diff --git a/crates/valence_packet/src/packets/play/play_pong_c2s.rs b/crates/valence_protocol/src/packets/play/play_pong_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/play_pong_c2s.rs rename to crates/valence_protocol/src/packets/play/play_pong_c2s.rs diff --git a/crates/valence_packet/src/packets/play/play_sound_from_entity_s2c.rs b/crates/valence_protocol/src/packets/play/play_sound_from_entity_s2c.rs similarity index 88% rename from crates/valence_packet/src/packets/play/play_sound_from_entity_s2c.rs rename to crates/valence_protocol/src/packets/play/play_sound_from_entity_s2c.rs index ea36d1987..c06f02017 100644 --- a/crates/valence_packet/src/packets/play/play_sound_from_entity_s2c.rs +++ b/crates/valence_protocol/src/packets/play/play_sound_from_entity_s2c.rs @@ -1,6 +1,5 @@ -use valence_core::sound::SoundCategory; - use super::*; +use crate::sound::SoundCategory; #[derive(Copy, Clone, Debug, Encode, Decode, Packet)] #[packet(id = packet_id::PLAY_SOUND_FROM_ENTITY_S2C)] diff --git a/crates/valence_packet/src/packets/play/play_sound_s2c.rs b/crates/valence_protocol/src/packets/play/play_sound_s2c.rs similarity index 84% rename from crates/valence_packet/src/packets/play/play_sound_s2c.rs rename to crates/valence_protocol/src/packets/play/play_sound_s2c.rs index 2651c29a9..6e04ce84d 100644 --- a/crates/valence_packet/src/packets/play/play_sound_s2c.rs +++ b/crates/valence_protocol/src/packets/play/play_sound_s2c.rs @@ -1,6 +1,5 @@ -use valence_core::sound::{SoundCategory, SoundId}; - use super::*; +use crate::sound::{SoundCategory, SoundId}; #[derive(Clone, Debug, Encode, Decode, Packet)] #[packet(id = packet_id::PLAY_SOUND_S2C)] diff --git a/crates/valence_packet/src/packets/play/player_abilities_s2c.rs b/crates/valence_protocol/src/packets/play/player_abilities_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_abilities_s2c.rs rename to crates/valence_protocol/src/packets/play/player_abilities_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_action_c2s.rs b/crates/valence_protocol/src/packets/play/player_action_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_action_c2s.rs rename to crates/valence_protocol/src/packets/play/player_action_c2s.rs diff --git a/crates/valence_packet/src/packets/play/player_action_response_s2c.rs b/crates/valence_protocol/src/packets/play/player_action_response_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_action_response_s2c.rs rename to crates/valence_protocol/src/packets/play/player_action_response_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_input_c2s.rs b/crates/valence_protocol/src/packets/play/player_input_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_input_c2s.rs rename to crates/valence_protocol/src/packets/play/player_input_c2s.rs diff --git a/crates/valence_packet/src/packets/play/player_interact_block_c2s.rs b/crates/valence_protocol/src/packets/play/player_interact_block_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_interact_block_c2s.rs rename to crates/valence_protocol/src/packets/play/player_interact_block_c2s.rs diff --git a/crates/valence_packet/src/packets/play/player_interact_entity_c2s.rs b/crates/valence_protocol/src/packets/play/player_interact_entity_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_interact_entity_c2s.rs rename to crates/valence_protocol/src/packets/play/player_interact_entity_c2s.rs diff --git a/crates/valence_packet/src/packets/play/player_interact_item_c2s.rs b/crates/valence_protocol/src/packets/play/player_interact_item_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_interact_item_c2s.rs rename to crates/valence_protocol/src/packets/play/player_interact_item_c2s.rs diff --git a/crates/valence_packet/src/packets/play/player_list_header_s2c.rs b/crates/valence_protocol/src/packets/play/player_list_header_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_list_header_s2c.rs rename to crates/valence_protocol/src/packets/play/player_list_header_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_list_s2c.rs b/crates/valence_protocol/src/packets/play/player_list_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_list_s2c.rs rename to crates/valence_protocol/src/packets/play/player_list_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_position_look_s2c.rs b/crates/valence_protocol/src/packets/play/player_position_look_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_position_look_s2c.rs rename to crates/valence_protocol/src/packets/play/player_position_look_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_remove_s2c.rs b/crates/valence_protocol/src/packets/play/player_remove_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_remove_s2c.rs rename to crates/valence_protocol/src/packets/play/player_remove_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_respawn_s2c.rs b/crates/valence_protocol/src/packets/play/player_respawn_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_respawn_s2c.rs rename to crates/valence_protocol/src/packets/play/player_respawn_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_session_c2s.rs b/crates/valence_protocol/src/packets/play/player_session_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_session_c2s.rs rename to crates/valence_protocol/src/packets/play/player_session_c2s.rs diff --git a/crates/valence_packet/src/packets/play/player_spawn_position_s2c.rs b/crates/valence_protocol/src/packets/play/player_spawn_position_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_spawn_position_s2c.rs rename to crates/valence_protocol/src/packets/play/player_spawn_position_s2c.rs diff --git a/crates/valence_packet/src/packets/play/player_spawn_s2c.rs b/crates/valence_protocol/src/packets/play/player_spawn_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/player_spawn_s2c.rs rename to crates/valence_protocol/src/packets/play/player_spawn_s2c.rs diff --git a/crates/valence_packet/src/packets/play/position_and_on_ground_c2s.rs b/crates/valence_protocol/src/packets/play/position_and_on_ground_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/position_and_on_ground_c2s.rs rename to crates/valence_protocol/src/packets/play/position_and_on_ground_c2s.rs diff --git a/crates/valence_packet/src/packets/play/profileless_chat_message_s2c.rs b/crates/valence_protocol/src/packets/play/profileless_chat_message_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/profileless_chat_message_s2c.rs rename to crates/valence_protocol/src/packets/play/profileless_chat_message_s2c.rs diff --git a/crates/valence_packet/src/packets/play/query_block_nbt_c2s.rs b/crates/valence_protocol/src/packets/play/query_block_nbt_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/query_block_nbt_c2s.rs rename to crates/valence_protocol/src/packets/play/query_block_nbt_c2s.rs diff --git a/crates/valence_packet/src/packets/play/query_entity_nbt_c2s.rs b/crates/valence_protocol/src/packets/play/query_entity_nbt_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/query_entity_nbt_c2s.rs rename to crates/valence_protocol/src/packets/play/query_entity_nbt_c2s.rs diff --git a/crates/valence_packet/src/packets/play/recipe_book_data_c2s.rs b/crates/valence_protocol/src/packets/play/recipe_book_data_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/recipe_book_data_c2s.rs rename to crates/valence_protocol/src/packets/play/recipe_book_data_c2s.rs diff --git a/crates/valence_packet/src/packets/play/recipe_category_options_c2s.rs b/crates/valence_protocol/src/packets/play/recipe_category_options_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/recipe_category_options_c2s.rs rename to crates/valence_protocol/src/packets/play/recipe_category_options_c2s.rs diff --git a/crates/valence_packet/src/packets/play/remove_entity_status_effect_s2c.rs b/crates/valence_protocol/src/packets/play/remove_entity_status_effect_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/remove_entity_status_effect_s2c.rs rename to crates/valence_protocol/src/packets/play/remove_entity_status_effect_s2c.rs diff --git a/crates/valence_packet/src/packets/play/remove_message_s2c.rs b/crates/valence_protocol/src/packets/play/remove_message_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/remove_message_s2c.rs rename to crates/valence_protocol/src/packets/play/remove_message_s2c.rs diff --git a/crates/valence_packet/src/packets/play/rename_item_c2s.rs b/crates/valence_protocol/src/packets/play/rename_item_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/rename_item_c2s.rs rename to crates/valence_protocol/src/packets/play/rename_item_c2s.rs diff --git a/crates/valence_packet/src/packets/play/request_command_completions_c2s.rs b/crates/valence_protocol/src/packets/play/request_command_completions_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/request_command_completions_c2s.rs rename to crates/valence_protocol/src/packets/play/request_command_completions_c2s.rs diff --git a/crates/valence_packet/src/packets/play/resource_pack_send_s2c.rs b/crates/valence_protocol/src/packets/play/resource_pack_send_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/resource_pack_send_s2c.rs rename to crates/valence_protocol/src/packets/play/resource_pack_send_s2c.rs diff --git a/crates/valence_packet/src/packets/play/resource_pack_status_c2s.rs b/crates/valence_protocol/src/packets/play/resource_pack_status_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/resource_pack_status_c2s.rs rename to crates/valence_protocol/src/packets/play/resource_pack_status_c2s.rs diff --git a/crates/valence_packet/src/packets/play/rotate_and_move_relative_s2c.rs b/crates/valence_protocol/src/packets/play/rotate_and_move_relative_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/rotate_and_move_relative_s2c.rs rename to crates/valence_protocol/src/packets/play/rotate_and_move_relative_s2c.rs diff --git a/crates/valence_packet/src/packets/play/rotate_s2c.rs b/crates/valence_protocol/src/packets/play/rotate_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/rotate_s2c.rs rename to crates/valence_protocol/src/packets/play/rotate_s2c.rs diff --git a/crates/valence_packet/src/packets/play/scoreboard_display_s2c.rs b/crates/valence_protocol/src/packets/play/scoreboard_display_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/scoreboard_display_s2c.rs rename to crates/valence_protocol/src/packets/play/scoreboard_display_s2c.rs diff --git a/crates/valence_packet/src/packets/play/scoreboard_objective_update_s2c.rs b/crates/valence_protocol/src/packets/play/scoreboard_objective_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/scoreboard_objective_update_s2c.rs rename to crates/valence_protocol/src/packets/play/scoreboard_objective_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/scoreboard_player_update_s2c.rs b/crates/valence_protocol/src/packets/play/scoreboard_player_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/scoreboard_player_update_s2c.rs rename to crates/valence_protocol/src/packets/play/scoreboard_player_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/screen_handler_property_update_s2c.rs b/crates/valence_protocol/src/packets/play/screen_handler_property_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/screen_handler_property_update_s2c.rs rename to crates/valence_protocol/src/packets/play/screen_handler_property_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/screen_handler_slot_update_s2c.rs b/crates/valence_protocol/src/packets/play/screen_handler_slot_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/screen_handler_slot_update_s2c.rs rename to crates/valence_protocol/src/packets/play/screen_handler_slot_update_s2c.rs diff --git a/crates/valence_packet/src/packets/play/select_advancement_tab_s2c.rs b/crates/valence_protocol/src/packets/play/select_advancement_tab_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/select_advancement_tab_s2c.rs rename to crates/valence_protocol/src/packets/play/select_advancement_tab_s2c.rs diff --git a/crates/valence_packet/src/packets/play/select_merchant_trade_c2s.rs b/crates/valence_protocol/src/packets/play/select_merchant_trade_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/select_merchant_trade_c2s.rs rename to crates/valence_protocol/src/packets/play/select_merchant_trade_c2s.rs diff --git a/crates/valence_packet/src/packets/play/server_metadata_s2c.rs b/crates/valence_protocol/src/packets/play/server_metadata_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/server_metadata_s2c.rs rename to crates/valence_protocol/src/packets/play/server_metadata_s2c.rs diff --git a/crates/valence_packet/src/packets/play/set_camera_entity_s2c.rs b/crates/valence_protocol/src/packets/play/set_camera_entity_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/set_camera_entity_s2c.rs rename to crates/valence_protocol/src/packets/play/set_camera_entity_s2c.rs diff --git a/crates/valence_packet/src/packets/play/set_trade_offers_s2c.rs b/crates/valence_protocol/src/packets/play/set_trade_offers_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/set_trade_offers_s2c.rs rename to crates/valence_protocol/src/packets/play/set_trade_offers_s2c.rs diff --git a/crates/valence_packet/src/packets/play/sign_editor_open_s2c.rs b/crates/valence_protocol/src/packets/play/sign_editor_open_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/sign_editor_open_s2c.rs rename to crates/valence_protocol/src/packets/play/sign_editor_open_s2c.rs diff --git a/crates/valence_packet/src/packets/play/simulation_distance_s2c.rs b/crates/valence_protocol/src/packets/play/simulation_distance_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/simulation_distance_s2c.rs rename to crates/valence_protocol/src/packets/play/simulation_distance_s2c.rs diff --git a/crates/valence_packet/src/packets/play/spectator_teleport_c2s.rs b/crates/valence_protocol/src/packets/play/spectator_teleport_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/spectator_teleport_c2s.rs rename to crates/valence_protocol/src/packets/play/spectator_teleport_c2s.rs diff --git a/crates/valence_packet/src/packets/play/statistics_s2c.rs b/crates/valence_protocol/src/packets/play/statistics_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/statistics_s2c.rs rename to crates/valence_protocol/src/packets/play/statistics_s2c.rs diff --git a/crates/valence_packet/src/packets/play/stop_sound_s2c.rs b/crates/valence_protocol/src/packets/play/stop_sound_s2c.rs similarity index 97% rename from crates/valence_packet/src/packets/play/stop_sound_s2c.rs rename to crates/valence_protocol/src/packets/play/stop_sound_s2c.rs index 85ed75ca3..b29c1a0b8 100644 --- a/crates/valence_packet/src/packets/play/stop_sound_s2c.rs +++ b/crates/valence_protocol/src/packets/play/stop_sound_s2c.rs @@ -1,6 +1,5 @@ -use valence_core::sound::SoundCategory; - use super::*; +use crate::sound::SoundCategory; #[derive(Clone, PartialEq, Debug, Packet)] #[packet(id = packet_id::STOP_SOUND_S2C)] diff --git a/crates/valence_packet/src/packets/play/subtitle_s2c.rs b/crates/valence_protocol/src/packets/play/subtitle_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/subtitle_s2c.rs rename to crates/valence_protocol/src/packets/play/subtitle_s2c.rs diff --git a/crates/valence_packet/src/packets/play/synchronize_recipes_s2c.rs b/crates/valence_protocol/src/packets/play/synchronize_recipes_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/synchronize_recipes_s2c.rs rename to crates/valence_protocol/src/packets/play/synchronize_recipes_s2c.rs diff --git a/crates/valence_packet/src/packets/play/synchronize_tags_s2c.rs b/crates/valence_protocol/src/packets/play/synchronize_tags_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/synchronize_tags_s2c.rs rename to crates/valence_protocol/src/packets/play/synchronize_tags_s2c.rs diff --git a/crates/valence_packet/src/packets/play/team_s2c.rs b/crates/valence_protocol/src/packets/play/team_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/team_s2c.rs rename to crates/valence_protocol/src/packets/play/team_s2c.rs diff --git a/crates/valence_packet/src/packets/play/teleport_confirm_c2s.rs b/crates/valence_protocol/src/packets/play/teleport_confirm_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/teleport_confirm_c2s.rs rename to crates/valence_protocol/src/packets/play/teleport_confirm_c2s.rs diff --git a/crates/valence_packet/src/packets/play/title_fade_s2c.rs b/crates/valence_protocol/src/packets/play/title_fade_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/title_fade_s2c.rs rename to crates/valence_protocol/src/packets/play/title_fade_s2c.rs diff --git a/crates/valence_packet/src/packets/play/title_s2c.rs b/crates/valence_protocol/src/packets/play/title_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/title_s2c.rs rename to crates/valence_protocol/src/packets/play/title_s2c.rs diff --git a/crates/valence_packet/src/packets/play/unload_chunk_s2c.rs b/crates/valence_protocol/src/packets/play/unload_chunk_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/unload_chunk_s2c.rs rename to crates/valence_protocol/src/packets/play/unload_chunk_s2c.rs diff --git a/crates/valence_packet/src/packets/play/unlock_recipes_s2c.rs b/crates/valence_protocol/src/packets/play/unlock_recipes_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/unlock_recipes_s2c.rs rename to crates/valence_protocol/src/packets/play/unlock_recipes_s2c.rs diff --git a/crates/valence_packet/src/packets/play/update_beacon_c2s.rs b/crates/valence_protocol/src/packets/play/update_beacon_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_beacon_c2s.rs rename to crates/valence_protocol/src/packets/play/update_beacon_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_command_block_c2s.rs b/crates/valence_protocol/src/packets/play/update_command_block_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_command_block_c2s.rs rename to crates/valence_protocol/src/packets/play/update_command_block_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_command_block_minecart_c2s.rs b/crates/valence_protocol/src/packets/play/update_command_block_minecart_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_command_block_minecart_c2s.rs rename to crates/valence_protocol/src/packets/play/update_command_block_minecart_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_difficulty_c2s.rs b/crates/valence_protocol/src/packets/play/update_difficulty_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_difficulty_c2s.rs rename to crates/valence_protocol/src/packets/play/update_difficulty_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_difficulty_lock_c2s.rs b/crates/valence_protocol/src/packets/play/update_difficulty_lock_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_difficulty_lock_c2s.rs rename to crates/valence_protocol/src/packets/play/update_difficulty_lock_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_jigsaw_c2s.rs b/crates/valence_protocol/src/packets/play/update_jigsaw_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_jigsaw_c2s.rs rename to crates/valence_protocol/src/packets/play/update_jigsaw_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_player_abilities_c2s.rs b/crates/valence_protocol/src/packets/play/update_player_abilities_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_player_abilities_c2s.rs rename to crates/valence_protocol/src/packets/play/update_player_abilities_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_selected_slot_c2s.rs b/crates/valence_protocol/src/packets/play/update_selected_slot_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_selected_slot_c2s.rs rename to crates/valence_protocol/src/packets/play/update_selected_slot_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_selected_slot_s2c.rs b/crates/valence_protocol/src/packets/play/update_selected_slot_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_selected_slot_s2c.rs rename to crates/valence_protocol/src/packets/play/update_selected_slot_s2c.rs diff --git a/crates/valence_packet/src/packets/play/update_sign_c2s.rs b/crates/valence_protocol/src/packets/play/update_sign_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_sign_c2s.rs rename to crates/valence_protocol/src/packets/play/update_sign_c2s.rs diff --git a/crates/valence_packet/src/packets/play/update_structure_block_c2s.rs b/crates/valence_protocol/src/packets/play/update_structure_block_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/update_structure_block_c2s.rs rename to crates/valence_protocol/src/packets/play/update_structure_block_c2s.rs diff --git a/crates/valence_packet/src/packets/play/vehicle_move_c2s.rs b/crates/valence_protocol/src/packets/play/vehicle_move_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/play/vehicle_move_c2s.rs rename to crates/valence_protocol/src/packets/play/vehicle_move_c2s.rs diff --git a/crates/valence_packet/src/packets/play/vehicle_move_s2c.rs b/crates/valence_protocol/src/packets/play/vehicle_move_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/vehicle_move_s2c.rs rename to crates/valence_protocol/src/packets/play/vehicle_move_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_border_center_changed_s2c.rs b/crates/valence_protocol/src/packets/play/world_border_center_changed_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_border_center_changed_s2c.rs rename to crates/valence_protocol/src/packets/play/world_border_center_changed_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_border_initialize_s2c.rs b/crates/valence_protocol/src/packets/play/world_border_initialize_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_border_initialize_s2c.rs rename to crates/valence_protocol/src/packets/play/world_border_initialize_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_border_interpolate_size_s2c.rs b/crates/valence_protocol/src/packets/play/world_border_interpolate_size_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_border_interpolate_size_s2c.rs rename to crates/valence_protocol/src/packets/play/world_border_interpolate_size_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_border_size_changed_s2c.rs b/crates/valence_protocol/src/packets/play/world_border_size_changed_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_border_size_changed_s2c.rs rename to crates/valence_protocol/src/packets/play/world_border_size_changed_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_border_warning_blocks_changed_s2c.rs b/crates/valence_protocol/src/packets/play/world_border_warning_blocks_changed_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_border_warning_blocks_changed_s2c.rs rename to crates/valence_protocol/src/packets/play/world_border_warning_blocks_changed_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_border_warning_time_changed_s2c.rs b/crates/valence_protocol/src/packets/play/world_border_warning_time_changed_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_border_warning_time_changed_s2c.rs rename to crates/valence_protocol/src/packets/play/world_border_warning_time_changed_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_event_s2c.rs b/crates/valence_protocol/src/packets/play/world_event_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_event_s2c.rs rename to crates/valence_protocol/src/packets/play/world_event_s2c.rs diff --git a/crates/valence_packet/src/packets/play/world_time_update_s2c.rs b/crates/valence_protocol/src/packets/play/world_time_update_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/play/world_time_update_s2c.rs rename to crates/valence_protocol/src/packets/play/world_time_update_s2c.rs diff --git a/crates/valence_packet/src/packets/status.rs b/crates/valence_protocol/src/packets/status.rs similarity index 100% rename from crates/valence_packet/src/packets/status.rs rename to crates/valence_protocol/src/packets/status.rs diff --git a/crates/valence_packet/src/packets/status/query_ping_c2s.rs b/crates/valence_protocol/src/packets/status/query_ping_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/status/query_ping_c2s.rs rename to crates/valence_protocol/src/packets/status/query_ping_c2s.rs diff --git a/crates/valence_packet/src/packets/status/query_pong_s2c.rs b/crates/valence_protocol/src/packets/status/query_pong_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/status/query_pong_s2c.rs rename to crates/valence_protocol/src/packets/status/query_pong_s2c.rs diff --git a/crates/valence_packet/src/packets/status/query_request_c2s.rs b/crates/valence_protocol/src/packets/status/query_request_c2s.rs similarity index 100% rename from crates/valence_packet/src/packets/status/query_request_c2s.rs rename to crates/valence_protocol/src/packets/status/query_request_c2s.rs diff --git a/crates/valence_packet/src/packets/status/query_response_s2c.rs b/crates/valence_protocol/src/packets/status/query_response_s2c.rs similarity index 100% rename from crates/valence_packet/src/packets/status/query_response_s2c.rs rename to crates/valence_protocol/src/packets/status/query_response_s2c.rs diff --git a/crates/valence_core/src/player_textures.rs b/crates/valence_protocol/src/player_textures.rs similarity index 100% rename from crates/valence_core/src/player_textures.rs rename to crates/valence_protocol/src/player_textures.rs diff --git a/crates/valence_core/src/property.rs b/crates/valence_protocol/src/property.rs similarity index 85% rename from crates/valence_core/src/property.rs rename to crates/valence_protocol/src/property.rs index 634d44162..b00d131c0 100644 --- a/crates/valence_core/src/property.rs +++ b/crates/valence_protocol/src/property.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; #[derive(Copy, Clone, PartialEq, Eq, Debug, Encode, Decode, Serialize, Deserialize)] pub struct Property { diff --git a/crates/valence_core/src/protocol/raw.rs b/crates/valence_protocol/src/raw.rs similarity index 96% rename from crates/valence_core/src/protocol/raw.rs rename to crates/valence_protocol/src/raw.rs index e49e8c680..a106d3310 100644 --- a/crates/valence_core/src/protocol/raw.rs +++ b/crates/valence_protocol/src/raw.rs @@ -1,7 +1,7 @@ use std::io::Write; use std::mem; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; /// While [encoding], the contained slice is written directly to the output /// without any length prefix or metadata. diff --git a/crates/valence_core/src/sound.rs b/crates/valence_protocol/src/sound.rs similarity index 78% rename from crates/valence_core/src/sound.rs rename to crates/valence_protocol/src/sound.rs index 91733d742..4fa3d9e4f 100644 --- a/crates/valence_core/src/sound.rs +++ b/crates/valence_protocol/src/sound.rs @@ -1,21 +1,11 @@ use std::borrow::Cow; use std::io::Write; -use crate::ident; -use crate::ident::Ident; -use crate::protocol::var_int::VarInt; -use crate::protocol::{Decode, Encode}; +pub use valence_generated::sound::Sound; +use valence_ident::Ident; -include!(concat!(env!("OUT_DIR"), "/sound.rs")); - -impl Sound { - pub fn to_id(self) -> SoundId<'static> { - SoundId::Direct { - id: self.to_ident().into(), - range: None, - } - } -} +use crate::var_int::VarInt; +use crate::{Decode, Encode}; #[derive(Clone, PartialEq, Debug)] pub enum SoundId<'a> { @@ -28,6 +18,20 @@ pub enum SoundId<'a> { }, } +#[derive(Copy, Clone, PartialEq, Eq, Debug, Encode, Decode)] +pub enum SoundCategory { + Master, + Music, + Record, + Weather, + Block, + Hostile, + Neutral, + Player, + Ambient, + Voice, +} + impl Encode for SoundId<'_> { fn encode(&self, mut w: impl Write) -> anyhow::Result<()> { match self { @@ -57,17 +61,3 @@ impl<'a> Decode<'a> for SoundId<'a> { } } } - -#[derive(Copy, Clone, PartialEq, Eq, Debug, Encode, Decode)] -pub enum SoundCategory { - Master, - Music, - Record, - Weather, - Block, - Hostile, - Neutral, - Player, - Ambient, - Voice, -} diff --git a/crates/valence_core/src/protocol/var_int.rs b/crates/valence_protocol/src/var_int.rs similarity index 99% rename from crates/valence_core/src/protocol/var_int.rs rename to crates/valence_protocol/src/var_int.rs index 68a7442d2..0e3e84924 100644 --- a/crates/valence_core/src/protocol/var_int.rs +++ b/crates/valence_protocol/src/var_int.rs @@ -5,7 +5,7 @@ use byteorder::ReadBytesExt; use serde::Deserialize; use thiserror::Error; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; /// An `i32` encoded with variable length. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Deserialize)] diff --git a/crates/valence_core/src/protocol/var_long.rs b/crates/valence_protocol/src/var_long.rs similarity index 99% rename from crates/valence_core/src/protocol/var_long.rs rename to crates/valence_protocol/src/var_long.rs index 12d26c424..626f3e8db 100644 --- a/crates/valence_core/src/protocol/var_long.rs +++ b/crates/valence_protocol/src/var_long.rs @@ -3,7 +3,7 @@ use std::io::Write; use anyhow::bail; use byteorder::ReadBytesExt; -use crate::protocol::{Decode, Encode}; +use crate::{Decode, Encode}; /// An `i64` encoded with variable length. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] diff --git a/crates/valence_packet_macros/Cargo.toml b/crates/valence_protocol_macros/Cargo.toml similarity index 77% rename from crates/valence_packet_macros/Cargo.toml rename to crates/valence_protocol_macros/Cargo.toml index 51394e258..299257dec 100644 --- a/crates/valence_packet_macros/Cargo.toml +++ b/crates/valence_protocol_macros/Cargo.toml @@ -1,7 +1,8 @@ [package] -name = "valence_packet_macros" +name = "valence_protocol_macros" version.workspace = true edition.workspace = true +license.workspace = true [lib] proc-macro = true diff --git a/crates/valence_core_macros/README.md b/crates/valence_protocol_macros/README.md similarity index 100% rename from crates/valence_core_macros/README.md rename to crates/valence_protocol_macros/README.md diff --git a/crates/valence_core_macros/src/decode.rs b/crates/valence_protocol_macros/src/decode.rs similarity index 90% rename from crates/valence_core_macros/src/decode.rs rename to crates/valence_protocol_macros/src/decode.rs index a996eef97..15f45e838 100644 --- a/crates/valence_core_macros/src/decode.rs +++ b/crates/valence_protocol_macros/src/decode.rs @@ -63,7 +63,7 @@ pub(super) fn derive_decode(item: TokenStream) -> Result { add_trait_bounds( &mut input.generics, - quote!(::valence_core::__private::Decode<#lifetime>), + quote!(::valence_protocol::__private::Decode<#lifetime>), ); let (impl_generics, ty_generics, where_clause) = @@ -71,11 +71,11 @@ pub(super) fn derive_decode(item: TokenStream) -> Result { Ok(quote! { #[allow(unused_imports)] - impl #impl_generics ::valence_core::__private::Decode<#lifetime> for #input_name #ty_generics + impl #impl_generics ::valence_protocol::__private::Decode<#lifetime> for #input_name #ty_generics #where_clause { - fn decode(_r: &mut &#lifetime [u8]) -> ::valence_core::__private::Result { - use ::valence_core::__private::{Decode, Context, ensure}; + fn decode(_r: &mut &#lifetime [u8]) -> ::valence_protocol::__private::Result { + use ::valence_protocol::__private::{Decode, Context, ensure}; Ok(#decode_fields) } @@ -135,7 +135,7 @@ pub(super) fn derive_decode(item: TokenStream) -> Result { add_trait_bounds( &mut input.generics, - quote!(::valence_core::__private::Decode<#lifetime>), + quote!(::valence_protocol::__private::Decode<#lifetime>), ); let (impl_generics, ty_generics, where_clause) = @@ -143,11 +143,11 @@ pub(super) fn derive_decode(item: TokenStream) -> Result { Ok(quote! { #[allow(unused_imports)] - impl #impl_generics ::valence_core::__private::Decode<#lifetime> for #input_name #ty_generics + impl #impl_generics ::valence_protocol::__private::Decode<#lifetime> for #input_name #ty_generics #where_clause { - fn decode(_r: &mut &#lifetime [u8]) -> ::valence_core::__private::Result { - use ::valence_core::__private::{Decode, Context, VarInt, bail}; + fn decode(_r: &mut &#lifetime [u8]) -> ::valence_protocol::__private::Result { + use ::valence_protocol::__private::{Decode, Context, VarInt, bail}; let ctx = concat!("failed to decode enum discriminant in `", stringify!(#input_name), "`"); let disc = VarInt::decode(_r).context(ctx)?.0; diff --git a/crates/valence_core_macros/src/encode.rs b/crates/valence_protocol_macros/src/encode.rs similarity index 92% rename from crates/valence_core_macros/src/encode.rs rename to crates/valence_protocol_macros/src/encode.rs index 06e1aef6f..101048e0c 100644 --- a/crates/valence_core_macros/src/encode.rs +++ b/crates/valence_protocol_macros/src/encode.rs @@ -12,7 +12,7 @@ pub(super) fn derive_encode(item: TokenStream) -> Result { add_trait_bounds( &mut input.generics, - quote!(::valence_core::__private::Encode), + quote!(::valence_protocol::__private::Encode), ); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); @@ -45,11 +45,11 @@ pub(super) fn derive_encode(item: TokenStream) -> Result { Ok(quote! { #[allow(unused_imports)] - impl #impl_generics ::valence_core::__private::Encode for #input_name #ty_generics + impl #impl_generics ::valence_protocol::__private::Encode for #input_name #ty_generics #where_clause { - fn encode(&self, mut _w: impl ::std::io::Write) -> ::valence_core::__private::Result<()> { - use ::valence_core::__private::{Encode, Context}; + fn encode(&self, mut _w: impl ::std::io::Write) -> ::valence_protocol::__private::Result<()> { + use ::valence_protocol::__private::{Encode, Context}; #encode_fields @@ -143,11 +143,11 @@ pub(super) fn derive_encode(item: TokenStream) -> Result { Ok(quote! { #[allow(unused_imports, unreachable_code)] - impl #impl_generics ::valence_core::__private::Encode for #input_name #ty_generics + impl #impl_generics ::valence_protocol::__private::Encode for #input_name #ty_generics #where_clause { - fn encode(&self, mut _w: impl ::std::io::Write) -> ::valence_core::__private::Result<()> { - use ::valence_core::__private::{Encode, VarInt, Context}; + fn encode(&self, mut _w: impl ::std::io::Write) -> ::valence_protocol::__private::Result<()> { + use ::valence_protocol::__private::{Encode, VarInt, Context}; match self { #encode_arms diff --git a/crates/valence_core_macros/src/lib.rs b/crates/valence_protocol_macros/src/lib.rs similarity index 95% rename from crates/valence_core_macros/src/lib.rs rename to crates/valence_protocol_macros/src/lib.rs index 82de02d63..46c552024 100644 --- a/crates/valence_core_macros/src/lib.rs +++ b/crates/valence_protocol_macros/src/lib.rs @@ -27,7 +27,7 @@ use syn::{ mod decode; mod encode; -mod ident; +mod packet; #[proc_macro_derive(Encode, attributes(packet))] pub fn derive_encode(item: StdTokenStream) -> StdTokenStream { @@ -45,9 +45,9 @@ pub fn derive_decode(item: StdTokenStream) -> StdTokenStream { } } -#[proc_macro] -pub fn parse_ident_str(item: StdTokenStream) -> StdTokenStream { - match ident::parse_ident_str(item.into()) { +#[proc_macro_derive(Packet, attributes(packet))] +pub fn derive_packet(item: StdTokenStream) -> StdTokenStream { + match packet::derive_packet(item.into()) { Ok(tokens) => tokens.into(), Err(e) => e.into_compile_error().into(), } diff --git a/crates/valence_packet_macros/src/packet.rs b/crates/valence_protocol_macros/src/packet.rs similarity index 86% rename from crates/valence_packet_macros/src/packet.rs rename to crates/valence_protocol_macros/src/packet.rs index cb97c77ba..5aa0738a3 100644 --- a/crates/valence_packet_macros/src/packet.rs +++ b/crates/valence_protocol_macros/src/packet.rs @@ -34,9 +34,9 @@ pub(super) fn derive_packet(item: TokenStream) -> Result { let side = if let Some(side_attr) = packet_attr.side { side_attr } else if name_str.to_lowercase().contains("s2c") { - parse_quote!(::valence_packet::protocol::PacketSide::Clientbound) + parse_quote!(::valence_protocol::PacketSide::Clientbound) } else if name_str.to_lowercase().contains("c2s") { - parse_quote!(::valence_packet::protocol::PacketSide::Serverbound) + parse_quote!(::valence_protocol::PacketSide::Serverbound) } else { return Err(Error::new( input.span(), @@ -46,16 +46,16 @@ pub(super) fn derive_packet(item: TokenStream) -> Result { let state = packet_attr .state - .unwrap_or_else(|| parse_quote!(::valence_packet::protocol::PacketState::Play)); + .unwrap_or_else(|| parse_quote!(::valence_protocol::PacketState::Play)); Ok(quote! { - impl #impl_generics ::valence_packet::__private::Packet for #name #ty_generics + impl #impl_generics ::valence_protocol::__private::Packet for #name #ty_generics #where_clause { const ID: i32 = #packet_id; const NAME: &'static str = #name_str; - const SIDE: ::valence_packet::protocol::PacketSide = #side; - const STATE: ::valence_packet::protocol::PacketState = #state; + const SIDE: ::valence_protocol::PacketSide = #side; + const STATE: ::valence_protocol::PacketState = #state; } }) } diff --git a/crates/valence_registry/Cargo.toml b/crates/valence_registry/Cargo.toml index 0de4f26c8..2dba59736 100644 --- a/crates/valence_registry/Cargo.toml +++ b/crates/valence_registry/Cargo.toml @@ -11,5 +11,4 @@ serde_json.workspace = true serde.workspace = true tracing.workspace = true valence_core.workspace = true -valence_packet.workspace = true valence_nbt.workspace = true \ No newline at end of file diff --git a/crates/valence_scoreboard/Cargo.toml b/crates/valence_scoreboard/Cargo.toml index fe28da114..63523c703 100644 --- a/crates/valence_scoreboard/Cargo.toml +++ b/crates/valence_scoreboard/Cargo.toml @@ -10,5 +10,4 @@ valence_client.workspace = true valence_core.workspace = true valence_entity.workspace = true valence_layer.workspace = true -valence_packet.workspace = true tracing.workspace = true diff --git a/crates/valence_text/Cargo.toml b/crates/valence_text/Cargo.toml index 4d47059b3..25ab42f77 100644 --- a/crates/valence_text/Cargo.toml +++ b/crates/valence_text/Cargo.toml @@ -6,9 +6,6 @@ repository.workspace = true documentation.workspace = true license.workspace = true -[features] -translate = [] - [dependencies] anyhow.workspace = true serde = { workspace = true, features = ["derive"] } @@ -16,13 +13,4 @@ serde_json.workspace = true thiserror.workspace = true uuid = { workspace = true, features = ["serde"] } valence_ident.workspace = true -valence_nbt.workspace = true - -[build-dependencies] -anyhow.workspace = true -heck.workspace = true -proc-macro2.workspace = true -quote.workspace = true -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true -valence_build_utils.workspace = true +valence_nbt.workspace = true \ No newline at end of file diff --git a/crates/valence_text/build.rs b/crates/valence_text/build.rs deleted file mode 100644 index 66de1f723..000000000 --- a/crates/valence_text/build.rs +++ /dev/null @@ -1,49 +0,0 @@ -pub fn main() { - #[cfg(feature = "translate")] - valence_build_utils::write_generated_file(translate::build().unwrap(), "translate.rs").unwrap(); -} - -#[cfg(feature = "translate")] -mod translate { - use heck::ToShoutySnakeCase; - use proc_macro2::TokenStream; - use quote::quote; - use serde::Deserialize; - use valence_build_utils::ident; - - pub fn build() -> anyhow::Result { - let translations = serde_json::from_str::>(include_str!( - "../../extracted/translation_keys.json" - ))?; - - let translation_key_consts = translations - .iter() - .map(|translation| { - let const_id = ident(translation.key.replace('.', "_").to_shouty_snake_case()); - let key = &translation.key; - let english_translation = &translation.english_translation; - let doc = format!("\"{}\"", escape(english_translation)); - - quote! { - #[doc = #doc] - pub const #const_id: &str = #key; - } - }) - .collect::>(); - - Ok(quote! { - #(#translation_key_consts)* - }) - } - - #[derive(Deserialize, Clone, Debug)] - struct Translation { - key: String, - english_translation: String, - } - - /// Escapes characters that have special meaning inside docs. - fn escape(text: &str) -> String { - text.replace('[', "\\[").replace(']', "\\]") - } -} diff --git a/crates/valence_text/src/lib.rs b/crates/valence_text/src/lib.rs index 520cfc31a..508d3747b 100644 --- a/crates/valence_text/src/lib.rs +++ b/crates/valence_text/src/lib.rs @@ -13,10 +13,8 @@ use valence_nbt::Value; pub mod color; mod into_text; -#[cfg(all(test, feature = "translate"))] +#[cfg(test)] mod tests; -#[cfg(feature = "translate")] -pub mod translate; pub use color::Color; pub use into_text::IntoText; diff --git a/crates/valence_text/src/tests.rs b/crates/valence_text/src/tests.rs index 9a43d4d15..f910c5fb3 100644 --- a/crates/valence_text/src/tests.rs +++ b/crates/valence_text/src/tests.rs @@ -32,7 +32,7 @@ fn non_object_data_types() { #[test] fn translate() { let txt = Text::translate( - translate::CHAT_TYPE_ADVANCEMENT_TASK, + "chat.type.advancement.task", ["arg1".into_text(), "arg2".into_text()], ); let serialized = txt.to_string(); diff --git a/crates/valence_text/src/translate.rs b/crates/valence_text/src/translate.rs deleted file mode 100644 index 3e46fc130..000000000 --- a/crates/valence_text/src/translate.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Contains all of Minecraft's vanilla translation keys. - -include!(concat!(env!("OUT_DIR"), "/translate.rs")); \ No newline at end of file diff --git a/crates/valence_weather/Cargo.toml b/crates/valence_weather/Cargo.toml index 0022c6f42..274b06cda 100644 --- a/crates/valence_weather/Cargo.toml +++ b/crates/valence_weather/Cargo.toml @@ -10,6 +10,5 @@ license.workspace = true valence_client.workspace = true valence_layer.workspace = true valence_core.workspace = true -valence_packet.workspace = true bevy_ecs.workspace = true bevy_app.workspace = true \ No newline at end of file diff --git a/crates/valence_world_border/Cargo.toml b/crates/valence_world_border/Cargo.toml index c9ca96c76..c18d3a1c1 100644 --- a/crates/valence_world_border/Cargo.toml +++ b/crates/valence_world_border/Cargo.toml @@ -12,4 +12,3 @@ valence_core.workspace = true valence_entity.workspace = true valence_layer.workspace = true valence_registry.workspace = true -valence_packet.workspace = true diff --git a/tools/stresser/Cargo.toml b/tools/stresser/Cargo.toml index c403774e3..4f5720f32 100644 --- a/tools/stresser/Cargo.toml +++ b/tools/stresser/Cargo.toml @@ -10,7 +10,6 @@ anyhow.workspace = true clap.workspace = true tokio.workspace = true uuid = { workspace = true, features = ["v4"] } -valence_network = { workspace = true, features = ["compression"] } +valence_network = { workspace = true } valence_core = { workspace = true } valence_client = { workspace = true } -valence_packet.workspace = true From aa2f3fd0ff9400899ecf5f8e93f653a524784a54 Mon Sep 17 00:00:00 2001 From: Ryan Date: Mon, 7 Aug 2023 07:55:13 -0700 Subject: [PATCH 06/17] update everything --- Cargo.toml | 21 +- benches/block.rs | 2 +- benches/many_players.rs | 25 +- benches/packet.rs | 10 +- benches/var_int.rs | 3 +- benches/var_long.rs | 3 +- crates/valence_advancement/Cargo.toml | 4 +- crates/valence_advancement/src/event.rs | 6 +- crates/valence_advancement/src/lib.rs | 18 +- crates/valence_anvil/Cargo.toml | 8 +- crates/valence_anvil/src/lib.rs | 19 +- crates/valence_anvil/src/parse_chunk.rs | 11 +- crates/valence_biome/Cargo.toml | 14 - crates/valence_biome/README.md | 10 - crates/valence_boss_bar/Cargo.toml | 7 +- crates/valence_boss_bar/src/lib.rs | 12 +- crates/valence_client/Cargo.toml | 24 -- crates/valence_client/README.md | 5 - crates/valence_core/Cargo.toml | 35 --- crates/valence_dimension/Cargo.toml | 14 - crates/valence_dimension/README.md | 8 - crates/valence_entity/Cargo.toml | 5 +- crates/valence_entity/build.rs | 32 +-- crates/valence_entity/src/hitbox.rs | 2 +- crates/valence_entity/src/lib.rs | 9 +- crates/valence_entity/src/query.rs | 10 +- crates/valence_entity/src/tracked_data.rs | 8 +- crates/valence_generated/build/chunk_view.rs | 2 +- crates/valence_generated/build/main.rs | 2 - crates/valence_generated/src/lib.rs | 4 - crates/valence_inventory/Cargo.toml | 4 +- crates/valence_inventory/README.md | 2 +- crates/valence_inventory/src/lib.rs | 44 ++-- crates/valence_inventory/src/validate.rs | 15 +- crates/valence_lang/Cargo.toml | 16 ++ .../build.rs} | 10 +- crates/valence_lang/src/lib.rs | 6 + crates/valence_layer/README.md | 5 - crates/valence_network/Cargo.toml | 11 +- crates/valence_network/src/connect.rs | 33 ++- crates/valence_network/src/lib.rs | 14 +- crates/valence_network/src/packet_io.rs | 11 +- crates/valence_player_list/Cargo.toml | 6 +- crates/valence_player_list/src/lib.rs | 19 +- crates/valence_protocol/src/block_pos.rs | 3 +- crates/valence_protocol/src/decode.rs | 14 +- crates/valence_protocol/src/encode.rs | 14 +- crates/valence_protocol/src/item.rs | 1 + crates/valence_protocol/src/lib.rs | 102 ++++++-- crates/valence_protocol/src/packets.rs | 3 +- crates/valence_registry/Cargo.toml | 7 +- .../lib.rs => valence_registry/src/biome.rs} | 35 +-- crates/valence_registry/src/codec.rs | 2 +- .../src/dimension_type.rs} | 39 +-- crates/valence_registry/src/lib.rs | 10 +- crates/valence_registry/src/tags.rs | 17 +- crates/valence_scoreboard/Cargo.toml | 5 +- crates/valence_scoreboard/README.md | 2 +- crates/valence_scoreboard/src/components.rs | 9 +- crates/valence_scoreboard/src/lib.rs | 31 +-- .../Cargo.toml | 26 +- .../src/action.rs | 30 ++- .../src/chunk_view.rs | 5 +- .../lib.rs => valence_server/src/client.rs} | 244 ++++++------------ .../src/client_command.rs} | 20 +- .../src/client_settings.rs} | 14 +- .../src/custom_payload.rs | 17 +- .../src/event_loop.rs | 35 +-- .../src/hand_swing.rs | 14 +- .../src/interact_block.rs | 16 +- .../src/interact_entity.rs | 14 +- .../src/interact_item.rs | 14 +- .../src/keepalive.rs | 32 ++- .../lib.rs => valence_server/src/layer.rs} | 56 +--- .../src => valence_server/src/layer}/bvh.rs | 4 +- .../src => valence_server/src/layer}/chunk.rs | 99 +++---- .../src/layer}/chunk/chunk.rs | 7 +- .../src/layer}/chunk/loaded.rs | 64 ++--- .../src/layer}/chunk/paletted_container.rs | 3 +- .../src/layer}/chunk/unloaded.rs | 4 +- .../src/layer}/entity.rs | 59 ++--- .../src/layer}/message.rs | 5 +- crates/valence_server/src/lib.rs | 55 ++++ .../src/message.rs | 16 +- .../src/movement.rs | 16 +- .../src/op_level.rs | 15 +- .../src/resource_pack.rs | 17 +- .../src/spawn.rs | 27 +- .../src/status.rs | 14 +- .../src/teleport.rs | 33 ++- .../src/title.rs | 7 +- crates/valence_server_core/Cargo.toml | 11 + .../README.md | 0 .../src/despawn.rs | 2 +- .../src/lib.rs | 90 ++++--- .../src/uuid.rs | 0 crates/valence_weather/Cargo.toml | 4 +- crates/valence_weather/src/lib.rs | 10 +- crates/valence_world_border/Cargo.toml | 7 +- crates/valence_world_border/src/lib.rs | 23 +- examples/anvil_loading.rs | 1 - examples/bench_players.rs | 14 +- examples/biomes.rs | 2 +- examples/block_entities.rs | 4 +- examples/boss_bar.rs | 6 +- examples/building.rs | 3 +- examples/chest.rs | 2 +- examples/combat.rs | 2 +- examples/cow_sphere.rs | 5 +- examples/ctf.rs | 24 +- examples/death.rs | 3 +- examples/entity_hitbox.rs | 23 +- examples/game_of_life.rs | 1 - examples/parkour.rs | 5 +- examples/particles.rs | 6 +- examples/player_list.rs | 3 +- examples/resource_pack.rs | 6 +- examples/server_list_ping.rs | 6 +- examples/terrain.rs | 2 +- examples/text.rs | 6 +- examples/weather.rs | 3 +- examples/world_border.rs | 3 +- src/lib.rs | 145 +++++++---- src/testing.rs | 34 +-- src/tests/boss_bar.rs | 6 +- src/tests/client.rs | 10 +- src/tests/example.rs | 13 +- src/tests/inventory.rs | 19 +- src/tests/layer.rs | 21 +- src/tests/player_list.rs | 7 +- src/tests/scoreboard.rs | 16 +- tools/packet_inspector/src/app/text_viewer.rs | 11 +- tools/packet_inspector/src/lib.rs | 14 +- tools/packet_inspector/src/packet_io.rs | 14 +- tools/packet_inspector/src/packet_registry.rs | 5 +- tools/playground/Cargo.toml | 2 +- tools/playground/src/extras.rs | 2 +- tools/stresser/Cargo.toml | 4 +- tools/stresser/src/stresser.rs | 15 +- 139 files changed, 1169 insertions(+), 1251 deletions(-) delete mode 100644 crates/valence_biome/Cargo.toml delete mode 100644 crates/valence_biome/README.md delete mode 100644 crates/valence_client/Cargo.toml delete mode 100644 crates/valence_client/README.md delete mode 100644 crates/valence_core/Cargo.toml delete mode 100644 crates/valence_dimension/Cargo.toml delete mode 100644 crates/valence_dimension/README.md create mode 100644 crates/valence_lang/Cargo.toml rename crates/{valence_generated/build/translation_key.rs => valence_lang/build.rs} (80%) create mode 100644 crates/valence_lang/src/lib.rs delete mode 100644 crates/valence_layer/README.md rename crates/{valence_biome/src/lib.rs => valence_registry/src/biome.rs} (84%) rename crates/{valence_dimension/src/lib.rs => valence_registry/src/dimension_type.rs} (87%) rename crates/{valence_layer => valence_server}/Cargo.toml (52%) rename crates/{valence_client => valence_server}/src/action.rs (80%) rename crates/{valence_protocol => valence_server}/src/chunk_view.rs (97%) rename crates/{valence_client/src/lib.rs => valence_server/src/client.rs} (84%) rename crates/{valence_client/src/command.rs => valence_server/src/client_command.rs} (90%) rename crates/{valence_client/src/settings.rs => valence_server/src/client_settings.rs} (81%) rename crates/{valence_client => valence_server}/src/custom_payload.rs (66%) rename crates/{valence_client => valence_server}/src/event_loop.rs (88%) rename crates/{valence_client => valence_server}/src/hand_swing.rs (77%) rename crates/{valence_client => valence_server}/src/interact_block.rs (82%) rename crates/{valence_client => valence_server}/src/interact_entity.rs (77%) rename crates/{valence_client => valence_server}/src/interact_item.rs (73%) rename crates/{valence_client => valence_server}/src/keepalive.rs (77%) rename crates/{valence_layer/src/lib.rs => valence_server/src/layer.rs} (77%) rename crates/{valence_layer/src => valence_server/src/layer}/bvh.rs (99%) rename crates/{valence_layer/src => valence_server/src/layer}/chunk.rs (89%) rename crates/{valence_layer/src => valence_server/src/layer}/chunk/chunk.rs (98%) rename crates/{valence_layer/src => valence_server/src/layer}/chunk/loaded.rs (92%) rename crates/{valence_layer/src => valence_server/src/layer}/chunk/paletted_container.rs (99%) rename crates/{valence_layer/src => valence_server/src/layer}/chunk/unloaded.rs (98%) rename crates/{valence_layer/src => valence_server/src/layer}/entity.rs (90%) rename crates/{valence_layer/src => valence_server/src/layer}/message.rs (98%) create mode 100644 crates/valence_server/src/lib.rs rename crates/{valence_client => valence_server}/src/message.rs (80%) rename crates/{valence_client => valence_server}/src/movement.rs (94%) rename crates/{valence_client => valence_server}/src/op_level.rs (60%) rename crates/{valence_client => valence_server}/src/resource_pack.rs (78%) rename crates/{valence_client => valence_server}/src/spawn.rs (85%) rename crates/{valence_client => valence_server}/src/status.rs (76%) rename crates/{valence_client => valence_server}/src/teleport.rs (83%) rename crates/{valence_client => valence_server}/src/title.rs (93%) create mode 100644 crates/valence_server_core/Cargo.toml rename crates/{valence_core => valence_server_core}/README.md (100%) rename crates/{valence_core => valence_server_core}/src/despawn.rs (100%) rename crates/{valence_core => valence_server_core}/src/lib.rs (73%) rename crates/{valence_core => valence_server_core}/src/uuid.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index 25976b8ec..0ddeb8f7b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ default = [ "scoreboard", "world_border", "weather", + "testing", ] advancement = ["dep:valence_advancement"] anvil = ["dep:valence_anvil"] @@ -33,6 +34,7 @@ player_list = ["dep:valence_player_list"] scoreboard = ["dep:valence_scoreboard"] world_border = ["dep:valence_world_border"] weather = ["dep:valence_weather"] +testing = [] [dependencies] anyhow.workspace = true @@ -45,22 +47,16 @@ bytes.workspace = true rand.workspace = true valence_advancement = { workspace = true, optional = true } valence_anvil = { workspace = true, optional = true } -valence_biome.workspace = true valence_boss_bar = { workspace = true, optional = true } -valence_client.workspace = true -valence_core.workspace = true -valence_dimension.workspace = true -valence_entity.workspace = true +valence_server.workspace = true valence_inventory = { workspace = true, optional = true } -valence_layer.workspace = true -valence_math = { workspace = true } -valence_nbt.workspace = true valence_network = { workspace = true, optional = true } valence_player_list = { workspace = true, optional = true } valence_registry.workspace = true valence_scoreboard = { workspace = true, optional = true } valence_weather = { workspace = true, optional = true } valence_world_border = { workspace = true, optional = true } +valence_lang.workspace = true valence_text.workspace = true valence_ident.workspace = true @@ -170,14 +166,11 @@ url = { version = "2.2.2", features = ["serde"] } uuid = "1.3.1" valence_advancement.path = "crates/valence_advancement" valence_anvil.path = "crates/valence_anvil" -valence_biome.path = "crates/valence_biome" valence_build_utils.path = "crates/valence_build_utils" -valence_client.path = "crates/valence_client" +valence_server.path = "crates/valence_server" valence_packet_macros.path = "crates/valence_packet_macros" -valence_core.path = "crates/valence_core" -valence_dimension.path = "crates/valence_dimension" +valence_server_core.path = "crates/valence_server_core" valence_entity.path = "crates/valence_entity" -valence_layer.path = "crates/valence_layer" valence_inventory.path = "crates/valence_inventory" valence_nbt = { path = "crates/valence_nbt", features = ["uuid"] } valence_network.path = "crates/valence_network" @@ -192,6 +185,8 @@ valence_ident.path = "crates/valence_ident" valence_ident_macros.path = "crates/valence_ident_macros" valence_generated.path = "crates/valence_generated" valence_text.path = "crates/valence_text" +valence_protocol.path = "crates/valence_protocol" valence_protocol_macros.path = "crates/valence_protocol_macros" +valence_lang.path = "crates/valence_lang" valence.path = "." zip = "0.6.3" diff --git a/benches/block.rs b/benches/block.rs index 03feb6363..f32c12bb4 100644 --- a/benches/block.rs +++ b/benches/block.rs @@ -2,7 +2,7 @@ use std::hint::black_box; use criterion::Criterion; use valence::block::{BlockKind, BlockState, PropName, PropValue}; -use valence::item::ItemKind; +use valence::ItemKind; pub fn block(c: &mut Criterion) { let mut group = c.benchmark_group("block"); diff --git a/benches/many_players.rs b/benches/many_players.rs index 44c93fe59..29fce678a 100644 --- a/benches/many_players.rs +++ b/benches/many_players.rs @@ -4,18 +4,15 @@ use bevy_app::prelude::*; use criterion::Criterion; use glam::DVec3; use rand::Rng; +use valence::entity::Position; +use valence::keepalive::KeepaliveSettings; +use valence::layer::chunk::UnloadedChunk; +use valence::layer::LayerBundle; +use valence::network::NetworkPlugin; +use valence::protocol::packets::play::{FullC2s, HandSwingC2s}; +use valence::registry::{BiomeRegistry, DimensionTypeRegistry}; use valence::testing::create_mock_client; -use valence::DefaultPlugins; -use valence_biome::BiomeRegistry; -use valence_client::keepalive::KeepaliveSettings; -use valence_core::chunk_pos::ChunkPos; -use valence_core::{ident, CoreSettings, Server}; -use valence_dimension::DimensionTypeRegistry; -use valence_entity::Position; -use valence_layer::chunk::UnloadedChunk; -use valence_layer::LayerBundle; -use valence_network::NetworkPlugin; -use valence_packet::packets::play::{FullC2s, HandSwingC2s}; +use valence::{ident, ChunkPos, DefaultPlugins, Hand, Server, ServerSettings}; pub fn many_players(c: &mut Criterion) { run_many_players(c, "many_players", 3000, 16, 16); @@ -31,7 +28,7 @@ fn run_many_players( ) { let mut app = App::new(); - app.insert_resource(CoreSettings { + app.insert_resource(ServerSettings { compression_threshold: Some(256), ..Default::default() }); @@ -111,9 +108,7 @@ fn run_many_players( on_ground: rng.gen(), }); - helper.send(&HandSwingC2s { - hand: valence_core::hand::Hand::Main, - }); + helper.send(&HandSwingC2s { hand: Hand::Main }); } drop(rng); diff --git a/benches/packet.rs b/benches/packet.rs index 1e0525bdb..923e7da43 100644 --- a/benches/packet.rs +++ b/benches/packet.rs @@ -3,13 +3,11 @@ use std::hint::black_box; use criterion::Criterion; use valence::nbt::{compound, List}; -use valence::packet::packets::play::{ChunkDataS2c, EntitySpawnS2c, PlayerListHeaderS2c}; -use valence::packet::protocol::decode::PacketDecoder; -use valence::packet::protocol::encode::{PacketEncoder, PacketWriter, WritePacket}; use valence::prelude::*; -use valence::protocol::array::LengthPrefixedArray; -use valence::protocol::byte_angle::ByteAngle; -use valence::protocol::var_int::VarInt; +use valence::protocol::decode::PacketDecoder; +use valence::protocol::encode::{PacketEncoder, PacketWriter, WritePacket}; +use valence::protocol::packets::play::{ChunkDataS2c, EntitySpawnS2c, PlayerListHeaderS2c}; +use valence::protocol::{ByteAngle, LengthPrefixedArray, VarInt}; use valence::text::IntoText; pub fn packet(c: &mut Criterion) { diff --git a/benches/var_int.rs b/benches/var_int.rs index b6c0b9600..e8fb1d0d2 100644 --- a/benches/var_int.rs +++ b/benches/var_int.rs @@ -2,8 +2,7 @@ use std::hint::black_box; use criterion::Criterion; use rand::Rng; -use valence::protocol::var_int::VarInt; -use valence::protocol::{Decode, Encode}; +use valence::protocol::{Decode, Encode, VarInt}; pub fn var_int(c: &mut Criterion) { let mut group = c.benchmark_group("varint"); diff --git a/benches/var_long.rs b/benches/var_long.rs index 20450071f..92577a4fb 100644 --- a/benches/var_long.rs +++ b/benches/var_long.rs @@ -2,8 +2,7 @@ use std::hint::black_box; use criterion::Criterion; use rand::Rng; -use valence::protocol::var_long::VarLong; -use valence::protocol::{Decode, Encode}; +use valence::protocol::{Decode, Encode, VarLong}; pub fn var_long(c: &mut Criterion) { let mut group = c.benchmark_group("varlong"); diff --git a/crates/valence_advancement/Cargo.toml b/crates/valence_advancement/Cargo.toml index 76d0aebd0..b2fd6aaba 100644 --- a/crates/valence_advancement/Cargo.toml +++ b/crates/valence_advancement/Cargo.toml @@ -4,10 +4,8 @@ version.workspace = true edition.workspace = true [dependencies] -valence_core.workspace = true -valence_client.workspace = true +valence_server.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true bevy_hierarchy.workspace = true rustc-hash.workspace = true -anyhow.workspace = true \ No newline at end of file diff --git a/crates/valence_advancement/src/event.rs b/crates/valence_advancement/src/event.rs index 8a4aa901c..55951e2c6 100644 --- a/crates/valence_advancement/src/event.rs +++ b/crates/valence_advancement/src/event.rs @@ -1,7 +1,7 @@ use bevy_ecs::prelude::*; -use valence_client::event_loop::PacketEvent; -use valence_core::ident::Ident; -use valence_packet::packets::play::AdvancementTabC2s; +use valence_server::event_loop::PacketEvent; +use valence_server::protocol::packets::play::AdvancementTabC2s; +use valence_server::Ident; /// This event sends when the client changes or closes advancement's tab. #[derive(Event, Clone, PartialEq, Eq, Debug)] diff --git a/crates/valence_advancement/src/lib.rs b/crates/valence_advancement/src/lib.rs index dc2254d2e..0973f4582 100644 --- a/crates/valence_advancement/src/lib.rs +++ b/crates/valence_advancement/src/lib.rs @@ -14,16 +14,14 @@ pub use bevy_hierarchy; use bevy_hierarchy::{Children, HierarchyPlugin, Parent}; use event::{handle_advancement_tab_change, AdvancementTabChangeEvent}; use rustc_hash::FxHashMap; -use valence_client::{Client, FlushPacketsSet, SpawnClientsSet}; -use valence_core::ident::Ident; -use valence_core::item::ItemStack; -use valence_core::protocol::raw::RawBytes; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::Encode; -use valence_core::text::Text; -use valence_packet::packets::play::{advancement_update_s2c as packet, SelectAdvancementTabS2c}; -use valence_packet::protocol::encode::WritePacket; -use valence_packet::protocol::{packet_id, Packet, PacketSide, PacketState}; +use valence_server::client::{Client, FlushPacketsSet, SpawnClientsSet}; +use valence_server::protocol::packets::play::{ + advancement_update_s2c as packet, SelectAdvancementTabS2c, +}; +use valence_server::protocol::{ + anyhow, packet_id, Encode, Packet, PacketSide, PacketState, RawBytes, VarInt, WritePacket, +}; +use valence_server::{Ident, ItemStack, Text}; pub struct AdvancementPlugin; diff --git a/crates/valence_anvil/Cargo.toml b/crates/valence_anvil/Cargo.toml index 777bb92e7..abb26e2d7 100644 --- a/crates/valence_anvil/Cargo.toml +++ b/crates/valence_anvil/Cargo.toml @@ -9,7 +9,6 @@ version.workspace = true edition.workspace = true [dependencies] -anyhow.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true byteorder.workspace = true @@ -19,9 +18,4 @@ lru.workspace = true num-integer.workspace = true thiserror.workspace = true tracing.workspace = true -valence_biome.workspace = true -valence_client.workspace = true -valence_core.workspace = true -valence_entity.workspace = true -valence_layer.workspace = true -valence_nbt.workspace = true +valence_server.workspace = true diff --git a/crates/valence_anvil/src/lib.rs b/crates/valence_anvil/src/lib.rs index ea718e62e..cd6c3d4a6 100644 --- a/crates/valence_anvil/src/lib.rs +++ b/crates/valence_anvil/src/lib.rs @@ -25,7 +25,6 @@ use std::num::NonZeroUsize; use std::path::PathBuf; use std::thread; -use anyhow::{bail, ensure}; use bevy_app::prelude::*; use bevy_ecs::prelude::*; use byteorder::{BigEndian, ReadBytesExt}; @@ -33,14 +32,16 @@ use flate2::bufread::{GzDecoder, ZlibDecoder}; use flume::{Receiver, Sender}; use lru::LruCache; use tracing::warn; -use valence_biome::{BiomeId, BiomeRegistry}; -use valence_client::{Client, OldView, View}; -use valence_core::chunk_pos::ChunkPos; -use valence_core::ident::Ident; -use valence_entity::{EntityLayerId, OldEntityLayerId}; -use valence_layer::chunk::UnloadedChunk; -use valence_layer::{ChunkLayer, UpdateLayersPreClientSet}; -use valence_nbt::Compound; +use valence_server::client::{Client, OldView, View}; +use valence_server::entity::{EntityLayerId, OldEntityLayerId}; +use valence_server::layer::chunk::UnloadedChunk; +use valence_server::layer::UpdateLayersPreClientSet; +use valence_server::nbt::Compound; +use valence_server::protocol::anyhow::{bail, ensure}; +use valence_server::protocol::{anyhow, ChunkPos}; +use valence_server::registry::biome::BiomeId; +use valence_server::registry::BiomeRegistry; +use valence_server::{ChunkLayer, Ident}; mod parse_chunk; diff --git a/crates/valence_anvil/src/parse_chunk.rs b/crates/valence_anvil/src/parse_chunk.rs index 616209408..65e7543f5 100644 --- a/crates/valence_anvil/src/parse_chunk.rs +++ b/crates/valence_anvil/src/parse_chunk.rs @@ -3,11 +3,12 @@ use std::collections::BTreeMap; use num_integer::div_ceil; use thiserror::Error; -use valence_biome::BiomeId; -use valence_block::{BlockKind, PropName, PropValue}; -use valence_core::ident::Ident; -use valence_layer::chunk::{Chunk, UnloadedChunk}; -use valence_nbt::{Compound, List, Value}; +use valence_server::block::{PropName, PropValue}; +use valence_server::layer::chunk::{Chunk, UnloadedChunk}; +use valence_server::nbt::{Compound, List, Value}; +use valence_server::protocol::BlockKind; +use valence_server::registry::biome::BiomeId; +use valence_server::Ident; #[derive(Clone, Debug, Error)] #[non_exhaustive] diff --git a/crates/valence_biome/Cargo.toml b/crates/valence_biome/Cargo.toml deleted file mode 100644 index 5ecd8fc40..000000000 --- a/crates/valence_biome/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "valence_biome" -version.workspace = true -edition.workspace = true - -[dependencies] -anyhow.workspace = true -bevy_app.workspace = true -bevy_ecs.workspace = true -serde.workspace = true -tracing.workspace = true -valence_core.workspace = true -valence_nbt = { workspace = true, features = ["serde"] } -valence_registry.workspace = true diff --git a/crates/valence_biome/README.md b/crates/valence_biome/README.md deleted file mode 100644 index 71d45b86b..000000000 --- a/crates/valence_biome/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# valence_biome - -Contains biomes and the biome registry. Minecraft's default biomes are added to the registry by default. - -### **NOTE:** -- Modifying the biome registry after the server has started can -break invariants within instances and clients! Make sure there are no -instances or clients spawned before mutating. -- A biome named "minecraft:plains" must exist. Otherwise, vanilla clients - will be disconnected. diff --git a/crates/valence_boss_bar/Cargo.toml b/crates/valence_boss_bar/Cargo.toml index efe5fdfee..572976723 100644 --- a/crates/valence_boss_bar/Cargo.toml +++ b/crates/valence_boss_bar/Cargo.toml @@ -8,11 +8,8 @@ version.workspace = true edition.workspace = true [dependencies] -valence_core.workspace = true -valence_network.workspace = true valence_entity.workspace = true -valence_client.workspace = true -uuid.workspace = true +valence_server.workspace = true bitfield-struct.workspace = true bevy_app.workspace = true -bevy_ecs.workspace = true \ No newline at end of file +bevy_ecs.workspace = true diff --git a/crates/valence_boss_bar/src/lib.rs b/crates/valence_boss_bar/src/lib.rs index e93c02fe7..73b8b70d9 100644 --- a/crates/valence_boss_bar/src/lib.rs +++ b/crates/valence_boss_bar/src/lib.rs @@ -23,15 +23,13 @@ use std::collections::BTreeSet; use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_client::{Client, FlushPacketsSet}; -use valence_core::despawn::Despawned; -use valence_core::text::Text; -use valence_core::uuid::UniqueId; -pub use valence_packet::packets::play::boss_bar_s2c::{ +use valence_server::client::{Client, FlushPacketsSet}; +pub use valence_server::protocol::packets::play::boss_bar_s2c::{ BossBarAction, BossBarColor, BossBarDivision, BossBarFlags, }; -use valence_packet::packets::play::BossBarS2c; -use valence_packet::protocol::encode::WritePacket; +use valence_server::protocol::packets::play::BossBarS2c; +use valence_server::protocol::WritePacket; +use valence_server::{Despawned, Text, UniqueId}; /// The bundle of components that make up a boss bar. #[derive(Bundle, Debug, Default)] diff --git a/crates/valence_client/Cargo.toml b/crates/valence_client/Cargo.toml deleted file mode 100644 index 845d544a0..000000000 --- a/crates/valence_client/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "valence_client" -version.workspace = true -edition.workspace = true - -[dependencies] -anyhow.workspace = true -bevy_app.workspace = true -bevy_ecs.workspace = true -bevy_utils.workspace = true # Needed for `ScheduleLabel` derive macro. -bitfield-struct.workspace = true -bytes.workspace = true -valence_math.workspace = true -rand.workspace = true -tracing.workspace = true -uuid.workspace = true -byteorder.workspace = true -valence_biome.workspace = true -valence_core.workspace = true -valence_dimension.workspace = true -valence_entity.workspace = true -valence_layer.workspace = true -valence_nbt.workspace = true -valence_registry.workspace = true diff --git a/crates/valence_client/README.md b/crates/valence_client/README.md deleted file mode 100644 index 4e21dfc16..000000000 --- a/crates/valence_client/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# valence_client - -Manages core components and systems related to Minecraft clients. - -A client is a Minecraft player entity backed by an abstract network connection and other necessary components. See [`Client`] for more information. diff --git a/crates/valence_core/Cargo.toml b/crates/valence_core/Cargo.toml deleted file mode 100644 index 7af30306c..000000000 --- a/crates/valence_core/Cargo.toml +++ /dev/null @@ -1,35 +0,0 @@ -[package] -name = "valence_core" -version.workspace = true -edition.workspace = true -build = "build/main.rs" - -[features] -encryption = ["dep:aes", "dep:cfb8"] -compression = ["dep:flate2"] - -[dependencies] -aes = { workspace = true, optional = true } -anyhow.workspace = true -bevy_app.workspace = true -bevy_ecs.workspace = true -bitfield-struct.workspace = true -byteorder.workspace = true -bytes.workspace = true -cfb8 = { workspace = true, optional = true } -flate2 = { workspace = true, optional = true } -valence_math.workspace = true -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true -thiserror.workspace = true -tracing.workspace = true -uuid = { workspace = true, features = ["serde"] } -valence_nbt = { workspace = true, features = ["binary"] } -url.workspace = true -base64.workspace = true -rand.workspace = true - -[dev-dependencies] -rand.workspace = true -# valence_core = { workspace = true, features = ["compression"] } - diff --git a/crates/valence_dimension/Cargo.toml b/crates/valence_dimension/Cargo.toml deleted file mode 100644 index 3aadc6a9f..000000000 --- a/crates/valence_dimension/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "valence_dimension" -version.workspace = true -edition.workspace = true - -[dependencies] -anyhow.workspace = true -bevy_app.workspace = true -bevy_ecs.workspace = true -serde.workspace = true -tracing.workspace = true -valence_core.workspace = true -valence_nbt = { workspace = true, features = ["serde"] } -valence_registry.workspace = true \ No newline at end of file diff --git a/crates/valence_dimension/README.md b/crates/valence_dimension/README.md deleted file mode 100644 index c89ea5986..000000000 --- a/crates/valence_dimension/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# valence_dimension - -Contains dimension types and the dimension type registry. Minecraft's default dimensions are added to the registry by default. - -### **NOTE:** -- Modifying the dimension type registry after the server has started can -break invariants within instances and clients! Make sure there are no -instances or clients spawned before mutating. diff --git a/crates/valence_entity/Cargo.toml b/crates/valence_entity/Cargo.toml index d547792c1..a33378ea1 100644 --- a/crates/valence_entity/Cargo.toml +++ b/crates/valence_entity/Cargo.toml @@ -13,8 +13,9 @@ paste.workspace = true rustc-hash.workspace = true tracing.workspace = true uuid.workspace = true -valence_core.workspace = true +valence_server_core.workspace = true valence_nbt.workspace = true +valence_protocol.workspace = true [build-dependencies] anyhow.workspace = true @@ -24,4 +25,4 @@ syn.workspace = true serde_json.workspace = true heck.workspace = true serde.workspace = true -valence_build_utils.workspace = true \ No newline at end of file +valence_build_utils.workspace = true diff --git a/crates/valence_entity/build.rs b/crates/valence_entity/build.rs index a34e87be4..00fbcf4d2 100644 --- a/crates/valence_entity/build.rs +++ b/crates/valence_entity/build.rs @@ -128,19 +128,19 @@ impl Value { Value::Long(_) => quote!(i64), Value::Float(_) => quote!(f32), Value::String(_) => quote!(String), - Value::TextComponent(_) => quote!(valence_core::text::Text), - Value::OptionalTextComponent(_) => quote!(Option), - Value::ItemStack(_) => quote!(valence_core::item::ItemStack), + Value::TextComponent(_) => quote!(valence_protocol::Text), + Value::OptionalTextComponent(_) => quote!(Option), + Value::ItemStack(_) => quote!(valence_protocol::ItemStack), Value::Boolean(_) => quote!(bool), Value::Rotation { .. } => quote!(crate::EulerAngle), - Value::BlockPos(_) => quote!(valence_core::block_pos::BlockPos), - Value::OptionalBlockPos(_) => quote!(Option), - Value::Facing(_) => quote!(valence_core::direction::Direction), + Value::BlockPos(_) => quote!(valence_protocol::BlockPos), + Value::OptionalBlockPos(_) => quote!(Option), + Value::Facing(_) => quote!(valence_protocol::Direction), Value::OptionalUuid(_) => quote!(Option<::uuid::Uuid>), - Value::BlockState(_) => quote!(valence_block::BlockState), - Value::OptionalBlockState(_) => quote!(valence_block::BlockState), + Value::BlockState(_) => quote!(valence_protocol::BlockState), + Value::OptionalBlockState(_) => quote!(valence_protocol::BlockState), Value::NbtCompound(_) => quote!(valence_nbt::Compound), - Value::Particle(_) => quote!(valence_packet::packets::play::particle_s2c::Particle), + Value::Particle(_) => quote!(valence_protocol::packets::play::particle_s2c::Particle), Value::VillagerData { .. } => quote!(crate::VillagerData), Value::OptionalInt(_) => quote!(Option), Value::EntityPose(_) => quote!(crate::Pose), @@ -163,7 +163,7 @@ impl Value { Value::String(s) => quote!(#s.to_owned()), Value::TextComponent(txt) => { assert!(txt.is_empty()); - quote!(valence_core::text::Text::default()) + quote!(valence_protocol::Text::default()) } Value::OptionalTextComponent(t) => { assert!(t.is_none()); @@ -171,7 +171,7 @@ impl Value { } Value::ItemStack(stack) => { assert_eq!(stack, "0 air"); - quote!(valence_core::item::ItemStack::default()) + quote!(valence_protocol::ItemStack::default()) } Value::Boolean(b) => quote!(#b), Value::Rotation { pitch, yaw, roll } => quote! { @@ -182,7 +182,7 @@ impl Value { } }, Value::BlockPos(BlockPos { x, y, z }) => { - quote!(valence_core::block_pos::BlockPos { x: #x, y: #y, z: #z }) + quote!(valence_protocol::BlockPos { x: #x, y: #y, z: #z }) } Value::OptionalBlockPos(pos) => { assert!(pos.is_none()); @@ -190,18 +190,18 @@ impl Value { } Value::Facing(f) => { let variant = ident(f.replace('.', "_").to_pascal_case()); - quote!(valence_core::direction::Direction::#variant) + quote!(valence_protocol::Direction::#variant) } Value::OptionalUuid(uuid) => { assert!(uuid.is_none()); quote!(None) } Value::BlockState(_) => { - quote!(valence_block::BlockState::default()) + quote!(valence_protocol::BlockState::default()) } Value::OptionalBlockState(bs) => { assert!(bs.is_none()); - quote!(valence_block::BlockState::default()) + quote!(valence_protocol::BlockState::default()) } Value::NbtCompound(s) => { assert_eq!(s, "{}"); @@ -209,7 +209,7 @@ impl Value { } Value::Particle(p) => { let variant = ident(p.replace('.', "_").to_pascal_case()); - quote!(valence_packet::packets::play::particle_s2c::Particle::#variant) + quote!(valence_protocol::packets::play::particle_s2c::Particle::#variant) } Value::VillagerData { typ, diff --git a/crates/valence_entity/src/hitbox.rs b/crates/valence_entity/src/hitbox.rs index fc4778464..807a20bf1 100644 --- a/crates/valence_entity/src/hitbox.rs +++ b/crates/valence_entity/src/hitbox.rs @@ -2,8 +2,8 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::direction::Direction; use valence_math::{Aabb, DVec3, UVec3, Vec3Swizzles}; +use valence_protocol::Direction; use crate::*; diff --git a/crates/valence_entity/src/lib.rs b/crates/valence_entity/src/lib.rs index 6d9a54496..0f72073dc 100644 --- a/crates/valence_entity/src/lib.rs +++ b/crates/valence_entity/src/lib.rs @@ -30,14 +30,9 @@ pub use manager::EntityManager; use paste::paste; use tracing::warn; use tracked_data::TrackedData; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::ChunkPos; -use valence_core::despawn::Despawned; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::{Decode, Encode}; -use valence_core::uuid::UniqueId; -use valence_core::DEFAULT_TPS; use valence_math::{DVec3, Vec3}; +use valence_protocol::{BlockPos, ChunkPos, Decode, Encode, VarInt}; +use valence_server_core::{Despawned, UniqueId, DEFAULT_TPS}; include!(concat!(env!("OUT_DIR"), "/entity.rs")); pub struct EntityPlugin; diff --git a/crates/valence_entity/src/query.rs b/crates/valence_entity/src/query.rs index 23a5f6d4a..b034be939 100644 --- a/crates/valence_entity/src/query.rs +++ b/crates/valence_entity/src/query.rs @@ -3,16 +3,16 @@ use std::mem; use bevy_ecs::prelude::DetectChanges; use bevy_ecs::query::WorldQuery; use bevy_ecs::world::Ref; -use valence_core::protocol::byte_angle::ByteAngle; -use valence_core::protocol::var_int::VarInt; -use valence_core::uuid::UniqueId; use valence_math::DVec3; -use valence_packet::packets::play::{ +use valence_protocol::encode::WritePacket; +use valence_protocol::packets::play::{ EntityAnimationS2c, EntityPositionS2c, EntitySetHeadYawS2c, EntitySpawnS2c, EntityStatusS2c, EntityTrackerUpdateS2c, EntityVelocityUpdateS2c, ExperienceOrbSpawnS2c, MoveRelativeS2c, PlayerSpawnS2c, RotateAndMoveRelativeS2c, RotateS2c, }; -use valence_packet::protocol::encode::WritePacket; +use valence_protocol::var_int::VarInt; +use valence_protocol::ByteAngle; +use valence_server_core::UniqueId; use crate::tracked_data::TrackedData; use crate::{ diff --git a/crates/valence_entity/src/tracked_data.rs b/crates/valence_entity/src/tracked_data.rs index a8a38d5a2..bbdb84923 100644 --- a/crates/valence_entity/src/tracked_data.rs +++ b/crates/valence_entity/src/tracked_data.rs @@ -1,11 +1,11 @@ use bevy_ecs::prelude::*; use tracing::warn; -use valence_core::protocol::Encode; +use valence_protocol::Encode; /// Cache for all the tracked data of an entity. Used for the /// [`EntityTrackerUpdateS2c`][packet] packet. /// -/// [packet]: valence_packet::packets::play::EntityTrackerUpdateS2c +/// [packet]: valence_protocol::packets::play::EntityTrackerUpdateS2c #[derive(Component, Default, Debug)] pub struct TrackedData { init_data: Vec, @@ -20,7 +20,7 @@ impl TrackedData { /// [`EntityTrackerUpdateS2c`][packet] packet. This is used when the entity /// enters the view of a client. /// - /// [packet]: valence_packet::packets::play::EntityTrackerUpdateS2c + /// [packet]: valence_protocol::packets::play::EntityTrackerUpdateS2c pub fn init_data(&self) -> Option<&[u8]> { if self.init_data.len() > 1 { Some(&self.init_data) @@ -33,7 +33,7 @@ impl TrackedData { /// [`EntityTrackerUpdateS2c`][packet] packet. This is used when tracked /// data is changed and the client is already in view of the entity. /// - /// [packet]: valence_packet::packets::play::EntityTrackerUpdateS2c + /// [packet]: valence_protocol::packets::play::EntityTrackerUpdateS2c pub fn update_data(&self) -> Option<&[u8]> { if self.update_data.len() > 1 { Some(&self.update_data) diff --git a/crates/valence_generated/build/chunk_view.rs b/crates/valence_generated/build/chunk_view.rs index 0fa73fe21..ebf80d8cf 100644 --- a/crates/valence_generated/build/chunk_view.rs +++ b/crates/valence_generated/build/chunk_view.rs @@ -30,7 +30,7 @@ pub fn build() -> TokenStream { let array_len = MAX_VIEW_DIST as usize + 1; quote! { - /// The maximum view distance for a [`ChunkView`]. + /// The maximum view distance for a `ChunkView`. pub const MAX_VIEW_DIST: u8 = #MAX_VIEW_DIST; pub const EXTRA_VIEW_RADIUS: i32 = #EXTRA_VIEW_RADIUS; diff --git a/crates/valence_generated/build/main.rs b/crates/valence_generated/build/main.rs index c84c4046f..adfa4fec2 100644 --- a/crates/valence_generated/build/main.rs +++ b/crates/valence_generated/build/main.rs @@ -5,11 +5,9 @@ mod chunk_view; mod item; mod packet_id; mod sound; -mod translation_key; pub fn main() -> anyhow::Result<()> { write_generated_file(block::build()?, "block.rs")?; - write_generated_file(translation_key::build()?, "translation_key.rs")?; write_generated_file(item::build()?, "item.rs")?; write_generated_file(sound::build()?, "sound.rs")?; write_generated_file(packet_id::build()?, "packet_id.rs")?; diff --git a/crates/valence_generated/src/lib.rs b/crates/valence_generated/src/lib.rs index 2d62541a9..53df8ae19 100644 --- a/crates/valence_generated/src/lib.rs +++ b/crates/valence_generated/src/lib.rs @@ -4,10 +4,6 @@ pub mod item { include!(concat!(env!("OUT_DIR"), "/item.rs")); } -pub mod translation_key { - include!(concat!(env!("OUT_DIR"), "/translation_key.rs")); -} - pub mod sound { include!(concat!(env!("OUT_DIR"), "/sound.rs")); } diff --git a/crates/valence_inventory/Cargo.toml b/crates/valence_inventory/Cargo.toml index 4e0a8d70a..e8b6baa52 100644 --- a/crates/valence_inventory/Cargo.toml +++ b/crates/valence_inventory/Cargo.toml @@ -4,9 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] -anyhow.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true tracing.workspace = true -valence_client.workspace = true -valence_core.workspace = true +valence_server.workspace = true diff --git a/crates/valence_inventory/README.md b/crates/valence_inventory/README.md index ae221722d..d5b2615be 100644 --- a/crates/valence_inventory/README.md +++ b/crates/valence_inventory/README.md @@ -20,7 +20,7 @@ An example system that will let you access all player's inventories: ``` # use bevy_ecs::prelude::*; # use valence_inventory::*; -# use valence_client::Client; +# use valence_server::client::Client; fn system(clients: Query<(&Client, &Inventory)>) {} ``` diff --git a/crates/valence_inventory/src/lib.rs b/crates/valence_inventory/src/lib.rs index ec969eec7..35edb227a 100644 --- a/crates/valence_inventory/src/lib.rs +++ b/crates/valence_inventory/src/lib.rs @@ -26,20 +26,18 @@ use std::ops::Range; use bevy_app::prelude::*; use bevy_ecs::prelude::*; use tracing::{debug, warn}; -use valence_client::event_loop::{EventLoopPreUpdate, PacketEvent}; -use valence_client::{Client, FlushPacketsSet, SpawnClientsSet}; -use valence_core::game_mode::GameMode; -use valence_core::item::{ItemKind, ItemStack}; -use valence_core::protocol::var_int::VarInt; -use valence_core::text::{IntoText, Text}; -pub use valence_packet::packets::play::click_slot_c2s::{ClickMode, SlotChange}; -pub use valence_packet::packets::play::open_screen_s2c::WindowType; -pub use valence_packet::packets::play::player_action_c2s::PlayerAction; -use valence_packet::packets::play::{ +use valence_server::client::{Client, FlushPacketsSet, SpawnClientsSet}; +use valence_server::event_loop::{EventLoopPreUpdate, PacketEvent}; +pub use valence_server::protocol::packets::play::click_slot_c2s::{ClickMode, SlotChange}; +use valence_server::protocol::packets::play::open_screen_s2c::WindowType; +pub use valence_server::protocol::packets::play::player_action_c2s::PlayerAction; +use valence_server::protocol::packets::play::{ ClickSlotC2s, CloseHandledScreenC2s, CloseScreenS2c, CreativeInventoryActionC2s, InventoryS2c, OpenScreenS2c, PlayerActionC2s, ScreenHandlerSlotUpdateS2c, UpdateSelectedSlotC2s, }; -use valence_packet::protocol::encode::WritePacket; +use valence_server::protocol::{VarInt, WritePacket}; +use valence_server::text::IntoText; +use valence_server::{GameMode, ItemKind, ItemStack, Text}; mod validate; @@ -121,7 +119,7 @@ impl Inventory { /// /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::{ItemStack, ItemKind}; + /// # use valence_server::item::{ItemStack, ItemKind}; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// assert_eq!(inv.slot(0).unwrap().item, ItemKind::Diamond); @@ -139,7 +137,7 @@ impl Inventory { /// /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::{ItemStack, ItemKind}; + /// # use valence_server::item::{ItemStack, ItemKind}; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// let old = inv.replace_slot(0, ItemStack::new(ItemKind::IronIngot, 1, None)); @@ -169,7 +167,7 @@ impl Inventory { /// /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::{ItemStack, ItemKind}; + /// # use valence_server::item::{ItemStack, ItemKind}; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// assert_eq!(inv.slot(1), None); @@ -204,7 +202,7 @@ impl Inventory { /// /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::{ItemStack, ItemKind}; + /// # use valence_server::item::{ItemStack, ItemKind}; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// inv.set_slot_amount(0, 64); @@ -245,8 +243,8 @@ impl Inventory { /// /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::{ItemStack, ItemKind}; - /// # use valence_core::text::Text; + /// # use valence_server::item::{ItemStack, ItemKind}; + /// # use valence_server::text::Text; /// let inv = Inventory::with_title(InventoryKind::Generic9x3, "Box of Holding"); /// assert_eq!(inv.title(), &Text::from("Box of Holding")); /// ``` @@ -285,7 +283,7 @@ impl Inventory { /// /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::*; + /// # use valence_server::item::*; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 1, None)); @@ -309,7 +307,7 @@ impl Inventory { /// empty slots. /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::*; + /// # use valence_server::item::*; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 1, None)); @@ -325,7 +323,7 @@ impl Inventory { /// where `count() < stack_max`, or `None` if there are no empty slots. /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::*; + /// # use valence_server::item::*; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 64, None)); @@ -361,7 +359,7 @@ impl Inventory { /// where `count() < stack_max`, or `None` if there are no empty slots. /// ``` /// # use valence_inventory::*; - /// # use valence_core::item::*; + /// # use valence_server::item::*; /// let mut inv = Inventory::new(InventoryKind::Generic9x1); /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None)); /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 64, None)); @@ -447,7 +445,7 @@ impl OpenInventory { /// /// ``` /// # use valence_inventory::*; -/// # use valence_core::item::*; +/// # use valence_server::item::*; /// let mut player_inventory = Inventory::new(InventoryKind::Player); /// player_inventory.set_slot(36, ItemStack::new(ItemKind::Diamond, 1, None)); /// @@ -503,7 +501,7 @@ impl<'a> InventoryWindow<'a> { /// /// ``` /// # use valence_inventory::*; -/// # use valence_core::item::*; +/// # use valence_server::item::*; /// let mut player_inventory = Inventory::new(InventoryKind::Player); /// let mut target_inventory = Inventory::new(InventoryKind::Generic9x3); /// let mut window = InventoryWindowMut::new(&mut player_inventory, Some(&mut target_inventory)); diff --git a/crates/valence_inventory/src/validate.rs b/crates/valence_inventory/src/validate.rs index ba1af7b4e..2d7b5f044 100644 --- a/crates/valence_inventory/src/validate.rs +++ b/crates/valence_inventory/src/validate.rs @@ -1,7 +1,7 @@ -use anyhow::{bail, ensure}; -use valence_core::item::ItemStack; -use valence_packet::packets::play::click_slot_c2s::ClickMode; -use valence_packet::packets::play::ClickSlotC2s; +use valence_server::protocol::anyhow::{self, bail, ensure}; +use valence_server::protocol::packets::play::click_slot_c2s::ClickMode; +use valence_server::protocol::packets::play::ClickSlotC2s; +use valence_server::ItemStack; use super::{CursorItem, Inventory, InventoryWindow, PLAYER_INVENTORY_MAIN_SLOTS_COUNT}; @@ -358,9 +358,10 @@ fn calculate_net_item_delta( #[cfg(test)] mod tests { - use valence_core::item::{ItemKind, ItemStack}; - use valence_core::protocol::var_int::VarInt; - use valence_packet::packets::play::click_slot_c2s::SlotChange; + + use valence_server::protocol::packets::play::click_slot_c2s::SlotChange; + use valence_server::protocol::VarInt; + use valence_server::ItemKind; use super::*; use crate::InventoryKind; diff --git a/crates/valence_lang/Cargo.toml b/crates/valence_lang/Cargo.toml new file mode 100644 index 000000000..07289a06a --- /dev/null +++ b/crates/valence_lang/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "valence_lang" +version.workspace = true +edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true + +[build-dependencies] +anyhow.workspace = true +heck.workspace = true +proc-macro2.workspace = true +quote.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +valence_build_utils.workspace = true \ No newline at end of file diff --git a/crates/valence_generated/build/translation_key.rs b/crates/valence_lang/build.rs similarity index 80% rename from crates/valence_generated/build/translation_key.rs rename to crates/valence_lang/build.rs index 90f5967eb..37fcb5c08 100644 --- a/crates/valence_generated/build/translation_key.rs +++ b/crates/valence_lang/build.rs @@ -2,13 +2,17 @@ use heck::ToShoutySnakeCase; use proc_macro2::TokenStream; use quote::quote; use serde::Deserialize; -use valence_build_utils::{ident, rerun_if_changed}; +use valence_build_utils::{ident, rerun_if_changed, write_generated_file}; -pub fn build() -> anyhow::Result { +pub fn main() -> anyhow::Result<()> { + write_generated_file(build()?, "translation_keys.rs") +} + +fn build() -> anyhow::Result { rerun_if_changed(["../../extracted/translation_keys.json"]); let translations = serde_json::from_str::>(include_str!( - "../../../extracted/translation_keys.json" + "../../extracted/translation_keys.json" ))?; let translation_key_consts = translations diff --git a/crates/valence_lang/src/lib.rs b/crates/valence_lang/src/lib.rs new file mode 100644 index 000000000..8c450a67c --- /dev/null +++ b/crates/valence_lang/src/lib.rs @@ -0,0 +1,6 @@ +/// Contains Rust constants for all of Minecraft's standard translation keys. +/// +/// Use these with `Text::translate`. +pub mod keys { + include!(concat!(env!("OUT_DIR"), "/translation_keys.rs")); +} diff --git a/crates/valence_layer/README.md b/crates/valence_layer/README.md deleted file mode 100644 index c6dd27dae..000000000 --- a/crates/valence_layer/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# valence_layer - -Defines chunk layers and entity layers. Chunk layers contain the chunks and dimension data of a world, while entity layers contain all the Minecraft entities. - -These two together are analogous to Minecraft "levels" or "worlds". diff --git a/crates/valence_network/Cargo.toml b/crates/valence_network/Cargo.toml index 05fd8466e..71133fd23 100644 --- a/crates/valence_network/Cargo.toml +++ b/crates/valence_network/Cargo.toml @@ -3,6 +3,8 @@ name = "valence_network" version.workspace = true edition.workspace = true +# TODO: make encryption and compression optional features. + [dependencies] anyhow.workspace = true async-trait.workspace = true @@ -24,9 +26,12 @@ thiserror.workspace = true tokio.workspace = true tracing.workspace = true uuid.workspace = true -valence_client.workspace = true -valence_core.workspace = true -valence_entity.workspace = true +valence_server.workspace = true +valence_lang.workspace = true +valence_protocol = { workspace = true, features = [ + "encryption", + "compression", +] } [dependencies.reqwest] workspace = true diff --git a/crates/valence_network/src/connect.rs b/crates/valence_network/src/connect.rs index ce1e68f38..82bf8133f 100644 --- a/crates/valence_network/src/connect.rs +++ b/crates/valence_network/src/connect.rs @@ -18,18 +18,20 @@ use sha2::{Digest, Sha256}; use tokio::net::{TcpListener, TcpStream}; use tracing::{error, info, trace, warn}; use uuid::Uuid; -use valence_core::property::Property; -use valence_core::protocol::raw::RawBytes; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::Decode; -use valence_core::text::{Color, IntoText, Text}; -use valence_core::{ident, translation_key, MINECRAFT_VERSION, PROTOCOL_VERSION}; -use valence_packet::packets::handshaking::handshake_c2s::HandshakeNextState; -use valence_packet::packets::handshaking::*; -use valence_packet::packets::login::*; -use valence_packet::packets::status::*; -use valence_packet::protocol::decode::PacketDecoder; -use valence_packet::protocol::encode::PacketEncoder; +use valence_lang::keys; +use valence_protocol::Decode; +use valence_server::protocol::packets::handshaking::handshake_c2s::HandshakeNextState; +use valence_server::protocol::packets::handshaking::HandshakeC2s; +use valence_server::protocol::packets::login::{ + LoginCompressionS2c, LoginDisconnectS2c, LoginHelloC2s, LoginHelloS2c, LoginKeyC2s, + LoginQueryRequestS2c, LoginQueryResponseC2s, LoginSuccessS2c, +}; +use valence_server::protocol::packets::status::{ + QueryPingC2s, QueryPongS2c, QueryRequestC2s, QueryResponseS2c, +}; +use valence_server::protocol::{PacketDecoder, PacketEncoder, Property, RawBytes, VarInt}; +use valence_server::text::{Color, IntoText}; +use valence_server::{ident, Text, MINECRAFT_VERSION, PROTOCOL_VERSION}; use crate::legacy_ping::try_handle_legacy_ping; use crate::packet_io::PacketIo; @@ -279,7 +281,7 @@ async fn handle_login( ConnectionMode::Velocity { secret } => login_velocity(io, username, secret).await?, }; - if let Some(threshold) = shared.0.compression_threshold { + if let Some(threshold) = shared.0.threshold { io.send_packet(&LoginCompressionS2c { threshold: VarInt(threshold as i32), }) @@ -377,10 +379,7 @@ async fn login_online( match resp.status() { StatusCode::OK => {} StatusCode::NO_CONTENT => { - let reason = Text::translate( - translation_key::MULTIPLAYER_DISCONNECT_UNVERIFIED_USERNAME, - [], - ); + let reason = Text::translate(keys::MULTIPLAYER_DISCONNECT_UNVERIFIED_USERNAME, []); io.send_packet(&LoginDisconnectS2c { reason: reason.into(), }) diff --git a/crates/valence_network/src/lib.rs b/crates/valence_network/src/lib.rs index 431c84bf6..259b46b64 100644 --- a/crates/valence_network/src/lib.rs +++ b/crates/valence_network/src/lib.rs @@ -45,9 +45,9 @@ use tokio::sync::Semaphore; use tokio::time; use tracing::error; use uuid::Uuid; -use valence_client::{ClientBundle, ClientBundleArgs, Properties, SpawnClientsSet}; -use valence_core::text::{IntoText, Text}; -use valence_core::{Server, MINECRAFT_VERSION, PROTOCOL_VERSION}; +use valence_protocol::text::IntoText; +use valence_server::client::{ClientBundle, ClientBundleArgs, Properties, SpawnClientsSet}; +use valence_server::{CompressionThreshold, Server, Text, MINECRAFT_VERSION, PROTOCOL_VERSION}; pub struct NetworkPlugin; @@ -60,7 +60,7 @@ impl Plugin for NetworkPlugin { } fn build_plugin(app: &mut App) -> anyhow::Result<()> { - let compression_threshold = app + let threshold = app .world .get_resource::() .context("missing server resource")? @@ -100,7 +100,7 @@ fn build_plugin(app: &mut App) -> anyhow::Result<()> { player_count: AtomicUsize::new(0), max_players: settings.max_players, connection_mode: settings.connection_mode.clone(), - compression_threshold, + threshold, tokio_handle, _tokio_runtime: runtime, new_clients_send, @@ -177,7 +177,7 @@ struct SharedNetworkStateInner { player_count: AtomicUsize, max_players: usize, connection_mode: ConnectionMode, - compression_threshold: Option, + threshold: CompressionThreshold, tokio_handle: Handle, // Holding a runtime handle is not enough to keep tokio working. We need // to store the runtime here so we don't drop it. @@ -617,7 +617,7 @@ pub enum ServerListPing<'a> { /// different protocol. /// /// Can be formatted using `§` and format codes. Or use - /// [`valence_core::text::Text::to_legacy_lossy`]. + /// [`valence_protocol::text::Text::to_legacy_lossy`]. version_name: String, /// The protocol version of the server. protocol: i32, diff --git a/crates/valence_network/src/packet_io.rs b/crates/valence_network/src/packet_io.rs index c7a584f75..0e2653efe 100644 --- a/crates/valence_network/src/packet_io.rs +++ b/crates/valence_network/src/packet_io.rs @@ -10,11 +10,10 @@ use tokio::net::TcpStream; use tokio::sync::Semaphore; use tokio::task::JoinHandle; use tracing::{debug, warn}; -use valence_client::{ClientBundleArgs, ClientConnection, ReceivedPacket}; -use valence_core::protocol::{Decode, Encode}; -use valence_packet::protocol::decode::{PacketDecoder, PacketFrame}; -use valence_packet::protocol::encode::PacketEncoder; -use valence_packet::protocol::Packet; +use valence_protocol::CompressionThreshold; +use valence_server::client::{ClientBundleArgs, ClientConnection, ReceivedPacket}; +use valence_server::protocol::decode::PacketFrame; +use valence_server::protocol::{Decode, Encode, Packet, PacketDecoder, PacketEncoder}; use crate::byte_channel::{byte_channel, ByteSender, TrySendError}; use crate::{CleanupOnDrop, NewClientInfo}; @@ -76,7 +75,7 @@ impl PacketIo { } #[allow(dead_code)] - pub(crate) fn set_compression(&mut self, threshold: Option) { + pub(crate) fn set_compression(&mut self, threshold: CompressionThreshold) { self.enc.set_compression(threshold); self.dec.set_compression(threshold); } diff --git a/crates/valence_player_list/Cargo.toml b/crates/valence_player_list/Cargo.toml index baf933fb1..c1396fdb1 100644 --- a/crates/valence_player_list/Cargo.toml +++ b/crates/valence_player_list/Cargo.toml @@ -4,11 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] -anyhow.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true bitfield-struct.workspace = true -valence_core.workspace = true -valence_client.workspace = true -valence_layer.workspace = true -uuid.workspace = true +valence_server.workspace = true diff --git a/crates/valence_player_list/src/lib.rs b/crates/valence_player_list/src/lib.rs index 445ef7c1a..0eeb5c730 100644 --- a/crates/valence_player_list/src/lib.rs +++ b/crates/valence_player_list/src/lib.rs @@ -22,18 +22,17 @@ use std::borrow::Cow; use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use uuid::Uuid; -use valence_client::{Client, Ping, Properties, Username}; -use valence_core::despawn::Despawned; -use valence_core::game_mode::GameMode; -use valence_core::text::{IntoText, Text}; -use valence_core::uuid::UniqueId; -use valence_core::Server; -use valence_layer::UpdateLayersPreClientSet; -use valence_packet::packets::play::{ +use valence_server::client::{Client, Properties, Username}; +use valence_server::keepalive::Ping; +use valence_server::layer::UpdateLayersPreClientSet; +use valence_server::protocol::encode::PacketWriter; +use valence_server::protocol::packets::play::{ player_list_s2c as packet, PlayerListHeaderS2c, PlayerListS2c, PlayerRemoveS2c, }; -use valence_packet::protocol::encode::{PacketWriter, WritePacket}; +use valence_server::protocol::WritePacket; +use valence_server::text::IntoText; +use valence_server::uuid::Uuid; +use valence_server::{Despawned, GameMode, Server, Text, UniqueId}; pub struct PlayerListPlugin; diff --git a/crates/valence_protocol/src/block_pos.rs b/crates/valence_protocol/src/block_pos.rs index 4d016917e..449226392 100644 --- a/crates/valence_protocol/src/block_pos.rs +++ b/crates/valence_protocol/src/block_pos.rs @@ -39,8 +39,7 @@ impl BlockPos { /// direction. /// /// ``` - /// use valence_protocol::block_pos::BlockPos; - /// use valence_protocol::direction::Direction; + /// use valence_protocol::{BlockPos, Direction}; /// /// let pos = BlockPos::new(0, 0, 0); /// let adj = pos.get_in_direction(Direction::South); diff --git a/crates/valence_protocol/src/decode.rs b/crates/valence_protocol/src/decode.rs index 1b73da61a..5fa431175 100644 --- a/crates/valence_protocol/src/decode.rs +++ b/crates/valence_protocol/src/decode.rs @@ -6,7 +6,7 @@ use anyhow::{bail, ensure, Context}; use bytes::{Buf, BytesMut}; use crate::var_int::{VarInt, VarIntDecodeError}; -use crate::{Decode, Packet, MAX_PACKET_SIZE}; +use crate::{CompressionThreshold, Decode, Packet, MAX_PACKET_SIZE}; /// The AES block cipher with a 128 bit key, using the CFB-8 mode of /// operation. @@ -19,7 +19,7 @@ pub struct PacketDecoder { #[cfg(feature = "compression")] decompress_buf: BytesMut, #[cfg(feature = "compression")] - compression_threshold: Option, + threshold: CompressionThreshold, #[cfg(feature = "encryption")] cipher: Option, } @@ -53,7 +53,7 @@ impl PacketDecoder { let mut data; #[cfg(feature = "compression")] - if let Some(threshold) = self.compression_threshold { + if let Some(threshold) = self.threshold { use std::io::Write; use bytes::BufMut; @@ -137,13 +137,13 @@ impl PacketDecoder { } #[cfg(feature = "compression")] - pub fn compression(&self) -> Option { - self.compression_threshold + pub fn compression(&self) -> CompressionThreshold { + self.threshold } #[cfg(feature = "compression")] - pub fn set_compression(&mut self, threshold: Option) { - self.compression_threshold = threshold; + pub fn set_compression(&mut self, threshold: CompressionThreshold) { + self.threshold = threshold; } #[cfg(feature = "encryption")] diff --git a/crates/valence_protocol/src/encode.rs b/crates/valence_protocol/src/encode.rs index 5b958a193..474ecf771 100644 --- a/crates/valence_protocol/src/encode.rs +++ b/crates/valence_protocol/src/encode.rs @@ -9,7 +9,7 @@ use bytes::{BufMut, BytesMut}; use tracing::warn; use crate::var_int::VarInt; -use crate::{Encode, Packet, MAX_PACKET_SIZE}; +use crate::{CompressionThreshold, Encode, Packet, MAX_PACKET_SIZE}; /// The AES block cipher with a 128 bit key, using the CFB-8 mode of /// operation. @@ -22,7 +22,7 @@ pub struct PacketEncoder { #[cfg(feature = "compression")] compress_buf: Vec, #[cfg(feature = "compression")] - compression_threshold: Option, + threshold: CompressionThreshold, #[cfg(feature = "encryption")] cipher: Option, } @@ -69,7 +69,7 @@ impl PacketEncoder { let data_len = self.buf.len() - start_len; #[cfg(feature = "compression")] - if let Some(threshold) = self.compression_threshold { + if let Some(threshold) = self.threshold { use std::io::Read; use flate2::bufread::ZlibEncoder; @@ -163,8 +163,8 @@ impl PacketEncoder { } #[cfg(feature = "compression")] - pub fn set_compression(&mut self, threshold: Option) { - self.compression_threshold = threshold; + pub fn set_compression(&mut self, threshold: CompressionThreshold) { + self.threshold = threshold; } /// Encrypts all future packets **and any packets that have @@ -235,11 +235,11 @@ impl WritePacket for bevy_ecs::world::Mut<'_, T> { #[derive(Debug)] pub struct PacketWriter<'a> { pub buf: &'a mut Vec, - pub threshold: Option, + pub threshold: CompressionThreshold, } impl<'a> PacketWriter<'a> { - pub fn new(buf: &'a mut Vec, threshold: Option) -> Self { + pub fn new(buf: &'a mut Vec, threshold: CompressionThreshold) -> Self { Self { buf, threshold } } } diff --git a/crates/valence_protocol/src/item.rs b/crates/valence_protocol/src/item.rs index d9e3936cc..ab28bfeb7 100644 --- a/crates/valence_protocol/src/item.rs +++ b/crates/valence_protocol/src/item.rs @@ -6,6 +6,7 @@ use valence_nbt::Compound; use crate::{Decode, Encode}; +/// A stack of items in an inventory. #[derive(Clone, PartialEq, Debug)] pub struct ItemStack { pub item: ItemKind, diff --git a/crates/valence_protocol/src/lib.rs b/crates/valence_protocol/src/lib.rs index 3a5fa94bc..4ef9822e4 100644 --- a/crates/valence_protocol/src/lib.rs +++ b/crates/valence_protocol/src/lib.rs @@ -1,8 +1,21 @@ -use std::io::Write; - -use anyhow::Context; -pub use valence_protocol_macros::{Decode, Encode, Packet}; -use var_int::VarInt; +// #![doc = include_str!("../README.md")] +#![deny( + rustdoc::broken_intra_doc_links, + rustdoc::private_intra_doc_links, + // rustdoc::missing_crate_level_docs, + rustdoc::invalid_codeblock_attributes, + rustdoc::invalid_rust_codeblocks, + rustdoc::bare_urls, + rustdoc::invalid_html_tags +)] +#![warn( + trivial_casts, + trivial_numeric_casts, + unused_lifetimes, + unused_import_braces, + unreachable_pub, + clippy::dbg_macro +)] /// Used only by macros. Not public API. #[doc(hidden)] @@ -16,28 +29,58 @@ pub mod __private { // This allows us to use our own proc macros internally. extern crate self as valence_protocol; -pub mod array; -pub mod block_pos; -pub mod byte_angle; -pub mod chunk_pos; -pub mod chunk_view; +mod array; +mod block_pos; +mod byte_angle; +mod chunk_pos; pub mod decode; -pub mod difficulty; -pub mod direction; +mod difficulty; +mod direction; pub mod encode; -pub mod game_mode; -pub mod global_pos; -pub mod hand; +mod game_mode; +mod global_pos; +mod hand; mod impls; pub mod item; -pub mod player_textures; -pub mod property; -pub mod raw; +pub mod packets; +mod player_textures; +mod property; +mod raw; pub mod sound; pub mod var_int; -pub mod var_long; -pub use {valence_ident as ident, valence_math as math, valence_text as text}; -pub mod packets; +mod var_long; + +use std::io::Write; + +use anyhow::Context; +pub use array::LengthPrefixedArray; +pub use block::{BlockKind, BlockState}; +pub use block_pos::BlockPos; +pub use byte_angle::ByteAngle; +pub use chunk_pos::ChunkPos; +pub use decode::PacketDecoder; +pub use direction::Direction; +pub use encode::{PacketEncoder, WritePacket}; +pub use game_mode::GameMode; +pub use global_pos::GlobalPos; +pub use hand::Hand; +pub use ident::ident; +pub use item::{ItemKind, ItemStack}; +pub use packets::play::particle_s2c::Particle; +pub use player_textures::PlayerTextures; +pub use property::Property; +pub use raw::RawBytes; +pub use sound::Sound; +pub use text::Text; +pub use valence_generated::{block, packet_id}; +pub use valence_ident::Ident; +pub use valence_protocol_macros::{Decode, Encode, Packet}; +pub use var_int::VarInt; +pub use var_long::VarLong; +pub use { + anyhow, bytes, uuid, valence_ident as ident, valence_math as math, valence_nbt as nbt, + valence_text as text, +}; /// The maximum number of bytes in a single Minecraft packet. pub const MAX_PACKET_SIZE: i32 = 2097152; @@ -49,6 +92,13 @@ pub const PROTOCOL_VERSION: i32 = 763; /// targets. pub const MINECRAFT_VERSION: &str = "1.20.1"; +/// Type alias for the compression threshold. +/// +/// For a compression threshold of `Some(N)`, packets with encoded lengths >= +/// `N` are compressed while all others are not. `None` disables compression +/// completely. +pub type CompressionThreshold = Option; + /// The `Encode` trait allows objects to be written to the Minecraft protocol. /// It is the inverse of [`Decode`]. /// @@ -95,7 +145,7 @@ pub const MINECRAFT_VERSION: &str = "1.20.1"; /// println!("{buf:?}"); /// ``` /// -/// [macro]: valence_core_macros::Encode +/// [macro]: valence_protocol_macros::Encode /// [`VarInt`]: var_int::VarInt pub trait Encode { /// Writes this object to the provided writer. @@ -180,7 +230,7 @@ pub trait Encode { /// assert!(r.is_empty()); /// ``` /// -/// [macro]: valence_core_macros::Decode +/// [macro]: valence_protocol_macros::Decode /// [`VarInt`]: var_int::VarInt pub trait Decode<'a>: Sized { /// Reads this object from the provided byte slice. @@ -219,7 +269,7 @@ pub trait Packet: std::fmt::Debug { } } -/// The side a packet is intended for +/// The side a packet is intended for. #[derive(Copy, Clone, PartialEq, Eq)] pub enum PacketSide { /// Server -> Client @@ -228,7 +278,7 @@ pub enum PacketSide { Serverbound, } -/// The state which a packet is used +/// The statein which a packet is used. #[derive(Copy, Clone, PartialEq, Eq)] pub enum PacketState { Handshaking, @@ -249,11 +299,11 @@ mod tests { use crate::decode::PacketDecoder; use crate::encode::PacketEncoder; use crate::hand::Hand; - use crate::ident::Ident; use crate::item::{ItemKind, ItemStack}; use crate::text::{IntoText, Text}; use crate::var_int::VarInt; use crate::var_long::VarLong; + use crate::Ident; #[derive(Encode, Decode, Packet, Debug)] #[packet(id = 1, side = PacketSide::Clientbound)] diff --git a/crates/valence_protocol/src/packets.rs b/crates/valence_protocol/src/packets.rs index 1a3072dc1..d377d5fc1 100644 --- a/crates/valence_protocol/src/packets.rs +++ b/crates/valence_protocol/src/packets.rs @@ -5,12 +5,11 @@ use anyhow::bail; use uuid::Uuid; use valence_generated::packet_id; -use crate::ident::Ident; use crate::property::Property; use crate::raw::RawBytes; use crate::text::Text; use crate::var_int::VarInt; -use crate::{Decode, Encode, Packet, PacketState}; +use crate::{Decode, Encode, Ident, Packet, PacketState}; pub mod handshaking; pub mod login; diff --git a/crates/valence_registry/Cargo.toml b/crates/valence_registry/Cargo.toml index 2dba59736..73072a4fe 100644 --- a/crates/valence_registry/Cargo.toml +++ b/crates/valence_registry/Cargo.toml @@ -10,5 +10,8 @@ indexmap.workspace = true serde_json.workspace = true serde.workspace = true tracing.workspace = true -valence_core.workspace = true -valence_nbt.workspace = true \ No newline at end of file +valence_protocol.workspace = true +anyhow.workspace = true +valence_ident.workspace = true +valence_nbt = { workspace = true, features = ["serde"] } +valence_server_core.workspace = true diff --git a/crates/valence_biome/src/lib.rs b/crates/valence_registry/src/biome.rs similarity index 84% rename from crates/valence_biome/src/lib.rs rename to crates/valence_registry/src/biome.rs index b61c52b65..b6048e76f 100644 --- a/crates/valence_biome/src/lib.rs +++ b/crates/valence_registry/src/biome.rs @@ -1,21 +1,12 @@ -#![doc = include_str!("../README.md")] -#![deny( - rustdoc::broken_intra_doc_links, - rustdoc::private_intra_doc_links, - rustdoc::missing_crate_level_docs, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_rust_codeblocks, - rustdoc::bare_urls, - rustdoc::invalid_html_tags -)] -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_lifetimes, - unused_import_braces, - unreachable_pub, - clippy::dbg_macro -)] +//! Contains biomes and the biome registry. Minecraft's default biomes are added +//! to the registry by default. +//! +//! ### **NOTE:** +//! - Modifying the biome registry after the server has started can +//! break invariants within instances and clients! Make sure there are no +//! instances or clients spawned before mutating. +//! - A biome named "minecraft:plains" must exist. Otherwise, vanilla clients +//! will be disconnected. use std::ops::{Deref, DerefMut}; @@ -23,11 +14,11 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use serde::{Deserialize, Serialize}; use tracing::error; -use valence_core::ident; -use valence_core::ident::Ident; +use valence_ident::{ident, Ident}; use valence_nbt::serde::CompoundSerializer; -use valence_registry::codec::{RegistryCodec, RegistryValue}; -use valence_registry::{Registry, RegistryIdx, RegistrySet}; + +use crate::codec::{RegistryCodec, RegistryValue}; +use crate::{Registry, RegistryIdx, RegistrySet}; pub struct BiomePlugin; diff --git a/crates/valence_registry/src/codec.rs b/crates/valence_registry/src/codec.rs index 2c570bd94..aa71fa689 100644 --- a/crates/valence_registry/src/codec.rs +++ b/crates/valence_registry/src/codec.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use bevy_app::prelude::*; use bevy_ecs::prelude::*; use tracing::error; -use valence_core::ident::Ident; +use valence_ident::Ident; use valence_nbt::{compound, Compound, List, Value}; use crate::RegistrySet; diff --git a/crates/valence_dimension/src/lib.rs b/crates/valence_registry/src/dimension_type.rs similarity index 87% rename from crates/valence_dimension/src/lib.rs rename to crates/valence_registry/src/dimension_type.rs index 78c4e7bfe..fccdedbb8 100644 --- a/crates/valence_dimension/src/lib.rs +++ b/crates/valence_registry/src/dimension_type.rs @@ -1,36 +1,25 @@ -#![doc = include_str!("../README.md")] -#![deny( - rustdoc::broken_intra_doc_links, - rustdoc::private_intra_doc_links, - rustdoc::missing_crate_level_docs, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_rust_codeblocks, - rustdoc::bare_urls, - rustdoc::invalid_html_tags -)] -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_lifetimes, - unused_import_braces, - unreachable_pub, - clippy::dbg_macro -)] +//! Contains dimension types and the dimension type registry. Minecraft's +//! default dimensions are added to the registry by default. +//! +//! ### **NOTE:** +//! - Modifying the dimension type registry after the server has started can +//! break invariants within instances and clients! Make sure there are no +//! instances or clients spawned before mutating. use std::ops::{Deref, DerefMut}; use bevy_app::prelude::*; use bevy_ecs::prelude::*; use serde::{Deserialize, Serialize}; -use tracing::{error, warn}; -use valence_core::ident; -use valence_core::ident::Ident; +use tracing::error; +use valence_ident::{ident, Ident}; use valence_nbt::serde::CompoundSerializer; -use valence_registry::codec::{RegistryCodec, RegistryValue}; -use valence_registry::{Registry, RegistryIdx, RegistrySet}; -pub struct DimensionPlugin; -impl Plugin for DimensionPlugin { +use crate::codec::{RegistryCodec, RegistryValue}; +use crate::{Registry, RegistryIdx, RegistrySet}; +pub struct DimensionTypePlugin; + +impl Plugin for DimensionTypePlugin { fn build(&self, app: &mut App) { app.init_resource::() .add_systems(PreStartup, load_default_dimension_types) diff --git a/crates/valence_registry/src/lib.rs b/crates/valence_registry/src/lib.rs index 0984f60c4..d9a59b105 100644 --- a/crates/valence_registry/src/lib.rs +++ b/crates/valence_registry/src/lib.rs @@ -17,7 +17,9 @@ clippy::dbg_macro )] +pub mod biome; pub mod codec; +pub mod dimension_type; pub mod tags; use std::fmt::Debug; @@ -26,10 +28,14 @@ use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use bevy_app::prelude::*; -pub use bevy_ecs::prelude::*; +use bevy_ecs::prelude::*; +pub use biome::BiomeRegistry; +pub use codec::RegistryCodec; +pub use dimension_type::DimensionTypeRegistry; use indexmap::map::Entry; use indexmap::IndexMap; -use valence_core::ident::Ident; +pub use tags::TagsRegistry; +use valence_ident::Ident; pub struct RegistryPlugin; diff --git a/crates/valence_registry/src/tags.rs b/crates/valence_registry/src/tags.rs index 5e9ae25eb..833227951 100644 --- a/crates/valence_registry/src/tags.rs +++ b/crates/valence_registry/src/tags.rs @@ -2,10 +2,10 @@ use std::borrow::Cow; use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::Server; -pub use valence_packet::packets::play::synchronize_tags_s2c::Registry; -use valence_packet::packets::play::SynchronizeTagsS2c; -use valence_packet::protocol::encode::{PacketWriter, WritePacket}; +use valence_protocol::encode::{PacketWriter, WritePacket}; +pub use valence_protocol::packets::play::synchronize_tags_s2c::Registry; +use valence_protocol::packets::play::SynchronizeTagsS2c; +use valence_server_core::Server; use crate::RegistrySet; @@ -33,7 +33,7 @@ impl TagsRegistry { } } -pub fn init_tags_registry(mut tags: ResMut) { +fn init_tags_registry(mut tags: ResMut) { let registries = serde_json::from_str::>(include_str!("../../../extracted/tags.json")) .expect("tags.json is invalid"); @@ -53,14 +53,12 @@ pub(crate) fn cache_tags_packet(server: Res, tags: ResMut) #[cfg(test)] mod tests { - use super::*; - use crate::RegistryPlugin; - + /* TODO: move this to src/tests/ #[test] fn smoke_test() { let mut app = bevy_app::App::new(); app.add_plugins(RegistryPlugin); - app.insert_resource(Server::default()); + // app.insert_resource(Server::default()); app.update(); let tags_registry = app.world.get_resource::().unwrap(); @@ -68,4 +66,5 @@ mod tests { assert!(!packet.registries.is_empty()); assert!(!tags_registry.cached_packet.is_empty()); } + */ } diff --git a/crates/valence_scoreboard/Cargo.toml b/crates/valence_scoreboard/Cargo.toml index 63523c703..ad99a3d84 100644 --- a/crates/valence_scoreboard/Cargo.toml +++ b/crates/valence_scoreboard/Cargo.toml @@ -6,8 +6,5 @@ edition = "2021" [dependencies] bevy_app.workspace = true bevy_ecs.workspace = true -valence_client.workspace = true -valence_core.workspace = true -valence_entity.workspace = true -valence_layer.workspace = true +valence_server.workspace = true tracing.workspace = true diff --git a/crates/valence_scoreboard/README.md b/crates/valence_scoreboard/README.md index 3b7173e93..65a04a85d 100644 --- a/crates/valence_scoreboard/README.md +++ b/crates/valence_scoreboard/README.md @@ -11,7 +11,7 @@ Example: ```rust # use bevy_ecs::prelude::*; use valence_scoreboard::*; -use valence_core::text::IntoText; +use valence_protocol::text::IntoText; fn spawn_scoreboard(mut commands: Commands) { commands.spawn(ObjectiveBundle { diff --git a/crates/valence_scoreboard/src/components.rs b/crates/valence_scoreboard/src/components.rs index 7c7b90089..71342fdbe 100644 --- a/crates/valence_scoreboard/src/components.rs +++ b/crates/valence_scoreboard/src/components.rs @@ -1,10 +1,11 @@ use std::collections::HashMap; use bevy_ecs::prelude::*; -use valence_core::text::{IntoText, Text}; -use valence_entity::EntityLayerId; -use valence_packet::packets::play::scoreboard_display_s2c::ScoreboardPosition; -use valence_packet::packets::play::scoreboard_objective_update_s2c::ObjectiveRenderType; +use valence_server::entity::EntityLayerId; +use valence_server::protocol::packets::play::scoreboard_display_s2c::ScoreboardPosition; +use valence_server::protocol::packets::play::scoreboard_objective_update_s2c::ObjectiveRenderType; +use valence_server::text::IntoText; +use valence_server::Text; /// A string that identifies an objective. There is one scoreboard per /// objective.It's generally not safe to modify this after it's been created. diff --git a/crates/valence_scoreboard/src/lib.rs b/crates/valence_scoreboard/src/lib.rs index 635044083..e7a2b9a68 100644 --- a/crates/valence_scoreboard/src/lib.rs +++ b/crates/valence_scoreboard/src/lib.rs @@ -18,27 +18,28 @@ )] #![allow(clippy::type_complexity)] +mod components; use std::collections::BTreeSet; use bevy_app::prelude::*; use bevy_ecs::change_detection::DetectChanges; use bevy_ecs::prelude::*; -use tracing::{debug, warn}; - -mod components; pub use components::*; -use valence_client::{Client, OldVisibleEntityLayers, VisibleEntityLayers}; -use valence_core::__private::VarInt; -use valence_core::despawn::Despawned; -use valence_core::text::IntoText; -use valence_entity::EntityLayerId; -use valence_layer::{EntityLayer, UpdateLayersPreClientSet}; -pub use valence_packet::packets::play::scoreboard_display_s2c::ScoreboardPosition; -use valence_packet::packets::play::scoreboard_display_s2c::*; -pub use valence_packet::packets::play::scoreboard_objective_update_s2c::ObjectiveRenderType; -use valence_packet::packets::play::scoreboard_objective_update_s2c::*; -use valence_packet::packets::play::scoreboard_player_update_s2c::*; -use valence_packet::protocol::encode::WritePacket; +use tracing::{debug, warn}; +use valence_server::client::{Client, OldVisibleEntityLayers, VisibleEntityLayers}; +use valence_server::entity::EntityLayerId; +use valence_server::layer::UpdateLayersPreClientSet; +use valence_server::protocol::packets::play::scoreboard_display_s2c::ScoreboardPosition; +use valence_server::protocol::packets::play::scoreboard_objective_update_s2c::{ + ObjectiveMode, ObjectiveRenderType, +}; +use valence_server::protocol::packets::play::scoreboard_player_update_s2c::ScoreboardPlayerUpdateAction; +use valence_server::protocol::packets::play::{ + ScoreboardDisplayS2c, ScoreboardObjectiveUpdateS2c, ScoreboardPlayerUpdateS2c, +}; +use valence_server::protocol::{VarInt, WritePacket}; +use valence_server::text::IntoText; +use valence_server::{Despawned, EntityLayer}; /// Provides all necessary systems to manage scoreboards. pub struct ScoreboardPlugin; diff --git a/crates/valence_layer/Cargo.toml b/crates/valence_server/Cargo.toml similarity index 52% rename from crates/valence_layer/Cargo.toml rename to crates/valence_server/Cargo.toml index 15c501279..bfc0a455d 100644 --- a/crates/valence_layer/Cargo.toml +++ b/crates/valence_server/Cargo.toml @@ -1,22 +1,30 @@ [package] -name = "valence_layer" +name = "valence_server" version.workspace = true edition.workspace = true +repository.workspace = true +documentation.workspace = true +license.workspace = true [dependencies] anyhow.workspace = true -arrayvec.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true +bevy_utils.workspace = true # Needed for `ScheduleLabel` derive macro. +bitfield-struct.workspace = true +bytes.workspace = true valence_math.workspace = true -num-integer.workspace = true -parking_lot.workspace = true rand.workspace = true -rustc-hash.workspace = true -valence_biome.workspace = true -valence_core.workspace = true -valence_dimension.workspace = true +tracing.workspace = true +uuid.workspace = true +byteorder.workspace = true +valence_server_core.workspace = true valence_entity.workspace = true valence_nbt.workspace = true valence_registry.workspace = true -tracing.workspace = true +valence_protocol.workspace = true +valence_generated.workspace = true +rustc-hash.workspace = true +parking_lot.workspace = true +num-integer.workspace = true +arrayvec.workspace = true diff --git a/crates/valence_client/src/action.rs b/crates/valence_server/src/action.rs similarity index 80% rename from crates/valence_client/src/action.rs rename to crates/valence_server/src/action.rs index 05f36fe1d..320377608 100644 --- a/crates/valence_client/src/action.rs +++ b/crates/valence_server/src/action.rs @@ -1,19 +1,23 @@ -use valence_core::block_pos::BlockPos; -use valence_core::direction::Direction; -use valence_core::protocol::var_int::VarInt; -use valence_packet::packets::play::player_action_c2s::PlayerAction; -use valence_packet::packets::play::{PlayerActionC2s, PlayerActionResponseS2c}; +use bevy_app::prelude::*; +use bevy_ecs::prelude::*; +use valence_protocol::packets::play::player_action_c2s::PlayerAction; +use valence_protocol::packets::play::{PlayerActionC2s, PlayerActionResponseS2c}; +use valence_protocol::{BlockPos, Direction, VarInt, WritePacket}; -use super::*; +use crate::client::{Client, UpdateClientsSet}; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_player_action) - .add_systems( - PostUpdate, - acknowledge_player_actions.in_set(UpdateClientsSet), - ); +pub struct ActionPlugin; + +impl Plugin for ActionPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_player_action) + .add_systems( + PostUpdate, + acknowledge_player_actions.in_set(UpdateClientsSet), + ); + } } #[derive(Event, Copy, Clone, Debug)] diff --git a/crates/valence_protocol/src/chunk_view.rs b/crates/valence_server/src/chunk_view.rs similarity index 97% rename from crates/valence_protocol/src/chunk_view.rs rename to crates/valence_server/src/chunk_view.rs index 9d1b43e71..eb1503460 100644 --- a/crates/valence_protocol/src/chunk_view.rs +++ b/crates/valence_server/src/chunk_view.rs @@ -1,8 +1,5 @@ -// TODO: move this module out of `valence_protocol`. - use valence_generated::chunk_view::{CHUNK_VIEW_LUT, EXTRA_VIEW_RADIUS, MAX_VIEW_DIST}; - -use crate::chunk_pos::ChunkPos; +use valence_protocol::ChunkPos; /// Represents the set of all chunk positions that a client can see, defined by /// a center chunk position `pos` and view distance `dist`. diff --git a/crates/valence_client/src/lib.rs b/crates/valence_server/src/client.rs similarity index 84% rename from crates/valence_client/src/lib.rs rename to crates/valence_server/src/client.rs index 437ce257e..401934fad 100644 --- a/crates/valence_client/src/lib.rs +++ b/crates/valence_server/src/client.rs @@ -1,23 +1,3 @@ -#![doc = include_str!("../README.md")] -#![deny( - rustdoc::broken_intra_doc_links, - rustdoc::private_intra_doc_links, - rustdoc::missing_crate_level_docs, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_rust_codeblocks, - rustdoc::bare_urls, - rustdoc::invalid_html_tags -)] -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_lifetimes, - unused_import_braces, - unreachable_pub, - clippy::dbg_macro -)] -#![allow(clippy::type_complexity)] - use std::borrow::Cow; use std::collections::BTreeSet; use std::fmt; @@ -33,59 +13,31 @@ use byteorder::{NativeEndian, ReadBytesExt}; use bytes::{Bytes, BytesMut}; use tracing::warn; use uuid::Uuid; -use valence_biome::BiomeRegistry; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::{ChunkPos, ChunkView}; -use valence_core::despawn::Despawned; -use valence_core::game_mode::GameMode; -use valence_core::ident::Ident; -use valence_core::property::Property; -use valence_core::protocol::global_pos::GlobalPos; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::Encode; -use valence_core::sound::{Sound, SoundCategory}; -use valence_core::text::{IntoText, Text}; -use valence_core::uuid::UniqueId; use valence_entity::player::PlayerEntityBundle; use valence_entity::query::EntityInitQuery; use valence_entity::tracked_data::TrackedData; use valence_entity::{ - ClearEntityChangesSet, EntityId, EntityLayerId, EntityStatus, Look, OldPosition, Position, - Velocity, + ClearEntityChangesSet, EntityId, EntityStatus, OldPosition, Position, Velocity, }; -use valence_layer::{ChunkLayer, EntityLayer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; use valence_math::{DVec3, Vec3}; -use valence_packet::packets::play::chunk_biome_data_s2c::ChunkBiome; -use valence_packet::packets::play::game_state_change_s2c::GameEventKind; -use valence_packet::packets::play::particle_s2c::Particle; -use valence_packet::packets::play::{ +use valence_protocol::encode::{PacketEncoder, WritePacket}; +use valence_protocol::packets::play::chunk_biome_data_s2c::ChunkBiome; +use valence_protocol::packets::play::game_state_change_s2c::GameEventKind; +use valence_protocol::packets::play::particle_s2c::Particle; +use valence_protocol::packets::play::{ ChunkBiomeDataS2c, ChunkLoadDistanceS2c, ChunkRenderDistanceCenterS2c, DeathMessageS2c, DisconnectS2c, EntitiesDestroyS2c, EntityStatusS2c, EntityTrackerUpdateS2c, - EntityVelocityUpdateS2c, GameJoinS2c, GameStateChangeS2c, ParticleS2c, PlaySoundS2c, - PlayerRespawnS2c, PlayerSpawnPositionS2c, UnloadChunkS2c, + EntityVelocityUpdateS2c, GameStateChangeS2c, ParticleS2c, PlaySoundS2c, UnloadChunkS2c, }; -use valence_packet::protocol::encode::{PacketEncoder, WritePacket}; -use valence_packet::protocol::Packet; +use valence_protocol::sound::{Sound, SoundCategory, SoundId}; +use valence_protocol::text::{IntoText, Text}; +use valence_protocol::var_int::VarInt; +use valence_protocol::{BlockPos, ChunkPos, Encode, GameMode, Packet, Property}; use valence_registry::RegistrySet; +use valence_server_core::{Despawned, UniqueId}; -pub mod action; -pub mod command; -pub mod custom_payload; -pub mod event_loop; -pub mod hand_swing; -pub mod interact_block; -pub mod interact_entity; -pub mod interact_item; -pub mod keepalive; -pub mod message; -pub mod movement; -pub mod op_level; -pub mod resource_pack; -pub mod settings; -pub mod spawn; -pub mod status; -pub mod teleport; -pub mod title; +use crate::layer::{ChunkLayer, EntityLayer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; +use crate::ChunkView; pub struct ClientPlugin; @@ -112,15 +64,15 @@ impl Plugin for ClientPlugin { PostUpdate, ( ( - spawn::initial_join.after(RegistrySet), + crate::spawn::initial_join.after(RegistrySet), update_chunk_load_dist, handle_layer_messages.after(update_chunk_load_dist), update_view_and_layers - .after(spawn::initial_join) + .after(crate::spawn::initial_join) .after(handle_layer_messages), cleanup_chunks_after_client_despawn.after(update_view_and_layers), - spawn::update_respawn_position.after(update_view_and_layers), - spawn::respawn.after(spawn::update_respawn_position), + crate::spawn::update_respawn_position.after(update_view_and_layers), + crate::spawn::respawn.after(crate::spawn::update_respawn_position), update_old_view_dist.after(update_view_and_layers), update_game_mode, update_tracked_data, @@ -142,24 +94,6 @@ impl Plugin for ClientPlugin { FlushPacketsSet, ), ); - - event_loop::build(app); - movement::build(app); - command::build(app); - keepalive::build(app); - interact_entity::build(app); - settings::build(app); - action::build(app); - teleport::build(app); - // weather::build(app); - message::build(app); - custom_payload::build(app); - hand_swing::build(app); - interact_block::build(app); - interact_item::build(app); - op_level::build(app); - resource_pack::build(app); - status::build(app); } } @@ -169,33 +103,33 @@ impl Plugin for ClientPlugin { pub struct ClientBundle { pub marker: ClientMarker, pub client: Client, - pub settings: settings::ClientSettings, + pub settings: crate::client_settings::ClientSettings, pub entity_remove_buf: EntityRemoveBuf, pub username: Username, pub ip: Ip, pub properties: Properties, - pub respawn_pos: RespawnPosition, - pub op_level: op_level::OpLevel, - pub action_sequence: action::ActionSequence, + pub respawn_pos: crate::spawn::RespawnPosition, + pub op_level: crate::op_level::OpLevel, + pub action_sequence: crate::action::ActionSequence, pub view_distance: ViewDistance, pub old_view_distance: OldViewDistance, pub visible_chunk_layer: VisibleChunkLayer, pub old_visible_chunk_layer: OldVisibleChunkLayer, pub visible_entity_layers: VisibleEntityLayers, pub old_visible_entity_layers: OldVisibleEntityLayers, - pub keepalive_state: keepalive::KeepaliveState, - pub ping: Ping, - pub teleport_state: teleport::TeleportState, + pub keepalive_state: crate::keepalive::KeepaliveState, + pub ping: crate::keepalive::Ping, + pub teleport_state: crate::teleport::TeleportState, pub game_mode: GameMode, - pub prev_game_mode: spawn::PrevGameMode, - pub death_location: spawn::DeathLocation, - pub is_hardcore: spawn::IsHardcore, - pub hashed_seed: spawn::HashedSeed, - pub reduced_debug_info: spawn::ReducedDebugInfo, - pub has_respawn_screen: spawn::HasRespawnScreen, - pub is_debug: spawn::IsDebug, - pub is_flat: spawn::IsFlat, - pub portal_cooldown: spawn::PortalCooldown, + pub prev_game_mode: crate::spawn::PrevGameMode, + pub death_location: crate::spawn::DeathLocation, + pub is_hardcore: crate::spawn::IsHardcore, + pub hashed_seed: crate::spawn::HashedSeed, + pub reduced_debug_info: crate::spawn::ReducedDebugInfo, + pub has_respawn_screen: crate::spawn::HasRespawnScreen, + pub is_debug: crate::spawn::IsDebug, + pub is_flat: crate::spawn::IsFlat, + pub portal_cooldown: crate::spawn::PortalCooldown, pub player: PlayerEntityBundle, } @@ -207,33 +141,33 @@ impl ClientBundle { conn: args.conn, enc: args.enc, }, - settings: settings::ClientSettings::default(), - entity_remove_buf: EntityRemoveBuf(vec![]), + settings: Default::default(), + entity_remove_buf: Default::default(), username: Username(args.username), ip: Ip(args.ip), properties: Properties(args.properties), - respawn_pos: RespawnPosition::default(), - op_level: op_level::OpLevel::default(), - action_sequence: action::ActionSequence::default(), - view_distance: ViewDistance::default(), + respawn_pos: Default::default(), + op_level: Default::default(), + action_sequence: Default::default(), + view_distance: Default::default(), old_view_distance: OldViewDistance(2), - visible_chunk_layer: VisibleChunkLayer::default(), + visible_chunk_layer: Default::default(), old_visible_chunk_layer: OldVisibleChunkLayer(Entity::PLACEHOLDER), - visible_entity_layers: VisibleEntityLayers::default(), + visible_entity_layers: Default::default(), old_visible_entity_layers: OldVisibleEntityLayers(BTreeSet::new()), - keepalive_state: keepalive::KeepaliveState::new(), - ping: Ping::default(), - teleport_state: teleport::TeleportState::new(), + keepalive_state: crate::keepalive::KeepaliveState::new(), + ping: Default::default(), + teleport_state: crate::teleport::TeleportState::new(), game_mode: GameMode::default(), - prev_game_mode: spawn::PrevGameMode::default(), - death_location: spawn::DeathLocation::default(), - is_hardcore: spawn::IsHardcore::default(), - is_flat: spawn::IsFlat::default(), - has_respawn_screen: spawn::HasRespawnScreen::default(), - hashed_seed: spawn::HashedSeed::default(), - reduced_debug_info: spawn::ReducedDebugInfo::default(), - is_debug: spawn::IsDebug::default(), - portal_cooldown: spawn::PortalCooldown::default(), + prev_game_mode: Default::default(), + death_location: Default::default(), + is_hardcore: Default::default(), + is_flat: Default::default(), + has_respawn_screen: Default::default(), + hashed_seed: Default::default(), + reduced_debug_info: Default::default(), + is_debug: Default::default(), + portal_cooldown: Default::default(), player: PlayerEntityBundle { uuid: UniqueId(args.uuid), ..Default::default() @@ -267,7 +201,7 @@ pub struct ClientMarker; #[derive(Component)] pub struct Client { conn: Box, - enc: PacketEncoder, + pub(crate) enc: PacketEncoder, } /// Represents the bidirectional packet channel between the server and a client @@ -394,7 +328,10 @@ impl Client { let position = position.into(); self.write_packet(&PlaySoundS2c { - id: sound.to_id(), + id: SoundId::Direct { + id: sound.to_ident().into(), + range: None, + }, category, position: (position * 8.0).as_ivec3(), volume, @@ -447,7 +384,7 @@ impl Command for DisconnectClient { /// in this list will be despawned all at once at the end of the tick. /// /// You should not need to use this directly under normal circumstances. -#[derive(Component, Debug)] +#[derive(Component, Default, Debug)] pub struct EntityRemoveBuf(Vec); impl EntityRemoveBuf { @@ -514,17 +451,6 @@ impl Deref for Properties { #[derive(Component, Clone, PartialEq, Eq, Debug)] pub struct Ip(pub IpAddr); -/// The position and angle that clients will respawn with. Also -/// controls the position that compasses point towards. -#[derive(Component, Copy, Clone, PartialEq, Default, Debug)] -pub struct RespawnPosition { - /// The position that clients will respawn at. This can be changed at any - /// time to set the position that compasses point towards. - pub pos: BlockPos, - /// The yaw angle that clients will respawn with (in degrees). - pub yaw: f32, -} - #[derive(Component, Clone, PartialEq, Eq, Debug)] pub struct ViewDistance(u8); @@ -587,16 +513,6 @@ impl OldViewItem<'_> { } } -/// Delay measured in milliseconds. Negative values indicate absence. -#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct Ping(pub i32); - -impl Default for Ping { - fn default() -> Self { - Self(-1) - } -} - /// A [`Component`] containing a handle to the [`ChunkLayer`] a client can /// see. /// @@ -716,10 +632,10 @@ fn handle_layer_messages( // Global messages for (msg, range) in messages.iter_global() { match msg { - valence_layer::chunk::GlobalMsg::Packet => { + crate::layer::chunk::GlobalMsg::Packet => { client.write_packet_bytes(&bytes[range]); } - valence_layer::chunk::GlobalMsg::PacketExcept { except } => { + crate::layer::chunk::GlobalMsg::PacketExcept { except } => { if self_entity != except { client.write_packet_bytes(&bytes[range]); } @@ -731,15 +647,15 @@ fn handle_layer_messages( // Local messages messages.query_local(old_view, |msg, range| match msg { - valence_layer::chunk::LocalMsg::PacketAt { .. } => { + crate::layer::chunk::LocalMsg::PacketAt { .. } => { client.write_packet_bytes(&bytes[range]); } - valence_layer::chunk::LocalMsg::PacketAtExcept { except, .. } => { + crate::layer::chunk::LocalMsg::PacketAtExcept { except, .. } => { if self_entity != except { client.write_packet_bytes(&bytes[range]); } } - valence_layer::chunk::LocalMsg::RadiusAt { + crate::layer::chunk::LocalMsg::RadiusAt { center, radius_squared, } => { @@ -747,7 +663,7 @@ fn handle_layer_messages( client.write_packet_bytes(&bytes[range]); } } - valence_layer::chunk::LocalMsg::RadiusAtExcept { + crate::layer::chunk::LocalMsg::RadiusAtExcept { center, radius_squared, except, @@ -756,13 +672,13 @@ fn handle_layer_messages( client.write_packet_bytes(&bytes[range]); } } - valence_layer::chunk::LocalMsg::ChangeBiome { pos } => { + crate::layer::chunk::LocalMsg::ChangeBiome { pos } => { chunk_biome_buf.push(ChunkBiome { pos, data: &bytes[range], }); } - valence_layer::chunk::LocalMsg::ChangeChunkState { pos } => { + crate::layer::chunk::LocalMsg::ChangeChunkState { pos } => { match &bytes[range] { [ChunkLayer::LOAD, .., ChunkLayer::UNLOAD] => { // Chunk is being loaded and unloaded on the @@ -801,15 +717,15 @@ fn handle_layer_messages( // Global messages for (msg, range) in messages.iter_global() { match msg { - valence_layer::entity::GlobalMsg::Packet => { + crate::layer::entity::GlobalMsg::Packet => { client.write_packet_bytes(&bytes[range]); } - valence_layer::entity::GlobalMsg::PacketExcept { except } => { + crate::layer::entity::GlobalMsg::PacketExcept { except } => { if self_entity != except { client.write_packet_bytes(&bytes[range]); } } - valence_layer::entity::GlobalMsg::DespawnLayer => { + crate::layer::entity::GlobalMsg::DespawnLayer => { // Remove this entity layer. The changes to the visible entity layer // set will be detected by the `update_view_and_layers` system and // despawning of entities will happen there. @@ -820,7 +736,7 @@ fn handle_layer_messages( // Local messages messages.query_local(old_view, |msg, range| match msg { - valence_layer::entity::LocalMsg::DespawnEntity { pos: _, dest_layer } => { + crate::layer::entity::LocalMsg::DespawnEntity { pos: _, dest_layer } => { if !old_visible_entity_layers.0.contains(&dest_layer) { let mut bytes = &bytes[range]; @@ -831,7 +747,7 @@ fn handle_layer_messages( } } } - valence_layer::entity::LocalMsg::DespawnEntityTransition { + crate::layer::entity::LocalMsg::DespawnEntityTransition { pos: _, dest_pos, } => { @@ -845,7 +761,7 @@ fn handle_layer_messages( } } } - valence_layer::entity::LocalMsg::SpawnEntity { pos: _, src_layer } => { + crate::layer::entity::LocalMsg::SpawnEntity { pos: _, src_layer } => { if !old_visible_entity_layers.0.contains(&src_layer) { let mut bytes = &bytes[range]; @@ -865,7 +781,7 @@ fn handle_layer_messages( } } } - valence_layer::entity::LocalMsg::SpawnEntityTransition { + crate::layer::entity::LocalMsg::SpawnEntityTransition { pos: _, src_pos, } => { @@ -888,15 +804,15 @@ fn handle_layer_messages( } } } - valence_layer::entity::LocalMsg::PacketAt { pos: _ } => { + crate::layer::entity::LocalMsg::PacketAt { pos: _ } => { client.write_packet_bytes(&bytes[range]); } - valence_layer::entity::LocalMsg::PacketAtExcept { pos: _, except } => { + crate::layer::entity::LocalMsg::PacketAtExcept { pos: _, except } => { if self_entity != except { client.write_packet_bytes(&bytes[range]); } } - valence_layer::entity::LocalMsg::RadiusAt { + crate::layer::entity::LocalMsg::RadiusAt { center, radius_squared, } => { @@ -904,7 +820,7 @@ fn handle_layer_messages( client.write_packet_bytes(&bytes[range]); } } - valence_layer::entity::LocalMsg::RadiusAtExcept { + crate::layer::entity::LocalMsg::RadiusAtExcept { center, radius_squared, except, @@ -923,7 +839,7 @@ fn handle_layer_messages( ); } -fn update_view_and_layers( +pub(crate) fn update_view_and_layers( mut clients: Query< ( Entity, diff --git a/crates/valence_client/src/command.rs b/crates/valence_server/src/client_command.rs similarity index 90% rename from crates/valence_client/src/command.rs rename to crates/valence_server/src/client_command.rs index 8f67d905a..b21b8c01b 100644 --- a/crates/valence_client/src/command.rs +++ b/crates/valence_server/src/client_command.rs @@ -2,17 +2,21 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use valence_entity::entity::Flags; use valence_entity::{entity, Pose}; -pub use valence_packet::packets::play::client_command_c2s::ClientCommand; -use valence_packet::packets::play::ClientCommandC2s; +pub use valence_protocol::packets::play::client_command_c2s::ClientCommand; +use valence_protocol::packets::play::ClientCommandC2s; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_event::() - .add_event::() - .add_event::() - .add_systems(EventLoopPreUpdate, handle_client_command); +pub struct ClientCommandPlugin; + +impl Plugin for ClientCommandPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_event::() + .add_event::() + .add_event::() + .add_systems(EventLoopPreUpdate, handle_client_command); + } } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] diff --git a/crates/valence_client/src/settings.rs b/crates/valence_server/src/client_settings.rs similarity index 81% rename from crates/valence_client/src/settings.rs rename to crates/valence_server/src/client_settings.rs index 2c99d32ab..1b058ecd3 100644 --- a/crates/valence_client/src/settings.rs +++ b/crates/valence_server/src/client_settings.rs @@ -1,14 +1,18 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use valence_entity::player::{self, PlayerModelParts}; -use valence_packet::packets::play::client_settings_c2s::ChatMode; -use valence_packet::packets::play::ClientSettingsC2s; +use valence_protocol::packets::play::client_settings_c2s::ChatMode; +use valence_protocol::packets::play::ClientSettingsC2s; +use crate::client::ViewDistance; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -use crate::ViewDistance; -pub(super) fn build(app: &mut App) { - app.add_systems(EventLoopPreUpdate, handle_client_settings); +pub struct ClientSettingsPlugin; + +impl Plugin for ClientSettingsPlugin { + fn build(&self, app: &mut App) { + app.add_systems(EventLoopPreUpdate, handle_client_settings); + } } /// Component containing client-controlled settings about a client. diff --git a/crates/valence_client/src/custom_payload.rs b/crates/valence_server/src/custom_payload.rs similarity index 66% rename from crates/valence_client/src/custom_payload.rs rename to crates/valence_server/src/custom_payload.rs index 5f35ad7d4..6d545ea32 100644 --- a/crates/valence_client/src/custom_payload.rs +++ b/crates/valence_server/src/custom_payload.rs @@ -1,11 +1,18 @@ -use valence_packet::packets::play::{CustomPayloadC2s, CustomPayloadS2c}; +use bevy_app::prelude::*; +use bevy_ecs::prelude::*; +use valence_protocol::packets::play::{CustomPayloadC2s, CustomPayloadS2c}; +use valence_protocol::{Ident, WritePacket}; -use super::*; +use crate::client::Client; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_custom_payload); +pub struct CustomPayloadPlugin; + +impl Plugin for CustomPayloadPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_custom_payload); + } } #[derive(Event, Clone, Debug)] diff --git a/crates/valence_client/src/event_loop.rs b/crates/valence_server/src/event_loop.rs similarity index 88% rename from crates/valence_client/src/event_loop.rs rename to crates/valence_server/src/event_loop.rs index b2be540ee..1e43703ac 100644 --- a/crates/valence_client/src/event_loop.rs +++ b/crates/valence_server/src/event_loop.rs @@ -7,22 +7,25 @@ use bevy_ecs::schedule::ScheduleLabel; use bevy_ecs::system::SystemState; use bytes::Bytes; use tracing::{debug, warn}; -use valence_core::protocol::Decode; -use valence_packet::protocol::Packet; - -use crate::Client; - -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_schedule(RunEventLoop, Schedule::new()) - .add_schedule(EventLoopPreUpdate, Schedule::new()) - .add_schedule(EventLoopUpdate, Schedule::new()) - .add_schedule(EventLoopPostUpdate, Schedule::new()) - .add_systems(RunEventLoop, run_event_loop); - - app.world - .resource_mut::() - .insert_after(PreUpdate, RunEventLoop); +use valence_protocol::{Decode, Packet}; + +use crate::client::Client; + +pub struct EventLoopPlugin; + +impl Plugin for EventLoopPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_schedule(RunEventLoop, Schedule::new()) + .add_schedule(EventLoopPreUpdate, Schedule::new()) + .add_schedule(EventLoopUpdate, Schedule::new()) + .add_schedule(EventLoopPostUpdate, Schedule::new()) + .add_systems(RunEventLoop, run_event_loop); + + app.world + .resource_mut::() + .insert_after(PreUpdate, RunEventLoop); + } } /// The schedule responsible for running [`EventLoopPreUpdate`], diff --git a/crates/valence_client/src/hand_swing.rs b/crates/valence_server/src/hand_swing.rs similarity index 77% rename from crates/valence_client/src/hand_swing.rs rename to crates/valence_server/src/hand_swing.rs index ebf70bef4..1b5acfc3e 100644 --- a/crates/valence_client/src/hand_swing.rs +++ b/crates/valence_server/src/hand_swing.rs @@ -1,14 +1,18 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::hand::Hand; use valence_entity::{EntityAnimation, EntityAnimations}; -use valence_packet::packets::play::HandSwingC2s; +use valence_protocol::packets::play::HandSwingC2s; +use valence_protocol::Hand; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_hand_swing); +pub struct HandSwingPlugin; + +impl Plugin for HandSwingPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_hand_swing); + } } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] diff --git a/crates/valence_client/src/interact_block.rs b/crates/valence_server/src/interact_block.rs similarity index 82% rename from crates/valence_client/src/interact_block.rs rename to crates/valence_server/src/interact_block.rs index 229145e3d..ff723a904 100644 --- a/crates/valence_client/src/interact_block.rs +++ b/crates/valence_server/src/interact_block.rs @@ -1,17 +1,19 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::block_pos::BlockPos; -use valence_core::direction::Direction; -use valence_core::hand::Hand; use valence_math::Vec3; -use valence_packet::packets::play::PlayerInteractBlockC2s; +use valence_protocol::packets::play::PlayerInteractBlockC2s; +use valence_protocol::{BlockPos, Direction, Hand}; use crate::action::ActionSequence; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_interact_block); +pub struct InteractBlockPlugin; + +impl Plugin for InteractBlockPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_interact_block); + } } #[derive(Event, Copy, Clone, Debug)] diff --git a/crates/valence_client/src/interact_entity.rs b/crates/valence_server/src/interact_entity.rs similarity index 77% rename from crates/valence_client/src/interact_entity.rs rename to crates/valence_server/src/interact_entity.rs index c6025843b..a1e645e95 100644 --- a/crates/valence_client/src/interact_entity.rs +++ b/crates/valence_server/src/interact_entity.rs @@ -1,14 +1,18 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use valence_entity::EntityManager; -pub use valence_packet::packets::play::player_interact_entity_c2s::EntityInteraction; -use valence_packet::packets::play::PlayerInteractEntityC2s; +pub use valence_protocol::packets::play::player_interact_entity_c2s::EntityInteraction; +use valence_protocol::packets::play::PlayerInteractEntityC2s; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_interact_entity); +pub struct InteractEntityPlugin; + +impl Plugin for InteractEntityPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_interact_entity); + } } #[derive(Event, Copy, Clone, Debug)] diff --git a/crates/valence_client/src/interact_item.rs b/crates/valence_server/src/interact_item.rs similarity index 73% rename from crates/valence_client/src/interact_item.rs rename to crates/valence_server/src/interact_item.rs index 09f61080c..335e9ab05 100644 --- a/crates/valence_client/src/interact_item.rs +++ b/crates/valence_server/src/interact_item.rs @@ -1,14 +1,18 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::hand::Hand; -use valence_packet::packets::play::PlayerInteractItemC2s; +use valence_protocol::packets::play::PlayerInteractItemC2s; +use valence_protocol::Hand; use crate::action::ActionSequence; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_player_interact_item); +pub struct InteractItemPlugin; + +impl Plugin for InteractItemPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_player_interact_item); + } } #[derive(Event, Copy, Clone, Debug)] diff --git a/crates/valence_client/src/keepalive.rs b/crates/valence_server/src/keepalive.rs similarity index 77% rename from crates/valence_client/src/keepalive.rs rename to crates/valence_server/src/keepalive.rs index 284160bc0..fab5368e0 100644 --- a/crates/valence_client/src/keepalive.rs +++ b/crates/valence_server/src/keepalive.rs @@ -1,14 +1,22 @@ -use std::time::Duration; +use std::time::{Duration, Instant}; -use valence_packet::packets::play::{KeepAliveC2s, KeepAliveS2c}; +use bevy_app::prelude::*; +use bevy_ecs::prelude::*; +use tracing::warn; +use valence_protocol::packets::play::{KeepAliveC2s, KeepAliveS2c}; +use valence_protocol::WritePacket; -use super::*; +use crate::client::{Client, UpdateClientsSet}; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.init_resource::() - .add_systems(PostUpdate, send_keepalive.in_set(UpdateClientsSet)) - .add_systems(EventLoopPreUpdate, handle_keepalive_response); +pub struct KeepalivePlugin; + +impl Plugin for KeepalivePlugin { + fn build(&self, app: &mut App) { + app.init_resource::() + .add_systems(PostUpdate, send_keepalive.in_set(UpdateClientsSet)) + .add_systems(EventLoopPreUpdate, handle_keepalive_response); + } } #[derive(Resource, Debug)] @@ -32,6 +40,16 @@ pub struct KeepaliveState { last_send: Instant, } +/// Delay measured in milliseconds. Negative values indicate absence. +#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct Ping(pub i32); + +impl Default for Ping { + fn default() -> Self { + Self(-1) + } +} + impl KeepaliveState { pub(super) fn new() -> Self { Self { diff --git a/crates/valence_layer/src/lib.rs b/crates/valence_server/src/layer.rs similarity index 77% rename from crates/valence_layer/src/lib.rs rename to crates/valence_server/src/layer.rs index 52fba6ff6..94621861e 100644 --- a/crates/valence_layer/src/lib.rs +++ b/crates/valence_server/src/layer.rs @@ -1,57 +1,25 @@ -#![doc = include_str!("../README.md")] -#![deny( - rustdoc::broken_intra_doc_links, - rustdoc::private_intra_doc_links, - rustdoc::missing_crate_level_docs, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_rust_codeblocks, - rustdoc::bare_urls, - rustdoc::invalid_html_tags -)] -#![warn( - trivial_casts, - trivial_numeric_casts, - unused_lifetimes, - unused_import_braces, - unreachable_pub, - clippy::dbg_macro -)] -#![allow(clippy::type_complexity)] +//! Defines chunk layers and entity layers. Chunk layers contain the chunks and +//! dimension data of a world, while entity layers contain all the Minecraft +//! entities. +//! +//! These two together are analogous to Minecraft "levels" or "worlds". pub mod bvh; pub mod chunk; pub mod entity; pub mod message; -use std::marker::PhantomData; - use bevy_app::prelude::*; use bevy_ecs::prelude::*; pub use chunk::ChunkLayer; pub use entity::EntityLayer; -use valence_biome::BiomeRegistry; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::ChunkPos; -use valence_core::ident::Ident; -use valence_core::Server; -use valence_dimension::DimensionTypeRegistry; use valence_entity::{InitEntitiesSet, UpdateTrackedDataSet}; -use valence_packet::protocol::encode::WritePacket; - -// Plugin is generic over the client type for hacky reasons. -pub struct LayerPlugin(PhantomData); +use valence_protocol::encode::WritePacket; +use valence_protocol::{BlockPos, ChunkPos, Ident}; +use valence_registry::{BiomeRegistry, DimensionTypeRegistry}; +use valence_server_core::Server; -impl LayerPlugin { - pub fn new() -> Self { - Self(PhantomData) - } -} - -impl Default for LayerPlugin { - fn default() -> Self { - Self::new() - } -} +pub struct LayerPlugin; /// When entity and chunk changes are written to layers. Systems that modify /// chunks and entities should run _before_ this. Systems that need to read @@ -64,7 +32,7 @@ pub struct UpdateLayersPreClientSet; #[derive(SystemSet, Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct UpdateLayersPostClientSet; -impl Plugin for LayerPlugin { +impl Plugin for LayerPlugin { fn build(&self, app: &mut App) { app.configure_sets( PostUpdate, @@ -77,7 +45,7 @@ impl Plugin for LayerPlugin { ); chunk::build(app); - entity::build::(app); + entity::build(app); } } diff --git a/crates/valence_layer/src/bvh.rs b/crates/valence_server/src/layer/bvh.rs similarity index 99% rename from crates/valence_layer/src/bvh.rs rename to crates/valence_server/src/layer/bvh.rs index f2c89c434..4f63cd01b 100644 --- a/crates/valence_layer/src/bvh.rs +++ b/crates/valence_server/src/layer/bvh.rs @@ -1,7 +1,9 @@ use std::mem; use std::ops::Range; -use valence_core::chunk_pos::{ChunkPos, ChunkView}; +use valence_protocol::ChunkPos; + +use crate::ChunkView; /// A bounding volume hierarchy for chunk positions. #[derive(Clone, Debug)] diff --git a/crates/valence_layer/src/chunk.rs b/crates/valence_server/src/layer/chunk.rs similarity index 89% rename from crates/valence_layer/src/chunk.rs rename to crates/valence_server/src/layer/chunk.rs index 8e5312e93..2f51effd0 100644 --- a/crates/valence_layer/src/chunk.rs +++ b/crates/valence_server/src/layer/chunk.rs @@ -10,31 +10,28 @@ use std::fmt; use bevy_app::prelude::*; use bevy_ecs::prelude::*; +pub use chunk::{MAX_HEIGHT, *}; +pub use loaded::LoadedChunk; use rustc_hash::FxHashMap; -use valence_biome::{BiomeId, BiomeRegistry}; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::ChunkPos; -use valence_core::ident::Ident; -use valence_core::protocol::Encode; -use valence_core::sound::{Sound, SoundCategory}; -use valence_core::Server; -use valence_dimension::DimensionTypeRegistry; +pub use unloaded::UnloadedChunk; use valence_math::{DVec3, Vec3}; use valence_nbt::Compound; -use valence_packet::packets::play::particle_s2c::Particle; -use valence_packet::packets::play::{ParticleS2c, PlaySoundS2c}; -use valence_packet::protocol::encode::{PacketWriter, WritePacket}; -use valence_packet::protocol::Packet; - -pub use self::chunk::{MAX_HEIGHT, *}; -pub use self::loaded::LoadedChunk; -pub use self::unloaded::UnloadedChunk; -use crate::bvh::GetChunkPos; -use crate::message::Messages; -use crate::{Layer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; +use valence_protocol::encode::{PacketWriter, WritePacket}; +use valence_protocol::packets::play::particle_s2c::Particle; +use valence_protocol::packets::play::{ParticleS2c, PlaySoundS2c}; +use valence_protocol::sound::{Sound, SoundCategory, SoundId}; +use valence_protocol::{BlockPos, ChunkPos, CompressionThreshold, Encode, Ident, Packet}; +use valence_registry::biome::{BiomeId, BiomeRegistry}; +use valence_registry::DimensionTypeRegistry; +use valence_server_core::Server; + +use super::bvh::GetChunkPos; +use super::message::Messages; +use super::{Layer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; /// A [`Component`] containing the [chunks](LoadedChunk) and [dimension -/// information](valence_dimension::DimensionTypeId) of a Minecraft world. +/// information](valence_registry::dimension_type::DimensionTypeId) of a +/// Minecraft world. #[derive(Component, Debug)] pub struct ChunkLayer { messages: ChunkLayerMessages, @@ -42,14 +39,13 @@ pub struct ChunkLayer { info: ChunkLayerInfo, } -/// Chunk layer information. Not public API. -#[doc(hidden)] -pub struct ChunkLayerInfo { +/// Chunk layer information. +pub(crate) struct ChunkLayerInfo { dimension_type_name: Ident, height: u32, min_y: i32, biome_registry_len: usize, - compression_threshold: Option, + threshold: CompressionThreshold, } impl fmt::Debug for ChunkLayerInfo { @@ -59,7 +55,7 @@ impl fmt::Debug for ChunkLayerInfo { .field("height", &self.height) .field("min_y", &self.min_y) .field("biome_registry_len", &self.biome_registry_len) - .field("compression_threshold", &self.compression_threshold) + .field("threshold", &self.threshold) // Ignore sky light mask and array. .finish() } @@ -67,9 +63,8 @@ impl fmt::Debug for ChunkLayerInfo { type ChunkLayerMessages = Messages; -#[doc(hidden)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub enum GlobalMsg { +pub(crate) enum GlobalMsg { /// Send packet data to all clients viewing the layer. Packet, /// Send packet data to all clients viewing the layer, except the client @@ -77,9 +72,8 @@ pub enum GlobalMsg { PacketExcept { except: Entity }, } -#[doc(hidden)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub enum LocalMsg { +pub(crate) enum LocalMsg { /// Send packet data to all clients viewing the layer in view of `pos`. PacketAt { pos: ChunkPos, @@ -126,12 +120,9 @@ impl GetChunkPos for LocalMsg { } impl ChunkLayer { - #[doc(hidden)] - pub const LOAD: u8 = 0; - #[doc(hidden)] - pub const UNLOAD: u8 = 1; - #[doc(hidden)] - pub const OVERWRITE: u8 = 2; + pub(crate) const LOAD: u8 = 0; + pub(crate) const UNLOAD: u8 = 1; + pub(crate) const OVERWRITE: u8 = 2; /// Creates a new chunk layer. #[track_caller] @@ -159,7 +150,7 @@ impl ChunkLayer { height: dim.height as u32, min_y: dim.min_y, biome_registry_len: biomes.iter().len(), - compression_threshold: server.compression_threshold(), + threshold: server.compression_threshold(), }, } } @@ -352,13 +343,11 @@ impl ChunkLayer { Some((chunk, x, y, z)) } - #[doc(hidden)] - pub fn info(&self) -> &ChunkLayerInfo { + pub(crate) fn info(&self) -> &ChunkLayerInfo { &self.info } - #[doc(hidden)] - pub fn messages(&self) -> &ChunkLayerMessages { + pub(crate) fn messages(&self) -> &ChunkLayerMessages { &self.messages } @@ -404,7 +393,10 @@ impl ChunkLayer { self.view_writer(ChunkPos::from_pos(position)) .write_packet(&PlaySoundS2c { - id: sound.to_id(), + id: SoundId::Direct { + id: sound.to_ident().into(), + range: None, + }, category, position: (position * 8.0).as_ivec3(), volume, @@ -484,7 +476,7 @@ impl WritePacket for ChunkLayer { P: Packet + Encode, { self.messages.send_global(GlobalMsg::Packet, |b| { - PacketWriter::new(b, self.info.compression_threshold).write_packet_fallible(packet) + PacketWriter::new(b, self.info.threshold).write_packet_fallible(packet) }) } @@ -508,10 +500,7 @@ impl WritePacket for ExceptWriter<'_> { GlobalMsg::PacketExcept { except: self.except, }, - |b| { - PacketWriter::new(b, self.layer.info.compression_threshold) - .write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet), ) } @@ -538,8 +527,7 @@ impl WritePacket for ViewWriter<'_> { self.layer .messages .send_local(LocalMsg::PacketAt { pos: self.pos }, |b| { - PacketWriter::new(b, self.layer.info.compression_threshold) - .write_packet_fallible(packet) + PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet) }) } @@ -568,10 +556,7 @@ impl WritePacket for ViewExceptWriter<'_> { pos: self.pos, except: self.except, }, - |b| { - PacketWriter::new(b, self.layer.info.compression_threshold) - .write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet), ) } @@ -602,10 +587,7 @@ impl WritePacket for RadiusWriter<'_> { center: self.center, radius_squared: self.radius, }, - |b| { - PacketWriter::new(b, self.layer.info.compression_threshold) - .write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet), ) } @@ -638,10 +620,7 @@ impl WritePacket for RadiusExceptWriter<'_> { radius_squared: self.radius, except: self.except, }, - |b| { - PacketWriter::new(b, self.layer.info.compression_threshold) - .write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet), ) } diff --git a/crates/valence_layer/src/chunk/chunk.rs b/crates/valence_server/src/layer/chunk/chunk.rs similarity index 98% rename from crates/valence_layer/src/chunk/chunk.rs rename to crates/valence_server/src/layer/chunk/chunk.rs index 3a7759f5d..e5b53eefc 100644 --- a/crates/valence_layer/src/chunk/chunk.rs +++ b/crates/valence_server/src/layer/chunk/chunk.rs @@ -1,6 +1,6 @@ -use valence_biome::BiomeId; -use valence_block::BlockState; use valence_nbt::Compound; +use valence_protocol::BlockState; +use valence_registry::biome::BiomeId; use super::paletted_container::PalettedContainer; @@ -316,8 +316,7 @@ pub(super) const fn bit_width(n: usize) -> usize { #[cfg(test)] mod tests { use super::*; - use crate::chunk::loaded::LoadedChunk; - use crate::chunk::unloaded::UnloadedChunk; + use crate::layer::chunk::{LoadedChunk, UnloadedChunk}; #[test] fn chunk_get_set() { diff --git a/crates/valence_layer/src/chunk/loaded.rs b/crates/valence_server/src/layer/chunk/loaded.rs similarity index 92% rename from crates/valence_layer/src/chunk/loaded.rs rename to crates/valence_server/src/layer/chunk/loaded.rs index 68e0cad3f..da1969c8a 100644 --- a/crates/valence_layer/src/chunk/loaded.rs +++ b/crates/valence_server/src/layer/chunk/loaded.rs @@ -4,19 +4,14 @@ use std::mem; use std::sync::atomic::{AtomicU32, Ordering}; use parking_lot::Mutex; // Using nonstandard mutex to avoid poisoning API. -use valence_biome::BiomeId; -use valence_block::BlockState; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::ChunkPos; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::var_long::VarLong; -use valence_core::protocol::Encode; use valence_nbt::{compound, Compound}; -use valence_packet::packets::play::chunk_data_s2c::ChunkDataBlockEntity; -use valence_packet::packets::play::{ +use valence_protocol::encode::{PacketWriter, WritePacket}; +use valence_protocol::packets::play::chunk_data_s2c::ChunkDataBlockEntity; +use valence_protocol::packets::play::{ BlockEntityUpdateS2c, BlockUpdateS2c, ChunkDataS2c, ChunkDeltaUpdateS2c, }; -use valence_packet::protocol::encode::{PacketWriter, WritePacket}; +use valence_protocol::{BlockPos, BlockState, ChunkPos, Encode, VarInt, VarLong}; +use valence_registry::biome::BiomeId; use valence_registry::RegistryIdx; use super::chunk::{ @@ -170,16 +165,14 @@ impl LoadedChunk { *self.viewer_count.get_mut() } - /// Increments the viewer count. For internal use only. - #[doc(hidden)] - pub fn inc_viewer_count(&self) { + /// Increments the viewer count. + pub(crate) fn inc_viewer_count(&self) { self.viewer_count.fetch_add(1, Ordering::Relaxed); } - /// Decrements the viewer count. For internal use only. - #[doc(hidden)] + /// Decrements the viewer count. #[track_caller] - pub fn dec_viewer_count(&self) { + pub(crate) fn dec_viewer_count(&self) { let old = self.viewer_count.fetch_sub(1, Ordering::Relaxed); debug_assert_ne!(old, 0, "viewer count underflow!"); } @@ -217,7 +210,7 @@ impl LoadedChunk { let global_z = pos.z * 16 + offset_z as i32; messages.send_local_infallible(LocalMsg::PacketAt { pos }, |buf| { - let mut writer = PacketWriter::new(buf, info.compression_threshold); + let mut writer = PacketWriter::new(buf, info.threshold); writer.write_packet(&BlockUpdateS2c { position: BlockPos::new(global_x, global_y, global_z), @@ -231,7 +224,7 @@ impl LoadedChunk { | (sect_y as i64 + info.min_y.div_euclid(16) as i64) & 0xfffff; messages.send_local_infallible(LocalMsg::PacketAt { pos }, |buf| { - let mut writer = PacketWriter::new(buf, info.compression_threshold); + let mut writer = PacketWriter::new(buf, info.threshold); writer.write_packet(&ChunkDeltaUpdateS2c { chunk_section_position, @@ -267,7 +260,7 @@ impl LoadedChunk { let global_z = pos.z * 16 + z as i32; messages.send_local_infallible(LocalMsg::PacketAt { pos }, |buf| { - let mut writer = PacketWriter::new(buf, info.compression_threshold); + let mut writer = PacketWriter::new(buf, info.threshold); writer.write_packet(&BlockEntityUpdateS2c { position: BlockPos::new(global_x, global_y, global_z), @@ -303,8 +296,7 @@ impl LoadedChunk { } /// Writes the packet data needed to initialize this chunk. - #[doc(hidden)] - pub fn write_init_packets( + pub(crate) fn write_init_packets( &self, mut writer: impl WritePacket, pos: ChunkPos, @@ -367,20 +359,18 @@ impl LoadedChunk { }) .collect(); - PacketWriter::new(&mut init_packets, info.compression_threshold).write_packet( - &ChunkDataS2c { - pos, - heightmaps: Cow::Owned(heightmaps), - blocks_and_biomes: &blocks_and_biomes, - block_entities: Cow::Owned(block_entities), - sky_light_mask: Cow::Borrowed(&[]), - block_light_mask: Cow::Borrowed(&[]), - empty_sky_light_mask: Cow::Borrowed(&[]), - empty_block_light_mask: Cow::Borrowed(&[]), - sky_light_arrays: Cow::Borrowed(&[]), - block_light_arrays: Cow::Borrowed(&[]), - }, - ) + PacketWriter::new(&mut init_packets, info.threshold).write_packet(&ChunkDataS2c { + pos, + heightmaps: Cow::Owned(heightmaps), + blocks_and_biomes: &blocks_and_biomes, + block_entities: Cow::Owned(block_entities), + sky_light_mask: Cow::Borrowed(&[]), + block_light_mask: Cow::Borrowed(&[]), + empty_sky_light_mask: Cow::Borrowed(&[]), + empty_block_light_mask: Cow::Borrowed(&[]), + sky_light_arrays: Cow::Borrowed(&[]), + block_light_arrays: Cow::Borrowed(&[]), + }) } writer.write_packet_bytes(&init_packets); @@ -609,7 +599,7 @@ impl Chunk for LoadedChunk { #[cfg(test)] mod tests { - use valence_core::ident; + use valence_protocol::ident; use super::*; @@ -639,7 +629,7 @@ mod tests { height: 512, min_y: -16, biome_registry_len: 200, - compression_threshold: None, + threshold: None, }; let mut buf = vec![]; diff --git a/crates/valence_layer/src/chunk/paletted_container.rs b/crates/valence_server/src/layer/chunk/paletted_container.rs similarity index 99% rename from crates/valence_layer/src/chunk/paletted_container.rs rename to crates/valence_server/src/layer/chunk/paletted_container.rs index ced9967c9..302151d83 100644 --- a/crates/valence_layer/src/chunk/paletted_container.rs +++ b/crates/valence_server/src/layer/chunk/paletted_container.rs @@ -3,8 +3,7 @@ use std::io::Write; use arrayvec::ArrayVec; use num_integer::div_ceil; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::Encode; +use valence_protocol::{Encode, VarInt}; use super::chunk::bit_width; diff --git a/crates/valence_layer/src/chunk/unloaded.rs b/crates/valence_server/src/layer/chunk/unloaded.rs similarity index 98% rename from crates/valence_layer/src/chunk/unloaded.rs rename to crates/valence_server/src/layer/chunk/unloaded.rs index 9bc2ab4bc..cd19114e1 100644 --- a/crates/valence_layer/src/chunk/unloaded.rs +++ b/crates/valence_server/src/layer/chunk/unloaded.rs @@ -1,9 +1,9 @@ use std::cmp::Ordering; use std::collections::BTreeMap; -use valence_biome::BiomeId; -use valence_block::BlockState; use valence_nbt::Compound; +use valence_protocol::BlockState; +use valence_registry::biome::BiomeId; use super::chunk::{ check_biome_oob, check_block_oob, check_section_oob, BiomeContainer, BlockStateContainer, diff --git a/crates/valence_layer/src/entity.rs b/crates/valence_server/src/layer/entity.rs similarity index 90% rename from crates/valence_layer/src/entity.rs rename to crates/valence_server/src/layer/entity.rs index 35b18f0be..142eb296f 100644 --- a/crates/valence_layer/src/entity.rs +++ b/crates/valence_server/src/layer/entity.rs @@ -5,33 +5,29 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use bevy_ecs::query::Has; use rustc_hash::FxHashMap; -use valence_core::block_pos::BlockPos; -use valence_core::chunk_pos::ChunkPos; -use valence_core::despawn::Despawned; -use valence_core::protocol::Encode; -use valence_core::Server; use valence_entity::query::UpdateEntityQuery; use valence_entity::{EntityId, EntityLayerId, OldEntityLayerId, OldPosition, Position}; -use valence_packet::protocol::encode::{PacketWriter, WritePacket}; -use valence_packet::protocol::Packet; +use valence_protocol::encode::{PacketWriter, WritePacket}; +use valence_protocol::{BlockPos, ChunkPos, CompressionThreshold, Encode, Packet}; +use valence_server_core::{Despawned, Server}; -use crate::bvh::GetChunkPos; -use crate::message::Messages; -use crate::{Layer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; +use super::bvh::GetChunkPos; +use super::message::Messages; +use super::{Layer, UpdateLayersPostClientSet, UpdateLayersPreClientSet}; +use crate::client::Client; /// A [`Component`] containing Minecraft entities. #[derive(Component, Debug)] pub struct EntityLayer { messages: EntityLayerMessages, entities: FxHashMap>, - compression_threshold: Option, + threshold: CompressionThreshold, } type EntityLayerMessages = Messages; -#[doc(hidden)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub enum GlobalMsg { +pub(crate) enum GlobalMsg { /// Send packet data to all clients viewing the layer. Message data is /// serialized packet data. Packet, @@ -43,10 +39,9 @@ pub enum GlobalMsg { DespawnLayer, } -#[doc(hidden)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] // NOTE: Variant order is significant. Despawns should be ordered before spawns. -pub enum LocalMsg { +pub(crate) enum LocalMsg { /// Despawn entities if the client is not already viewing `dest_layer`. /// Message data is the serialized form of `EntityId`. DespawnEntity { pos: ChunkPos, dest_layer: Entity }, @@ -100,7 +95,7 @@ impl EntityLayer { Self { messages: Messages::new(), entities: Default::default(), - compression_threshold: server.compression_threshold(), + threshold: server.compression_threshold(), } } @@ -116,8 +111,7 @@ impl EntityLayer { .flat_map(|entities| entities.iter().copied()) } - #[doc(hidden)] - pub fn messages(&self) -> &EntityLayerMessages { + pub(crate) fn messages(&self) -> &EntityLayerMessages { &self.messages } } @@ -192,7 +186,7 @@ impl WritePacket for EntityLayer { P: Packet + Encode, { self.messages.send_global(GlobalMsg::Packet, |b| { - PacketWriter::new(b, self.compression_threshold).write_packet_fallible(packet) + PacketWriter::new(b, self.threshold).write_packet_fallible(packet) }) } @@ -216,9 +210,7 @@ impl WritePacket for ExceptWriter<'_> { GlobalMsg::PacketExcept { except: self.except, }, - |b| { - PacketWriter::new(b, self.layer.compression_threshold).write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.threshold).write_packet_fallible(packet), ) } @@ -245,7 +237,7 @@ impl<'a> WritePacket for ViewWriter<'a> { self.layer .messages .send_local(LocalMsg::PacketAt { pos: self.pos }, |b| { - PacketWriter::new(b, self.layer.compression_threshold).write_packet_fallible(packet) + PacketWriter::new(b, self.layer.threshold).write_packet_fallible(packet) }) } @@ -274,9 +266,7 @@ impl WritePacket for ViewExceptWriter<'_> { pos: self.pos, except: self.except, }, - |b| { - PacketWriter::new(b, self.layer.compression_threshold).write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.threshold).write_packet_fallible(packet), ) } @@ -307,9 +297,7 @@ impl WritePacket for RadiusWriter<'_> { center: self.center, radius_squared: self.radius_squared, }, - |b| { - PacketWriter::new(b, self.layer.compression_threshold).write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.threshold).write_packet_fallible(packet), ) } @@ -342,9 +330,7 @@ impl WritePacket for RadiusExceptWriter<'_> { radius_squared: self.radius_squared, except: self.except, }, - |b| { - PacketWriter::new(b, self.layer.compression_threshold).write_packet_fallible(packet) - }, + |b| PacketWriter::new(b, self.layer.threshold).write_packet_fallible(packet), ) } @@ -360,13 +346,13 @@ impl WritePacket for RadiusExceptWriter<'_> { } } -pub(super) fn build(app: &mut App) { +pub(super) fn build(app: &mut App) { app.add_systems( PostUpdate, ( ( change_entity_positions, - send_entity_update_messages::, + send_entity_update_messages, send_layer_despawn_messages, ready_entity_layers, ) @@ -484,7 +470,7 @@ fn change_entity_positions( } } -fn send_entity_update_messages( +fn send_entity_update_messages( entities: Query<(Entity, UpdateEntityQuery, Has), Without>, mut layers: Query<&mut EntityLayer>, ) { @@ -509,8 +495,7 @@ fn send_entity_update_messages( }; layer.messages.send_local_infallible(msg, |b| { - update - .write_update_packets(PacketWriter::new(b, layer.compression_threshold)) + update.write_update_packets(PacketWriter::new(b, layer.threshold)) }); } else { panic!( diff --git a/crates/valence_layer/src/message.rs b/crates/valence_server/src/layer/message.rs similarity index 98% rename from crates/valence_layer/src/message.rs rename to crates/valence_server/src/layer/message.rs index a2e3ca18a..c52269d1d 100644 --- a/crates/valence_layer/src/message.rs +++ b/crates/valence_server/src/layer/message.rs @@ -2,9 +2,10 @@ use core::fmt; use std::convert::Infallible; use std::ops::Range; -use valence_core::chunk_pos::{ChunkPos, ChunkView}; +use valence_protocol::ChunkPos; -use crate::bvh::{ChunkBvh, GetChunkPos}; +use crate::layer::bvh::{ChunkBvh, GetChunkPos}; +use crate::ChunkView; /// A message buffer of global messages (`G`) and local messages (`L`) meant for /// consumption by clients. Local messages are those that have some spatial diff --git a/crates/valence_server/src/lib.rs b/crates/valence_server/src/lib.rs new file mode 100644 index 000000000..7d84bd67a --- /dev/null +++ b/crates/valence_server/src/lib.rs @@ -0,0 +1,55 @@ +// #![doc = include_str!("../README.md")] +#![deny( + rustdoc::broken_intra_doc_links, + rustdoc::private_intra_doc_links, + rustdoc::missing_crate_level_docs, + rustdoc::invalid_codeblock_attributes, + rustdoc::invalid_rust_codeblocks, + rustdoc::bare_urls, + rustdoc::invalid_html_tags +)] +#![warn( + trivial_casts, + trivial_numeric_casts, + unused_lifetimes, + unused_import_braces, + unreachable_pub, + clippy::dbg_macro +)] +#![allow(clippy::type_complexity)] + +pub mod action; +mod chunk_view; +pub mod client; +pub mod client_command; +pub mod client_settings; +pub mod custom_payload; +pub mod event_loop; +pub mod hand_swing; +pub mod interact_block; +pub mod interact_entity; +pub mod interact_item; +pub mod keepalive; +pub mod layer; +pub mod message; +pub mod movement; +pub mod op_level; +pub mod resource_pack; +pub mod spawn; +pub mod status; +pub mod teleport; +pub mod title; + +pub use chunk_view::ChunkView; +pub use event_loop::{EventLoopPostUpdate, EventLoopPreUpdate, EventLoopUpdate}; +pub use layer::{ChunkLayer, EntityLayer, Layer, LayerBundle}; +pub use valence_protocol::{ + block, ident, item, math, text, uuid, BlockPos, BlockState, ChunkPos, CompressionThreshold, + Direction, GameMode, Hand, Ident, ItemKind, ItemStack, PlayerTextures, Text, MINECRAFT_VERSION, + PROTOCOL_VERSION, +}; +pub use valence_server_core::*; +pub use { + bevy_app as app, bevy_ecs as ecs, rand, valence_entity as entity, valence_nbt as nbt, + valence_protocol as protocol, valence_registry as registry, +}; diff --git a/crates/valence_client/src/message.rs b/crates/valence_server/src/message.rs similarity index 80% rename from crates/valence_client/src/message.rs rename to crates/valence_server/src/message.rs index c0f6941ad..0a6b00791 100644 --- a/crates/valence_client/src/message.rs +++ b/crates/valence_server/src/message.rs @@ -2,15 +2,19 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::text::IntoText; -use valence_packet::packets::play::{ChatMessageC2s, GameMessageS2c}; -use valence_packet::protocol::encode::WritePacket; +use valence_protocol::encode::WritePacket; +use valence_protocol::packets::play::{ChatMessageC2s, GameMessageS2c}; +use valence_protocol::text::IntoText; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_chat_message); +pub struct MessagePlugin; + +impl Plugin for MessagePlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_chat_message); + } } pub trait SendMessage { diff --git a/crates/valence_client/src/movement.rs b/crates/valence_server/src/movement.rs similarity index 94% rename from crates/valence_client/src/movement.rs rename to crates/valence_server/src/movement.rs index 8f60155ad..5b5835799 100644 --- a/crates/valence_client/src/movement.rs +++ b/crates/valence_server/src/movement.rs @@ -2,17 +2,21 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use valence_entity::{HeadYaw, Look, OnGround, Position}; use valence_math::DVec3; -use valence_packet::packets::play::{ +use valence_protocol::packets::play::{ FullC2s, LookAndOnGroundC2s, OnGroundOnlyC2s, PositionAndOnGroundC2s, VehicleMoveC2s, }; -use super::teleport::TeleportState; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; +use crate::teleport::TeleportState; -pub(super) fn build(app: &mut App) { - app.init_resource::() - .add_event::() - .add_systems(EventLoopPreUpdate, handle_client_movement); +pub struct MovementPlugin; + +impl Plugin for MovementPlugin { + fn build(&self, app: &mut App) { + app.init_resource::() + .add_event::() + .add_systems(EventLoopPreUpdate, handle_client_movement); + } } /// Configuration resource for client movement checks. diff --git a/crates/valence_client/src/op_level.rs b/crates/valence_server/src/op_level.rs similarity index 60% rename from crates/valence_client/src/op_level.rs rename to crates/valence_server/src/op_level.rs index 5426961f1..55dd586f1 100644 --- a/crates/valence_client/src/op_level.rs +++ b/crates/valence_server/src/op_level.rs @@ -1,7 +1,16 @@ -use super::*; +use bevy_app::prelude::*; +use bevy_ecs::prelude::*; +use valence_protocol::packets::play::EntityStatusS2c; +use valence_protocol::WritePacket; -pub(super) fn build(app: &mut App) { - app.add_systems(PostUpdate, update_op_level.in_set(UpdateClientsSet)); +use crate::client::{Client, UpdateClientsSet}; + +pub struct OpLevelPlugin; + +impl Plugin for OpLevelPlugin { + fn build(&self, app: &mut App) { + app.add_systems(PostUpdate, update_op_level.in_set(UpdateClientsSet)); + } } #[derive(Component, Clone, PartialEq, Eq, Default, Debug)] diff --git a/crates/valence_client/src/resource_pack.rs b/crates/valence_server/src/resource_pack.rs similarity index 78% rename from crates/valence_client/src/resource_pack.rs rename to crates/valence_server/src/resource_pack.rs index 9d3edec94..f0a9cc5a9 100644 --- a/crates/valence_client/src/resource_pack.rs +++ b/crates/valence_server/src/resource_pack.rs @@ -1,14 +1,19 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::text::Text; -use valence_packet::packets::play::{ResourcePackSendS2c, ResourcePackStatusC2s}; +use valence_protocol::packets::play::{ResourcePackSendS2c, ResourcePackStatusC2s}; +use valence_protocol::text::Text; +use valence_protocol::WritePacket; -use super::*; +use crate::client::Client; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_systems(EventLoopPreUpdate, handle_resource_pack_status); +pub struct ResourcePackPlugin; + +impl Plugin for ResourcePackPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_systems(EventLoopPreUpdate, handle_resource_pack_status); + } } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] diff --git a/crates/valence_client/src/spawn.rs b/crates/valence_server/src/spawn.rs similarity index 85% rename from crates/valence_client/src/spawn.rs rename to crates/valence_server/src/spawn.rs index 97afcb2df..61c361a18 100644 --- a/crates/valence_client/src/spawn.rs +++ b/crates/valence_server/src/spawn.rs @@ -1,9 +1,17 @@ //! Handles spawning and respawning the client. -use valence_registry::codec::RegistryCodec; +use std::borrow::Cow; + +use bevy_ecs::prelude::*; +use bevy_ecs::query::WorldQuery; +use valence_entity::EntityLayerId; +use valence_protocol::packets::play::{GameJoinS2c, PlayerRespawnS2c, PlayerSpawnPositionS2c}; +use valence_protocol::{BlockPos, GameMode, GlobalPos, Ident, VarInt, WritePacket}; use valence_registry::tags::TagsRegistry; +use valence_registry::{BiomeRegistry, RegistryCodec}; -use super::*; +use crate::client::{Client, ViewDistance, VisibleChunkLayer}; +use crate::layer::ChunkLayer; // Components for the join game and respawn packet. @@ -44,6 +52,17 @@ impl Default for HasRespawnScreen { } } +/// The position and angle that clients will respawn with. Also +/// controls the position that compasses point towards. +#[derive(Component, Copy, Clone, PartialEq, Default, Debug)] +pub struct RespawnPosition { + /// The position that clients will respawn at. This can be changed at any + /// time to set the position that compasses point towards. + pub pos: BlockPos, + /// The yaw angle that clients will respawn with (in degrees). + pub yaw: f32, +} + /// A convenient [`WorldQuery`] for obtaining client spawn components. Also see /// [`ClientSpawnQueryReadOnly`]. #[derive(WorldQuery)] @@ -99,7 +118,7 @@ pub(super) fn initial_join( dimension_name, hashed_seed: spawn.hashed_seed.0 as i64, max_players: VarInt(0), // Ignored by clients. - view_distance: VarInt(spawn.view_distance.0 as i32), + view_distance: VarInt(spawn.view_distance.get() as i32), simulation_distance: VarInt(16), // TODO. reduced_debug_info: spawn.reduced_debug_info.0, enable_respawn_screen: spawn.has_respawn_screen.0, @@ -109,7 +128,7 @@ pub(super) fn initial_join( portal_cooldown: VarInt(spawn.portal_cooldown.0), }); - client.enc.append_bytes(tags.sync_tags_packet()); + client.write_packet_bytes(tags.sync_tags_packet()); /* // TODO: enable all the features? diff --git a/crates/valence_client/src/status.rs b/crates/valence_server/src/status.rs similarity index 76% rename from crates/valence_client/src/status.rs rename to crates/valence_server/src/status.rs index 74bf9218f..5571188ae 100644 --- a/crates/valence_client/src/status.rs +++ b/crates/valence_server/src/status.rs @@ -1,13 +1,17 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_packet::packets::play::ClientStatusC2s; +use valence_protocol::packets::play::ClientStatusC2s; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; -pub(super) fn build(app: &mut App) { - app.add_event::() - .add_event::() - .add_systems(EventLoopPreUpdate, handle_status); +pub struct StatusPlugin; + +impl Plugin for StatusPlugin { + fn build(&self, app: &mut App) { + app.add_event::() + .add_event::() + .add_systems(EventLoopPreUpdate, handle_status); + } } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] diff --git a/crates/valence_client/src/teleport.rs b/crates/valence_server/src/teleport.rs similarity index 83% rename from crates/valence_client/src/teleport.rs rename to crates/valence_server/src/teleport.rs index 86d83a05f..28b5d837b 100644 --- a/crates/valence_client/src/teleport.rs +++ b/crates/valence_server/src/teleport.rs @@ -1,20 +1,29 @@ +use bevy_app::prelude::*; +use bevy_ecs::prelude::*; +use tracing::warn; +use valence_entity::{Look, Position}; use valence_math::DVec3; -use valence_packet::packets::play::player_position_look_s2c::PlayerPositionLookFlags; -use valence_packet::packets::play::{PlayerPositionLookS2c, TeleportConfirmC2s}; +use valence_protocol::packets::play::player_position_look_s2c::PlayerPositionLookFlags; +use valence_protocol::packets::play::{PlayerPositionLookS2c, TeleportConfirmC2s}; +use valence_protocol::WritePacket; -use super::*; +use crate::client::{update_view_and_layers, Client, UpdateClientsSet}; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; use crate::spawn::update_respawn_position; -pub(super) fn build(app: &mut App) { - app.add_systems( - PostUpdate, - teleport - .after(update_view_and_layers) - .before(update_respawn_position) - .in_set(UpdateClientsSet), - ) - .add_systems(EventLoopPreUpdate, handle_teleport_confirmations); +pub struct TeleportPlugin; + +impl Plugin for TeleportPlugin { + fn build(&self, app: &mut App) { + app.add_systems( + PostUpdate, + teleport + .after(update_view_and_layers) + .before(update_respawn_position) + .in_set(UpdateClientsSet), + ) + .add_systems(EventLoopPreUpdate, handle_teleport_confirmations); + } } #[derive(Component, Debug)] diff --git a/crates/valence_client/src/title.rs b/crates/valence_server/src/title.rs similarity index 93% rename from crates/valence_client/src/title.rs rename to crates/valence_server/src/title.rs index f6b1fe2c8..6f0613f91 100644 --- a/crates/valence_client/src/title.rs +++ b/crates/valence_server/src/title.rs @@ -1,9 +1,8 @@ -use valence_core::text::IntoText; -use valence_packet::packets::play::{ +use valence_protocol::encode::WritePacket; +use valence_protocol::packets::play::{ ClearTitleS2c, OverlayMessageS2c, SubtitleS2c, TitleFadeS2c, TitleS2c, }; - -use super::*; +use valence_protocol::text::IntoText; pub trait SetTitle { /// Displays a title to a client. diff --git a/crates/valence_server_core/Cargo.toml b/crates/valence_server_core/Cargo.toml new file mode 100644 index 000000000..2cfd1a838 --- /dev/null +++ b/crates/valence_server_core/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "valence_server_core" +version.workspace = true +edition.workspace = true + +[dependencies] +bevy_ecs.workspace = true +bevy_app.workspace = true +uuid.workspace = true +rand.workspace = true +valence_protocol.workspace = true \ No newline at end of file diff --git a/crates/valence_core/README.md b/crates/valence_server_core/README.md similarity index 100% rename from crates/valence_core/README.md rename to crates/valence_server_core/README.md diff --git a/crates/valence_core/src/despawn.rs b/crates/valence_server_core/src/despawn.rs similarity index 100% rename from crates/valence_core/src/despawn.rs rename to crates/valence_server_core/src/despawn.rs index a3bb97cfb..17a9c22b4 100644 --- a/crates/valence_core/src/despawn.rs +++ b/crates/valence_server_core/src/despawn.rs @@ -17,8 +17,8 @@ use bevy_ecs::prelude::*; pub struct Despawned; pub(super) fn despawn_marked_entities( - mut commands: Commands, entities: Query>, + mut commands: Commands, ) { for entity in &entities { commands.entity(entity).despawn(); diff --git a/crates/valence_core/src/lib.rs b/crates/valence_server_core/src/lib.rs similarity index 73% rename from crates/valence_core/src/lib.rs rename to crates/valence_server_core/src/lib.rs index 4ff1faacd..ca47d39c4 100644 --- a/crates/valence_core/src/lib.rs +++ b/crates/valence_server_core/src/lib.rs @@ -18,8 +18,8 @@ )] #![allow(clippy::unusual_byte_groupings)] -pub mod despawn; -pub mod uuid; +mod despawn; +mod uuid; use std::num::NonZeroU32; use std::time::Duration; @@ -27,47 +27,20 @@ use std::time::Duration; use bevy_app::prelude::*; use bevy_app::ScheduleRunnerPlugin; use bevy_ecs::prelude::*; +pub use despawn::*; +pub use uuid::*; +use valence_protocol::CompressionThreshold; use crate::despawn::despawn_marked_entities; -// Needed to make proc macros work. -extern crate self as valence_core; - /// Minecraft's standard ticks per second (TPS). pub const DEFAULT_TPS: NonZeroU32 = match NonZeroU32::new(20) { Some(n) => n, None => unreachable!(), }; -pub struct CorePlugin; - -impl Plugin for CorePlugin { - fn build(&self, app: &mut App) { - let settings = app.world.get_resource_or_insert_with(CoreSettings::default); - - let compression_threshold = settings.compression_threshold; - let tick_rate = settings.tick_rate; - - app.insert_resource(Server { - current_tick: 0, - compression_threshold, - }); - - let tick_period = Duration::from_secs_f64((tick_rate.get() as f64).recip()); - - // Make the app loop forever at the configured TPS. - app.add_plugins(ScheduleRunnerPlugin::run_loop(tick_period)); - - fn increment_tick_counter(mut server: ResMut) { - server.current_tick += 1; - } - - app.add_systems(Last, (increment_tick_counter, despawn_marked_entities)); - } -} - -#[derive(Resource, Debug)] -pub struct CoreSettings { +#[derive(Clone, Resource)] +pub struct ServerSettings { /// The target ticks per second (TPS) of the server. This is the number of /// game updates that should occur in one second. /// @@ -94,10 +67,10 @@ pub struct CoreSettings { /// /// Compression is enabled with an unspecified value. This value may /// change in future versions. - pub compression_threshold: Option, + pub compression_threshold: CompressionThreshold, } -impl Default for CoreSettings { +impl Default for ServerSettings { fn default() -> Self { Self { tick_rate: DEFAULT_TPS, @@ -106,12 +79,41 @@ impl Default for CoreSettings { } } +pub struct ServerPlugin; + +impl Plugin for ServerPlugin { + fn build(&self, app: &mut App) { + let settings = app + .world + .get_resource_or_insert_with(ServerSettings::default) + .clone(); + + app.insert_resource(Server { + current_tick: 0, + threshold: settings.compression_threshold, + tick_rate: settings.tick_rate, + }); + + let tick_period = Duration::from_secs_f64((settings.tick_rate.get() as f64).recip()); + + // Make the app loop forever at the configured TPS. + app.add_plugins(ScheduleRunnerPlugin::run_loop(tick_period)); + + fn increment_tick_counter(mut server: ResMut) { + server.current_tick += 1; + } + + app.add_systems(Last, (increment_tick_counter, despawn_marked_entities)); + } +} + /// Contains global server state accessible as a [`Resource`]. -#[derive(Resource, Default)] +#[derive(Resource)] pub struct Server { /// Incremented on every tick. current_tick: i64, - compression_threshold: Option, + threshold: CompressionThreshold, + tick_rate: NonZeroU32, } impl Server { @@ -120,8 +122,14 @@ impl Server { self.current_tick } - /// Returns the server's compression threshold. - pub fn compression_threshold(&self) -> Option { - self.compression_threshold + /// Returns the server's [compression + /// threshold](ServerSettings::compression_threshold). + pub fn compression_threshold(&self) -> CompressionThreshold { + self.threshold + } + + // Returns the server's [tick rate](ServerPlugin::tick_rate). + pub fn tick_rate(&self) -> NonZeroU32 { + self.tick_rate } } diff --git a/crates/valence_core/src/uuid.rs b/crates/valence_server_core/src/uuid.rs similarity index 100% rename from crates/valence_core/src/uuid.rs rename to crates/valence_server_core/src/uuid.rs diff --git a/crates/valence_weather/Cargo.toml b/crates/valence_weather/Cargo.toml index 274b06cda..63a67dff3 100644 --- a/crates/valence_weather/Cargo.toml +++ b/crates/valence_weather/Cargo.toml @@ -7,8 +7,6 @@ documentation.workspace = true license.workspace = true [dependencies] -valence_client.workspace = true -valence_layer.workspace = true -valence_core.workspace = true +valence_server.workspace = true bevy_ecs.workspace = true bevy_app.workspace = true \ No newline at end of file diff --git a/crates/valence_weather/src/lib.rs b/crates/valence_weather/src/lib.rs index 73e898fc4..881e927a4 100644 --- a/crates/valence_weather/src/lib.rs +++ b/crates/valence_weather/src/lib.rs @@ -20,11 +20,11 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_client::{Client, FlushPacketsSet, UpdateClientsSet, VisibleChunkLayer}; -use valence_layer::ChunkLayer; -use valence_packet::packets::play::game_state_change_s2c::GameEventKind; -use valence_packet::packets::play::GameStateChangeS2c; -use valence_packet::protocol::encode::WritePacket; +use valence_server::client::{Client, FlushPacketsSet, UpdateClientsSet, VisibleChunkLayer}; +use valence_server::protocol::packets::play::game_state_change_s2c::GameEventKind; +use valence_server::protocol::packets::play::GameStateChangeS2c; +use valence_server::protocol::WritePacket; +use valence_server::ChunkLayer; pub struct WeatherPlugin; diff --git a/crates/valence_world_border/Cargo.toml b/crates/valence_world_border/Cargo.toml index c18d3a1c1..de46acd55 100644 --- a/crates/valence_world_border/Cargo.toml +++ b/crates/valence_world_border/Cargo.toml @@ -6,9 +6,4 @@ edition.workspace = true [dependencies] bevy_app.workspace = true bevy_ecs.workspace = true -valence_math.workspace = true -valence_client.workspace = true -valence_core.workspace = true -valence_entity.workspace = true -valence_layer.workspace = true -valence_registry.workspace = true +valence_server.workspace = true diff --git a/crates/valence_world_border/src/lib.rs b/crates/valence_world_border/src/lib.rs index 37facf585..fb313baba 100644 --- a/crates/valence_world_border/src/lib.rs +++ b/crates/valence_world_border/src/lib.rs @@ -19,16 +19,15 @@ )] use bevy_app::prelude::*; -use valence_client::{Client, UpdateClientsSet, VisibleChunkLayer}; -use valence_core::CoreSettings; -use valence_layer::ChunkLayer; -use valence_packet::packets::play::{ +use bevy_ecs::prelude::*; +use valence_server::client::{Client, UpdateClientsSet, VisibleChunkLayer}; +use valence_server::protocol::packets::play::{ WorldBorderCenterChangedS2c, WorldBorderInitializeS2c, WorldBorderInterpolateSizeS2c, WorldBorderSizeChangedS2c, WorldBorderWarningBlocksChangedS2c, WorldBorderWarningTimeChangedS2c, }; -use valence_packet::protocol::encode::WritePacket; -use valence_registry::*; +use valence_server::protocol::WritePacket; +use valence_server::{ChunkLayer, Server}; // https://minecraft.fandom.com/wiki/World_border pub const DEFAULT_PORTAL_LIMIT: i32 = 29999984; @@ -143,11 +142,11 @@ fn init_world_border_for_new_clients( &WorldBorderWarnTime, &WorldBorderWarnBlocks, )>, - settings: Res, + server: Res, ) { for (mut client, layer) in &mut clients { if let Ok((center, lerp, portal_tp_boundary, warn_time, warn_blocks)) = wbs.get(layer.0) { - let millis = lerp.remaining_ticks as i64 * 1000 / settings.tick_rate.get() as i64; + let millis = lerp.remaining_ticks as i64 * 1000 / server.tick_rate().get() as i64; client.write_packet(&WorldBorderInitializeS2c { x: center.x, @@ -165,7 +164,7 @@ fn init_world_border_for_new_clients( fn tick_world_border_lerp( mut wbs: Query<(&mut ChunkLayer, &mut WorldBorderLerp)>, - settings: Res, + server: Res, ) { for (mut layer, mut lerp) in &mut wbs { if lerp.is_changed() { @@ -176,7 +175,7 @@ fn tick_world_border_lerp( lerp.current_diameter = lerp.target_diameter; } else { - let millis = lerp.remaining_ticks as i64 * 1000 / settings.tick_rate.get() as i64; + let millis = lerp.remaining_ticks as i64 * 1000 / server.tick_rate().get() as i64; layer.write_packet(&WorldBorderInterpolateSizeS2c { old_diameter: lerp.current_diameter, @@ -238,10 +237,10 @@ fn change_world_border_portal_tp_boundary( ), Changed, >, - settings: Res, + server: Res, ) { for (mut layer, center, lerp, portal_tp_boundary, warn_time, warn_blocks) in &mut wbs { - let millis = lerp.remaining_ticks as i64 * 1000 / settings.tick_rate.get() as i64; + let millis = lerp.remaining_ticks as i64 * 1000 / server.tick_rate().get() as i64; layer.write_packet(&WorldBorderInitializeS2c { x: center.x, diff --git a/examples/anvil_loading.rs b/examples/anvil_loading.rs index 86f96c8b2..6cfa7cd4f 100644 --- a/examples/anvil_loading.rs +++ b/examples/anvil_loading.rs @@ -3,7 +3,6 @@ use std::path::PathBuf; use clap::Parser; use valence::prelude::*; use valence_anvil::{AnvilLevel, ChunkLoadEvent, ChunkLoadStatus}; -use valence_client::message::SendMessage; const SPAWN_POS: DVec3 = DVec3::new(0.0, 256.0, 0.0); diff --git a/examples/bench_players.rs b/examples/bench_players.rs index 4f147e702..670db45e0 100644 --- a/examples/bench_players.rs +++ b/examples/bench_players.rs @@ -2,8 +2,9 @@ use std::time::Instant; +use valence::client::{VisibleChunkLayer, VisibleEntityLayers}; use valence::prelude::*; -use valence_client::{VisibleChunkLayer, VisibleEntityLayers}; +use valence::ServerSettings; const SPAWN_Y: i32 = 64; @@ -12,7 +13,7 @@ struct TickStart(Instant); fn main() { App::new() - .insert_resource(CoreSettings { + .insert_resource(ServerSettings { compression_threshold: None, ..Default::default() }) @@ -34,14 +35,9 @@ fn record_tick_start_time(mut commands: Commands) { commands.insert_resource(TickStart(Instant::now())); } -fn print_tick_time( - server: Res, - settings: Res, - time: Res, - clients: Query<(), With>, -) { +fn print_tick_time(server: Res, time: Res, clients: Query<(), With>) { let tick = server.current_tick(); - if tick % (settings.tick_rate.get() as i64 / 2) == 0 { + if tick % (server.tick_rate().get() as i64 / 2) == 0 { let client_count = clients.iter().len(); let millis = time.0.elapsed().as_secs_f32() * 1000.0; diff --git a/examples/biomes.rs b/examples/biomes.rs index 2f2d8f159..51a427d49 100644 --- a/examples/biomes.rs +++ b/examples/biomes.rs @@ -3,7 +3,7 @@ use rand::seq::IteratorRandom; use rand::Rng; use valence::prelude::*; -use valence_biome::BiomeEffects; +use valence::registry::biome::BiomeEffects; const SPAWN_Y: i32 = 0; const SIZE: i32 = 5; diff --git a/examples/block_entities.rs b/examples/block_entities.rs index 9e4564c87..937db43ca 100644 --- a/examples/block_entities.rs +++ b/examples/block_entities.rs @@ -1,9 +1,9 @@ #![allow(clippy::type_complexity)] +use valence::interact_block::InteractBlockEvent; +use valence::message::ChatMessageEvent; use valence::nbt::{compound, List}; use valence::prelude::*; -use valence_client::interact_block::InteractBlockEvent; -use valence_client::message::ChatMessageEvent; const FLOOR_Y: i32 = 64; const SIGN_POS: [i32; 3] = [3, FLOOR_Y + 1, 2]; diff --git a/examples/boss_bar.rs b/examples/boss_bar.rs index f6858dfa1..47055ed22 100644 --- a/examples/boss_bar.rs +++ b/examples/boss_bar.rs @@ -1,12 +1,12 @@ #![allow(clippy::type_complexity)] use rand::seq::SliceRandom; -use valence::prelude::*; -use valence_boss_bar::{ +use valence::boss_bar::{ BossBarBundle, BossBarColor, BossBarDivision, BossBarFlags, BossBarHealth, BossBarStyle, BossBarTitle, BossBarViewers, }; -use valence_client::message::{ChatMessageEvent, SendMessage}; +use valence::message::{ChatMessageEvent, SendMessage}; +use valence::prelude::*; const SPAWN_Y: i32 = 64; diff --git a/examples/building.rs b/examples/building.rs index f57ef2522..7c00ef16f 100644 --- a/examples/building.rs +++ b/examples/building.rs @@ -1,9 +1,8 @@ #![allow(clippy::type_complexity)] +use valence::interact_block::InteractBlockEvent; use valence::inventory::HeldItem; use valence::prelude::*; -use valence_client::interact_block::InteractBlockEvent; -use valence_client::message::SendMessage; const SPAWN_Y: i32 = 64; diff --git a/examples/chest.rs b/examples/chest.rs index 2aaab908f..57add8e28 100644 --- a/examples/chest.rs +++ b/examples/chest.rs @@ -1,7 +1,7 @@ #![allow(clippy::type_complexity)] +use valence::interact_block::InteractBlockEvent; use valence::prelude::*; -use valence_client::interact_block::InteractBlockEvent; const SPAWN_Y: i32 = 64; const CHEST_POS: [i32; 3] = [0, SPAWN_Y + 1, 3]; diff --git a/examples/combat.rs b/examples/combat.rs index 4803fb892..6a79a267f 100644 --- a/examples/combat.rs +++ b/examples/combat.rs @@ -1,9 +1,9 @@ #![allow(clippy::type_complexity)] use bevy_ecs::query::WorldQuery; -use glam::Vec3Swizzles; use rand::Rng; use valence::entity::EntityStatuses; +use valence::math::Vec3Swizzles; use valence::prelude::*; const SPAWN_Y: i32 = 64; diff --git a/examples/cow_sphere.rs b/examples/cow_sphere.rs index 90e9e1707..402c558b4 100644 --- a/examples/cow_sphere.rs +++ b/examples/cow_sphere.rs @@ -2,7 +2,7 @@ use std::f64::consts::TAU; -use glam::{DQuat, EulerRot}; +use valence::math::{DQuat, EulerRot}; use valence::prelude::*; type SpherePartBundle = valence::entity::cow::CowEntityBundle; @@ -95,11 +95,10 @@ fn init_clients( } fn update_sphere( - settings: Res, server: Res, mut parts: Query<(&mut Position, &mut Look, &mut HeadYaw), With>, ) { - let time = server.current_tick() as f64 / settings.tick_rate.get() as f64; + let time = server.current_tick() as f64 / server.tick_rate().get() as f64; let rot_angles = DVec3::new(0.2, 0.4, 0.6) * SPHERE_FREQ * time * TAU % TAU; let rot = DQuat::from_euler(EulerRot::XYZ, rot_angles.x, rot_angles.y, rot_angles.z); diff --git a/examples/ctf.rs b/examples/ctf.rs index 2178eff0c..98bdc51e1 100644 --- a/examples/ctf.rs +++ b/examples/ctf.rs @@ -3,22 +3,20 @@ use std::collections::HashMap; use bevy_ecs::query::WorldQuery; -use glam::Vec3Swizzles; -use tracing::debug; -use valence::entity::EntityStatuses; +use valence::entity::cow::CowEntityBundle; +use valence::entity::entity::Flags; +use valence::entity::living::Health; +use valence::entity::pig::PigEntityBundle; +use valence::entity::player::PlayerEntityBundle; +use valence::entity::{EntityAnimations, EntityStatuses, OnGround, Velocity}; +use valence::interact_block::InteractBlockEvent; use valence::inventory::HeldItem; +use valence::log::debug; +use valence::math::Vec3Swizzles; use valence::nbt::{compound, List}; use valence::prelude::*; -use valence_client::interact_block::InteractBlockEvent; -use valence_client::message::SendMessage; -use valence_client::status::RequestRespawnEvent; -use valence_entity::cow::CowEntityBundle; -use valence_entity::entity::Flags; -use valence_entity::living::Health; -use valence_entity::pig::PigEntityBundle; -use valence_entity::player::PlayerEntityBundle; -use valence_entity::{EntityAnimations, OnGround, Velocity}; -use valence_scoreboard::*; +use valence::scoreboard::*; +use valence::status::RequestRespawnEvent; const ARENA_Y: i32 = 64; const ARENA_MID_WIDTH: i32 = 2; diff --git a/examples/death.rs b/examples/death.rs index dbe7a3c5d..645d76d45 100644 --- a/examples/death.rs +++ b/examples/death.rs @@ -1,8 +1,7 @@ #![allow(clippy::type_complexity)] use valence::prelude::*; -use valence_client::message::SendMessage; -use valence_client::status::RequestRespawnEvent; +use valence::status::RequestRespawnEvent; const SPAWN_Y: i32 = 64; diff --git a/examples/entity_hitbox.rs b/examples/entity_hitbox.rs index bff7e4b4d..59eff1a31 100644 --- a/examples/entity_hitbox.rs +++ b/examples/entity_hitbox.rs @@ -2,19 +2,18 @@ use std::collections::HashMap; -use bevy_app::App; -use bevy_ecs::prelude::Entity; -use rand::Rng; +use bevy_app::prelude::*; +use bevy_ecs::prelude::*; +use entity::NameVisible; +use valence::entity::hoglin::HoglinEntityBundle; +use valence::entity::pig::PigEntityBundle; +use valence::entity::sheep::SheepEntityBundle; +use valence::entity::warden::WardenEntityBundle; +use valence::entity::zombie::ZombieEntityBundle; +use valence::entity::zombie_horse::ZombieHorseEntityBundle; +use valence::entity::{entity, Pose}; use valence::prelude::*; -use valence_client::message::SendMessage; -use valence_entity::entity::NameVisible; -use valence_entity::hoglin::HoglinEntityBundle; -use valence_entity::pig::PigEntityBundle; -use valence_entity::sheep::SheepEntityBundle; -use valence_entity::warden::WardenEntityBundle; -use valence_entity::zombie::ZombieEntityBundle; -use valence_entity::zombie_horse::ZombieHorseEntityBundle; -use valence_entity::{entity, Pose}; +use valence::rand::Rng; pub fn main() { App::new() diff --git a/examples/game_of_life.rs b/examples/game_of_life.rs index ab8b426b2..aa1ca830e 100644 --- a/examples/game_of_life.rs +++ b/examples/game_of_life.rs @@ -3,7 +3,6 @@ use std::mem; use valence::prelude::*; -use valence_client::message::SendMessage; const BOARD_MIN_X: i32 = -30; const BOARD_MAX_X: i32 = 30; diff --git a/examples/parkour.rs b/examples/parkour.rs index 2878620ba..66fda594a 100644 --- a/examples/parkour.rs +++ b/examples/parkour.rs @@ -6,9 +6,8 @@ use std::time::{SystemTime, UNIX_EPOCH}; use rand::seq::SliceRandom; use rand::Rng; use valence::prelude::*; -use valence::sound::{Sound, SoundCategory}; -use valence_client::message::SendMessage; -use valence_client::spawn::IsFlat; +use valence::protocol::sound::{Sound, SoundCategory}; +use valence::spawn::IsFlat; const START_POS: BlockPos = BlockPos::new(0, 100, 0); const VIEW_DIST: u8 = 10; diff --git a/examples/particles.rs b/examples/particles.rs index f67488c06..89925a3a3 100644 --- a/examples/particles.rs +++ b/examples/particles.rs @@ -110,8 +110,8 @@ fn create_particle_vec() -> Vec { vec![ Particle::AmbientEntityEffect, Particle::AngryVillager, - Particle::Block(BlockState::OAK_PLANKS.to_raw() as _), - Particle::BlockMarker(BlockState::GOLD_BLOCK.to_raw() as _), + Particle::Block(BlockState::OAK_PLANKS), + Particle::BlockMarker(BlockState::GOLD_BLOCK), Particle::Bubble, Particle::Cloud, Particle::Crit, @@ -140,7 +140,7 @@ fn create_particle_vec() -> Vec { Particle::ExplosionEmitter, Particle::Explosion, Particle::SonicBoom, - Particle::FallingDust(BlockState::RED_SAND.to_raw() as _), + Particle::FallingDust(BlockState::RED_SAND), Particle::Firework, Particle::Fishing, Particle::Flame, diff --git a/examples/player_list.rs b/examples/player_list.rs index 6249fe450..8b3635286 100644 --- a/examples/player_list.rs +++ b/examples/player_list.rs @@ -1,10 +1,9 @@ #![allow(clippy::type_complexity)] use rand::Rng; +use valence::keepalive::Ping; use valence::player_list::{DisplayName, PlayerListEntryBundle}; use valence::prelude::*; -use valence_client::message::SendMessage; -use valence_client::Ping; const SPAWN_Y: i32 = 64; const PLAYER_UUID_1: Uuid = Uuid::from_u128(1); diff --git a/examples/resource_pack.rs b/examples/resource_pack.rs index aa841d845..b337aadad 100644 --- a/examples/resource_pack.rs +++ b/examples/resource_pack.rs @@ -1,10 +1,10 @@ #![allow(clippy::type_complexity)] use valence::entity::sheep::SheepEntityBundle; +use valence::message::SendMessage; use valence::prelude::*; -use valence_client::message::SendMessage; -use valence_client::resource_pack::ResourcePackStatusEvent; -use valence_packet::packets::play::ResourcePackStatusC2s; +use valence::protocol::packets::play::ResourcePackStatusC2s; +use valence::resource_pack::ResourcePackStatusEvent; const SPAWN_Y: i32 = 64; diff --git a/examples/server_list_ping.rs b/examples/server_list_ping.rs index eca06a8a5..f0d39c59d 100644 --- a/examples/server_list_ping.rs +++ b/examples/server_list_ping.rs @@ -4,11 +4,11 @@ use std::net::SocketAddr; use rand::Rng; use valence::network::{ - async_trait, BroadcastToLan, CleanupFn, ConnectionMode, PlayerSampleEntry, ServerListPing, + async_trait, BroadcastToLan, CleanupFn, ConnectionMode, HandshakeData, PlayerSampleEntry, + ServerListPing, }; use valence::prelude::*; -use valence_core::MINECRAFT_VERSION; -use valence_network::HandshakeData; +use valence::MINECRAFT_VERSION; pub fn main() { App::new() diff --git a/examples/terrain.rs b/examples/terrain.rs index eca5448c5..bc3fe2ee6 100644 --- a/examples/terrain.rs +++ b/examples/terrain.rs @@ -10,7 +10,7 @@ use flume::{Receiver, Sender}; use noise::{NoiseFn, SuperSimplex}; use tracing::info; use valence::prelude::*; -use valence_client::spawn::IsFlat; +use valence::spawn::IsFlat; const SPAWN_POS: DVec3 = DVec3::new(0.0, 200.0, 0.0); const HEIGHT: u32 = 384; diff --git a/examples/text.rs b/examples/text.rs index 6839d5240..8a7ed9eb7 100644 --- a/examples/text.rs +++ b/examples/text.rs @@ -1,7 +1,7 @@ #![allow(clippy::type_complexity)] +use valence::lang::keys; use valence::prelude::*; -use valence_client::message::SendMessage; const SPAWN_Y: i32 = 64; @@ -91,12 +91,12 @@ fn init_clients( client.send_chat_message("\nTranslated Text"); client.send_chat_message( " - 'chat.type.advancement.task': ".into_text() - + Text::translate(translation_key::CHAT_TYPE_ADVANCEMENT_TASK, []), + + Text::translate(keys::CHAT_TYPE_ADVANCEMENT_TASK, []), ); client.send_chat_message( " - 'chat.type.advancement.task' with slots: ".into_text() + Text::translate( - translation_key::CHAT_TYPE_ADVANCEMENT_TASK, + keys::CHAT_TYPE_ADVANCEMENT_TASK, ["arg1".into(), "arg2".into()], ), ); diff --git a/examples/weather.rs b/examples/weather.rs index 84ce9a652..e0c227668 100644 --- a/examples/weather.rs +++ b/examples/weather.rs @@ -1,8 +1,7 @@ use std::f64::consts::TAU; use valence::prelude::*; -use valence::weather::Rain; -use valence_weather::{Thunder, WeatherBundle}; +use valence::weather::{Rain, Thunder, WeatherBundle}; pub fn main() { App::new() diff --git a/examples/world_border.rs b/examples/world_border.rs index 3264ee396..1a7337377 100644 --- a/examples/world_border.rs +++ b/examples/world_border.rs @@ -2,11 +2,10 @@ use bevy_app::App; use valence::client::despawn_disconnected_clients; -use valence::client::message::ChatMessageEvent; use valence::inventory::HeldItem; +use valence::message::{ChatMessageEvent, SendMessage}; use valence::prelude::*; use valence::world_border::*; -use valence_client::message::SendMessage; const SPAWN_Y: i32 = 64; diff --git a/src/lib.rs b/src/lib.rs index 7f92cbc38..fc7b660f5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,37 +23,57 @@ use bevy_app::{PluginGroup, PluginGroupBuilder}; +#[cfg(feature = "testing")] pub mod testing; + #[cfg(test)] mod tests; #[cfg(feature = "log")] pub use bevy_log as log; +use registry::biome::BiomePlugin; +use registry::dimension_type::DimensionTypePlugin; #[cfg(feature = "advancement")] pub use valence_advancement as advancement; #[cfg(feature = "anvil")] pub use valence_anvil as anvil; #[cfg(feature = "boss_bar")] pub use valence_boss_bar as boss_bar; -pub use valence_core::*; #[cfg(feature = "inventory")] pub use valence_inventory as inventory; +pub use valence_lang as lang; #[cfg(feature = "network")] pub use valence_network as network; #[cfg(feature = "player_list")] pub use valence_player_list as player_list; +use valence_registry::RegistryPlugin; #[cfg(feature = "scoreboard")] pub use valence_scoreboard as scoreboard; +use valence_server::action::ActionPlugin; +use valence_server::client::ClientPlugin; +use valence_server::client_command::ClientCommandPlugin; +use valence_server::client_settings::ClientSettingsPlugin; +use valence_server::custom_payload::CustomPayloadPlugin; +use valence_server::entity::hitbox::HitboxPlugin; +use valence_server::entity::EntityPlugin; +use valence_server::event_loop::EventLoopPlugin; +use valence_server::hand_swing::HandSwingPlugin; +use valence_server::interact_block::InteractBlockPlugin; +use valence_server::interact_entity::InteractEntityPlugin; +use valence_server::interact_item::InteractItemPlugin; +use valence_server::keepalive::KeepalivePlugin; +use valence_server::layer::LayerPlugin; +use valence_server::message::MessagePlugin; +use valence_server::movement::MovementPlugin; +use valence_server::op_level::OpLevelPlugin; +use valence_server::resource_pack::ResourcePackPlugin; +use valence_server::status::StatusPlugin; +use valence_server::teleport::TeleportPlugin; +pub use valence_server::*; #[cfg(feature = "weather")] pub use valence_weather as weather; #[cfg(feature = "world_border")] pub use valence_world_border as world_border; -pub use { - bevy_app as app, bevy_ecs as ecs, valence_biome as biome, valence_block as block, - valence_client as client, valence_dimension as dimension, valence_entity as entity, - valence_layer as layer, valence_math as math, valence_nbt as nbt, valence_packet as packet, - valence_registry as registry, -}; /// Contains the most frequently used items in Valence projects. /// @@ -70,65 +90,60 @@ pub mod prelude { pub use bevy_app::prelude::*; pub use bevy_ecs; // Needed for bevy_ecs macros to function correctly. pub use bevy_ecs::prelude::*; - pub use glam::{DVec2, DVec3, Vec2, Vec3}; - pub use ident::Ident; pub use uuid::Uuid; #[cfg(feature = "advancement")] pub use valence_advancement::{ event::AdvancementTabChangeEvent, Advancement, AdvancementBundle, AdvancementClientUpdate, AdvancementCriteria, AdvancementDisplay, AdvancementFrameType, AdvancementRequirements, }; - pub use valence_biome::{Biome, BiomeId, BiomeRegistry}; - pub use valence_block::{BlockKind, BlockState, PropName, PropValue}; - pub use valence_client::action::{DiggingEvent, DiggingState}; - pub use valence_client::command::{ - ClientCommand, JumpWithHorseEvent, JumpWithHorseState, LeaveBedEvent, SneakEvent, - SneakState, SprintEvent, SprintState, - }; - pub use valence_client::event_loop::{ - EventLoopPostUpdate, EventLoopPreUpdate, EventLoopUpdate, - }; - pub use valence_client::interact_entity::{EntityInteraction, InteractEntityEvent}; - pub use valence_client::spawn::{ClientSpawnQuery, ClientSpawnQueryReadOnly}; - pub use valence_client::title::SetTitle as _; - pub use valence_client::{ - despawn_disconnected_clients, Client, Ip, OldView, OldViewDistance, Properties, - RespawnPosition, Username, View, ViewDistance, VisibleChunkLayer, VisibleEntityLayers, - }; - pub use valence_core::block_pos::BlockPos; - pub use valence_core::chunk_pos::{ChunkPos, ChunkView}; - pub use valence_core::despawn::Despawned; - pub use valence_core::direction::Direction; - pub use valence_core::game_mode::GameMode; - pub use valence_core::hand::Hand; - pub use valence_core::ident; // Export the `ident!` macro. - pub use valence_core::item::{ItemKind, ItemStack}; - pub use valence_core::text::{Color, IntoText, Text}; - pub use valence_core::uuid::UniqueId; - pub use valence_core::{translation_key, CoreSettings, Server}; - pub use valence_dimension::{DimensionType, DimensionTypeRegistry}; - pub use valence_entity::hitbox::{Hitbox, HitboxShape}; - pub use valence_entity::{ - EntityAnimation, EntityKind, EntityLayerId, EntityManager, EntityStatus, HeadYaw, Look, - OldEntityLayerId, OldPosition, Position, - }; #[cfg(feature = "inventory")] pub use valence_inventory::{ CursorItem, Inventory, InventoryKind, InventoryWindow, InventoryWindowMut, OpenInventory, }; - pub use valence_layer::chunk::{ - Block, BlockRef, Chunk, ChunkLayer, LoadedChunk, UnloadedChunk, - }; - pub use valence_layer::{EntityLayer, LayerBundle}; - pub use valence_nbt::Compound; #[cfg(feature = "network")] pub use valence_network::{ ConnectionMode, ErasedNetworkCallbacks, NetworkCallbacks, NetworkSettings, NewClientInfo, SharedNetworkState, }; - pub use valence_packet::packets::play::particle_s2c::Particle; #[cfg(feature = "player_list")] pub use valence_player_list::{PlayerList, PlayerListEntry}; + pub use valence_registry::biome::{Biome, BiomeId, BiomeRegistry}; + pub use valence_registry::dimension_type::{DimensionType, DimensionTypeRegistry}; + pub use valence_server::action::{DiggingEvent, DiggingState}; + pub use valence_server::block::{BlockKind, BlockState, PropName, PropValue}; + pub use valence_server::client::{ + despawn_disconnected_clients, Client, Ip, OldView, OldViewDistance, Properties, Username, + View, ViewDistance, VisibleChunkLayer, VisibleEntityLayers, + }; + pub use valence_server::client_command::{ + ClientCommand, JumpWithHorseEvent, JumpWithHorseState, LeaveBedEvent, SneakEvent, + SneakState, SprintEvent, SprintState, + }; + pub use valence_server::entity::hitbox::{Hitbox, HitboxShape}; + pub use valence_server::entity::{ + EntityAnimation, EntityKind, EntityLayerId, EntityManager, EntityStatus, HeadYaw, Look, + OldEntityLayerId, OldPosition, Position, + }; + pub use valence_server::event_loop::{ + EventLoopPostUpdate, EventLoopPreUpdate, EventLoopUpdate, + }; + pub use valence_server::ident::Ident; + pub use valence_server::interact_entity::{EntityInteraction, InteractEntityEvent}; + pub use valence_server::layer::chunk::{ + Block, BlockRef, Chunk, ChunkLayer, LoadedChunk, UnloadedChunk, + }; + pub use valence_server::layer::{EntityLayer, LayerBundle}; + pub use valence_server::math::{DVec2, DVec3, Vec2, Vec3}; + pub use valence_server::message::SendMessage as _; + pub use valence_server::nbt::Compound; + pub use valence_server::protocol::packets::play::particle_s2c::Particle; + pub use valence_server::protocol::text::{Color, IntoText, Text}; + pub use valence_server::spawn::{ClientSpawnQuery, ClientSpawnQueryReadOnly, RespawnPosition}; + pub use valence_server::title::SetTitle as _; + pub use valence_server::{ + ident, BlockPos, ChunkPos, ChunkView, Despawned, Direction, GameMode, Hand, ItemKind, + ItemStack, Server, UniqueId, + }; pub use super::DefaultPlugins; } @@ -145,14 +160,30 @@ impl PluginGroup for DefaultPlugins { fn build(self) -> PluginGroupBuilder { #[allow(unused_mut)] let mut group = PluginGroupBuilder::start::() - .add(valence_core::CorePlugin) - .add(valence_registry::RegistryPlugin) - .add(valence_biome::BiomePlugin) - .add(valence_dimension::DimensionPlugin) - .add(valence_entity::EntityPlugin) - .add(valence_entity::hitbox::HitboxPlugin) - .add(valence_layer::LayerPlugin::::new()) - .add(valence_client::ClientPlugin); + .add(ServerPlugin) + .add(RegistryPlugin) + .add(BiomePlugin) + .add(DimensionTypePlugin) + .add(EntityPlugin) + .add(HitboxPlugin) + .add(LayerPlugin) + .add(ClientPlugin) + .add(EventLoopPlugin) + .add(MovementPlugin) + .add(ClientCommandPlugin) + .add(KeepalivePlugin) + .add(InteractEntityPlugin) + .add(ClientSettingsPlugin) + .add(ActionPlugin) + .add(TeleportPlugin) + .add(MessagePlugin) + .add(CustomPayloadPlugin) + .add(HandSwingPlugin) + .add(InteractBlockPlugin) + .add(InteractItemPlugin) + .add(OpLevelPlugin) + .add(ResourcePackPlugin) + .add(StatusPlugin); #[cfg(feature = "log")] { diff --git a/src/testing.rs b/src/testing.rs index 0beb401cb..23ce0924d 100644 --- a/src/testing.rs +++ b/src/testing.rs @@ -7,19 +7,15 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use bytes::{Buf, BufMut, BytesMut}; use uuid::Uuid; -use valence_biome::BiomeRegistry; -use valence_client::keepalive::KeepaliveSettings; -use valence_client::ClientBundleArgs; -use valence_core::protocol::var_int::VarInt; -use valence_core::protocol::{Decode, Encode}; -use valence_core::{ident, CoreSettings, Server}; -use valence_dimension::DimensionTypeRegistry; -use valence_layer::{ChunkLayer, EntityLayer}; +use valence_ident::ident; use valence_network::NetworkPlugin; -use valence_packet::packets::play::{PlayerPositionLookS2c, TeleportConfirmC2s}; -use valence_packet::protocol::decode::{PacketDecoder, PacketFrame}; -use valence_packet::protocol::encode::PacketEncoder; -use valence_packet::protocol::Packet; +use valence_registry::{BiomeRegistry, DimensionTypeRegistry}; +use valence_server::client::ClientBundleArgs; +use valence_server::keepalive::KeepaliveSettings; +use valence_server::protocol::decode::PacketFrame; +use valence_server::protocol::packets::play::{PlayerPositionLookS2c, TeleportConfirmC2s}; +use valence_server::protocol::{Decode, Encode, Packet, PacketDecoder, PacketEncoder, VarInt}; +use valence_server::{ChunkLayer, EntityLayer, Server, ServerSettings}; use crate::client::{ClientBundle, ClientConnection, ReceivedPacket}; use crate::DefaultPlugins; @@ -42,16 +38,14 @@ impl ScenarioSingleClient { pub fn new() -> Self { let mut app = App::new(); - app.insert_resource(CoreSettings { - compression_threshold: None, - ..Default::default() - }); - app.insert_resource(KeepaliveSettings { period: Duration::MAX, - }); - - app.add_plugins(DefaultPlugins.build().disable::()); + }) + .insert_resource(ServerSettings { + compression_threshold: None, + ..Default::default() + }) + .add_plugins(DefaultPlugins.build().disable::()); app.update(); // Initialize plugins. diff --git a/src/tests/boss_bar.rs b/src/tests/boss_bar.rs index 244ca6e2e..caeaa0bfe 100644 --- a/src/tests/boss_bar.rs +++ b/src/tests/boss_bar.rs @@ -2,11 +2,11 @@ use valence_boss_bar::{ BossBarBundle, BossBarColor, BossBarDivision, BossBarFlags, BossBarHealth, BossBarStyle, BossBarTitle, BossBarViewers, }; -use valence_core::despawn::Despawned; -use valence_core::text::Text; -use valence_packet::packets::play::BossBarS2c; +use valence_server::protocol::packets::play::BossBarS2c; +use valence_server::Despawned; use crate::testing::ScenarioSingleClient; +use crate::Text; #[test] fn test_intialize_on_join() { diff --git a/src/tests/client.rs b/src/tests/client.rs index 1690c7b5d..b3ddbd739 100644 --- a/src/tests/client.rs +++ b/src/tests/client.rs @@ -1,12 +1,12 @@ use glam::DVec3; -use valence_core::chunk_pos::ChunkPos; -use valence_layer::chunk::UnloadedChunk; -use valence_layer::ChunkLayer; -use valence_packet::packets::play::{ + +use crate::layer::chunk::UnloadedChunk; +use crate::layer::ChunkLayer; +use crate::protocol::packets::play::{ FullC2s, MoveRelativeS2c, PlayerPositionLookS2c, TeleportConfirmC2s, }; - use crate::testing::{create_mock_client, ScenarioSingleClient}; +use crate::ChunkPos; #[test] fn client_teleport_and_move() { diff --git a/src/tests/example.rs b/src/tests/example.rs index ac6b33c29..fe3a8d9dd 100644 --- a/src/tests/example.rs +++ b/src/tests/example.rs @@ -6,15 +6,14 @@ //! Some of the tests in this file may be inferior duplicates of real tests. use bevy_app::App; -use glam::DVec3; -use valence_client::Client; -use valence_core::Server; -use valence_entity::Position; -use valence_inventory::{Inventory, InventoryKind, OpenInventory}; -use valence_packet::packets::play::{InventoryS2c, OpenScreenS2c, PositionAndOnGroundC2s}; +use crate::client::Client; +use crate::entity::Position; +use crate::inventory::{Inventory, InventoryKind, OpenInventory}; +use crate::math::DVec3; +use crate::protocol::packets::play::{InventoryS2c, OpenScreenS2c, PositionAndOnGroundC2s}; use crate::testing::ScenarioSingleClient; -use crate::DefaultPlugins; +use crate::{DefaultPlugins, Server}; /// The server's tick should increment every update. #[test] diff --git a/src/tests/inventory.rs b/src/tests/inventory.rs index 4b5d91021..2c3269f57 100644 --- a/src/tests/inventory.rs +++ b/src/tests/inventory.rs @@ -1,18 +1,17 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use valence_core::game_mode::GameMode; -use valence_core::item::{ItemKind, ItemStack}; -use valence_core::protocol::var_int::VarInt; -use valence_inventory::{ + +use crate::inventory::{ convert_to_player_slot_id, ClickMode, ClientInventoryState, CursorItem, DropItemStackEvent, HeldItem, Inventory, InventoryKind, OpenInventory, SlotChange, }; -use valence_packet::packets::play::{ +use crate::protocol::packets::play::{ ClickSlotC2s, CloseScreenS2c, CreativeInventoryActionC2s, InventoryS2c, OpenScreenS2c, ScreenHandlerSlotUpdateS2c, UpdateSelectedSlotC2s, }; - +use crate::protocol::VarInt; use crate::testing::ScenarioSingleClient; +use crate::{GameMode, ItemKind, ItemStack}; #[test] fn test_should_open_inventory() { @@ -581,12 +580,10 @@ fn should_not_increment_state_id_on_cursor_item_change() { } mod dropping_items { - use valence_core::block_pos::BlockPos; - use valence_core::direction::Direction; - use valence_inventory::{convert_to_player_slot_id, PlayerAction}; - use valence_packet::packets::play::PlayerActionC2s; - use super::*; + use crate::inventory::{convert_to_player_slot_id, PlayerAction}; + use crate::protocol::packets::play::PlayerActionC2s; + use crate::{BlockPos, Direction}; #[test] fn should_drop_item_player_action() { diff --git a/src/tests/layer.rs b/src/tests/layer.rs index 11ac37dba..dcb542b23 100644 --- a/src/tests/layer.rs +++ b/src/tests/layer.rs @@ -1,22 +1,19 @@ use std::collections::BTreeSet; use bevy_ecs::world::EntityMut; -use valence_block::BlockState; -use valence_client::{ViewDistance, VisibleEntityLayers}; -use valence_core::chunk_pos::ChunkView; -use valence_core::despawn::Despawned; -use valence_core::Server; -use valence_entity::cow::CowEntityBundle; -use valence_entity::{EntityLayerId, Position}; -use valence_layer::chunk::UnloadedChunk; -use valence_layer::{ChunkLayer, EntityLayer}; -use valence_packet::packets::play::{ + +use crate::client::{ViewDistance, VisibleEntityLayers}; +use crate::entity::cow::CowEntityBundle; +use crate::entity::{EntityLayerId, Position}; +use crate::layer::chunk::UnloadedChunk; +use crate::layer::{ChunkLayer, EntityLayer}; +use crate::protocol::packets::play::{ BlockEntityUpdateS2c, ChunkDataS2c, ChunkDeltaUpdateS2c, EntitiesDestroyS2c, EntitySpawnS2c, MoveRelativeS2c, UnloadChunkS2c, }; -use valence_packet::protocol::Packet; - +use crate::protocol::Packet; use crate::testing::ScenarioSingleClient; +use crate::{BlockState, ChunkView, Despawned, Server}; #[test] fn block_create_destroy() { diff --git a/src/tests/player_list.rs b/src/tests/player_list.rs index b58e1dd11..2a3e4954b 100644 --- a/src/tests/player_list.rs +++ b/src/tests/player_list.rs @@ -1,8 +1,7 @@ -use valence_layer::chunk::UnloadedChunk; -use valence_layer::ChunkLayer; -use valence_packet::packets::play::{PlayerListS2c, PlayerSpawnS2c}; - +use crate::layer::chunk::UnloadedChunk; +use crate::protocol::packets::play::{PlayerListS2c, PlayerSpawnS2c}; use crate::testing::{create_mock_client, ScenarioSingleClient}; +use crate::ChunkLayer; #[test] fn player_list_arrives_before_player_spawn() { diff --git a/src/tests/scoreboard.rs b/src/tests/scoreboard.rs index fb1a5141b..867af687a 100644 --- a/src/tests/scoreboard.rs +++ b/src/tests/scoreboard.rs @@ -1,14 +1,14 @@ -use valence_client::VisibleEntityLayers; -use valence_core::text::IntoText; -use valence_core::Server; -use valence_entity::EntityLayerId; -use valence_layer::EntityLayer; -use valence_packet::packets::play::{ - ScoreboardDisplayS2c, ScoreboardObjectiveUpdateS2c, ScoreboardPlayerUpdateS2c, -}; use valence_scoreboard::*; +use crate::client::VisibleEntityLayers; +use crate::entity::EntityLayerId; +use crate::layer::EntityLayer; +use crate::protocol::packets::play::{ + ScoreboardDisplayS2c, ScoreboardObjectiveUpdateS2c, ScoreboardPlayerUpdateS2c, +}; use crate::testing::ScenarioSingleClient; +use crate::text::IntoText; +use crate::Server; #[test] fn show_scoreboard_when_added_to_layer() { diff --git a/tools/packet_inspector/src/app/text_viewer.rs b/tools/packet_inspector/src/app/text_viewer.rs index 987c114bc..edaf80002 100644 --- a/tools/packet_inspector/src/app/text_viewer.rs +++ b/tools/packet_inspector/src/app/text_viewer.rs @@ -2,12 +2,11 @@ use super::{SharedState, Tab, View}; mod utils { use packet_inspector::{Packet as ProxyPacket, PacketSide, PacketState}; - use valence::packet::packets::play::*; - use valence::packet::packets::status::*; - use valence::packet::packets::login::*; - use valence::packet::packets::handshaking::*; - use valence::packet::protocol::Packet; - use valence::protocol::Decode; + use valence::protocol::packets::handshaking::*; + use valence::protocol::packets::login::*; + use valence::protocol::packets::play::*; + use valence::protocol::packets::status::*; + use valence::protocol::{Decode, Packet}; include!(concat!(env!("OUT_DIR"), "/packet_to_string.rs")); } diff --git a/tools/packet_inspector/src/lib.rs b/tools/packet_inspector/src/lib.rs index 697f12cec..198f4a63e 100644 --- a/tools/packet_inspector/src/lib.rs +++ b/tools/packet_inspector/src/lib.rs @@ -7,12 +7,12 @@ use std::sync::{Arc, OnceLock}; pub use packet_registry::Packet; use tokio::net::TcpStream; use tokio::sync::RwLock; -use valence::packet::packets::handshaking::handshake_c2s::HandshakeNextState; -use valence::packet::packets::handshaking::HandshakeC2s; -use valence::packet::packets::login::{LoginCompressionS2c, LoginSuccessS2c}; -use valence::packet::protocol::decode::PacketFrame; -use valence::packet::protocol::Packet as ValencePacket; -use valence::protocol::Decode; +use valence::protocol::decode::PacketFrame; +use valence::protocol::packets::handshaking::handshake_c2s::HandshakeNextState; +use valence::protocol::packets::handshaking::HandshakeC2s; +use valence::protocol::packets::login::{LoginCompressionS2c, LoginSuccessS2c}; +use valence::protocol::{Decode, Packet as ValencePacket}; +use valence::CompressionThreshold; use crate::packet_io::PacketIo; use crate::packet_registry::PacketRegistry; @@ -74,7 +74,7 @@ impl Proxy { let (mut server_reader, mut server_writer) = server.split(); let current_state_inner = Arc::new(RwLock::new(PacketState::Handshaking)); - let threshold_inner: Arc>> = Arc::new(RwLock::new(None)); + let threshold_inner: Arc> = Arc::new(RwLock::new(None)); let current_state = current_state_inner.clone(); let threshold = threshold_inner.clone(); diff --git a/tools/packet_inspector/src/packet_io.rs b/tools/packet_inspector/src/packet_io.rs index c1a847f35..341b6155c 100644 --- a/tools/packet_inspector/src/packet_io.rs +++ b/tools/packet_inspector/src/packet_io.rs @@ -5,15 +5,15 @@ use anyhow::ensure; use bytes::{BufMut, BytesMut}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; -use valence::__private::VarInt; -use valence::packet::protocol::decode::{PacketDecoder, PacketFrame}; -use valence::packet::protocol::encode::PacketEncoder; -use valence::protocol::{Encode, MAX_PACKET_SIZE}; +use valence::protocol::decode::{PacketDecoder, PacketFrame}; +use valence::protocol::encode::PacketEncoder; +use valence::protocol::{Encode, VarInt, MAX_PACKET_SIZE}; +use valence::CompressionThreshold; pub(crate) struct PacketIoReader { reader: tokio::io::ReadHalf, dec: PacketDecoder, - threshold: Option, + threshold: CompressionThreshold, } impl PacketIoReader { @@ -49,7 +49,7 @@ impl PacketIoReader { pub(crate) struct PacketIoWriter { writer: tokio::io::WriteHalf, enc: PacketEncoder, - threshold: Option, + threshold: CompressionThreshold, } impl PacketIoWriter { @@ -147,7 +147,7 @@ pub(crate) struct PacketIo { stream: TcpStream, enc: PacketEncoder, dec: PacketDecoder, - threshold: Option, + threshold: CompressionThreshold, } const READ_BUF_SIZE: usize = 1024; diff --git a/tools/packet_inspector/src/packet_registry.rs b/tools/packet_inspector/src/packet_registry.rs index 4e8d7f18e..9eb77656c 100644 --- a/tools/packet_inspector/src/packet_registry.rs +++ b/tools/packet_inspector/src/packet_registry.rs @@ -3,7 +3,8 @@ use std::sync::RwLock; use bytes::Bytes; use time::OffsetDateTime; -use valence::packet::protocol::decode::PacketFrame; +use valence::protocol::decode::PacketFrame; +use valence::CompressionThreshold; pub struct PacketRegistry { packets: RwLock>, @@ -62,7 +63,7 @@ impl PacketRegistry { &self, side: PacketSide, state: PacketState, - threshold: Option, + threshold: CompressionThreshold, packet: &PacketFrame, ) -> anyhow::Result<()> { let mut p = self.get_specific_packet(side, state, packet.id); diff --git a/tools/playground/Cargo.toml b/tools/playground/Cargo.toml index d1cd5ce9f..8a1a86913 100644 --- a/tools/playground/Cargo.toml +++ b/tools/playground/Cargo.toml @@ -9,5 +9,5 @@ clap.workspace = true valence_math.workspace = true tracing-subscriber.workspace = true tracing.workspace = true -valence_core.workspace = true +valence_server_core.workspace = true valence.workspace = true \ No newline at end of file diff --git a/tools/playground/src/extras.rs b/tools/playground/src/extras.rs index 3b384d03c..2b77ce2f0 100644 --- a/tools/playground/src/extras.rs +++ b/tools/playground/src/extras.rs @@ -1,7 +1,7 @@ //! Put stuff in here if you find that you have to write the same code for //! multiple playgrounds. -use valence::client::command::{SneakEvent, SneakState}; +use valence::client_command::{SneakEvent, SneakState}; use valence::prelude::*; /// Toggles client's game mode between survival and creative when they start diff --git a/tools/stresser/Cargo.toml b/tools/stresser/Cargo.toml index 4f5720f32..f2c8b898e 100644 --- a/tools/stresser/Cargo.toml +++ b/tools/stresser/Cargo.toml @@ -10,6 +10,4 @@ anyhow.workspace = true clap.workspace = true tokio.workspace = true uuid = { workspace = true, features = ["v4"] } -valence_network = { workspace = true } -valence_core = { workspace = true } -valence_client = { workspace = true } +valence_protocol.workspace = true diff --git a/tools/stresser/src/stresser.rs b/tools/stresser/src/stresser.rs index 06b672dff..b4dc90b0c 100644 --- a/tools/stresser/src/stresser.rs +++ b/tools/stresser/src/stresser.rs @@ -5,19 +5,16 @@ use anyhow::bail; use tokio::io::AsyncWriteExt; use tokio::net::TcpStream; use uuid::Uuid; -use valence_core::protocol::var_int::VarInt; -use valence_core::PROTOCOL_VERSION; -use valence_packet::packets::handshaking::handshake_c2s::HandshakeNextState; -use valence_packet::packets::handshaking::HandshakeC2s; -use valence_packet::packets::login::{ +use valence_protocol::packets::handshaking::handshake_c2s::HandshakeNextState; +use valence_protocol::packets::handshaking::HandshakeC2s; +use valence_protocol::packets::login::{ LoginCompressionS2c, LoginHelloC2s, LoginHelloS2c, LoginSuccessS2c, }; -use valence_packet::packets::play::{ +use valence_protocol::packets::play::{ KeepAliveC2s, KeepAliveS2c, PlayerPositionLookS2c, PositionAndOnGroundC2s, TeleportConfirmC2s, }; -use valence_packet::protocol::decode::PacketDecoder; -use valence_packet::protocol::encode::PacketEncoder; -use valence_packet::protocol::Packet; +use valence_protocol::var_int::VarInt; +use valence_protocol::{Packet, PacketDecoder, PacketEncoder, PROTOCOL_VERSION}; pub struct SessionParams<'a> { pub socket_addr: SocketAddr, From 1836693e5be47cdfc854c5734be2ae7ca4dfbaa3 Mon Sep 17 00:00:00 2001 From: Ryan Date: Mon, 7 Aug 2023 08:18:18 -0700 Subject: [PATCH 07/17] add depgraph --- assets/depgraph.svg | 378 ++++++++++++++++++++++++++++++++++++++++++++ crates/README.md | 23 +-- 2 files changed, 381 insertions(+), 20 deletions(-) create mode 100644 assets/depgraph.svg diff --git a/assets/depgraph.svg b/assets/depgraph.svg new file mode 100644 index 000000000..23c995c91 --- /dev/null +++ b/assets/depgraph.svg @@ -0,0 +1,378 @@ + + + + + + + + + +0 + +valence_advancement + + + +1 + +valence_server + + + +0->1 + + + + + +2 + +valence_entity + + + +1->2 + + + + + +11 + +valence_registry + + + +1->11 + + + + + +10 + +valence_server_core + + + +2->10 + + + + + +11->10 + + + + + +6 + +valence_protocol + + + +10->6 + + + + + +3 + +valence_math + + + +4 + +valence_nbt + + + +5 + +valence_ident + + + +7 + +valence_generated + + + +6->7 + + + + + +9 + +valence_text + + + +6->9 + + + + + +7->3 + + + + + +7->5 + + + + + +9->4 + + + + + +9->5 + + + + + +8 + +valence_build_utils + + + +12 + +valence_anvil + + + +12->1 + + + + + +13 + +valence_boss_bar + + + +13->1 + + + + + +14 + +valence_inventory + + + +14->1 + + + + + +15 + +valence_lang + + + +16 + +valence_network + + + +16->1 + + + + + +16->15 + + + + + +17 + +valence_player_list + + + +17->1 + + + + + +18 + +valence_scoreboard + + + +18->1 + + + + + +19 + +valence_spatial_index + + + +20 + +valence_weather + + + +20->1 + + + + + +21 + +valence_world_border + + + +21->1 + + + + + +22 + +dump_schedule + + + +23 + +valence + + + +22->23 + + + + + +23->0 + + + + + +23->12 + + + + + +23->13 + + + + + +23->14 + + + + + +23->16 + + + + + +23->17 + + + + + +23->18 + + + + + +23->20 + + + + + +23->21 + + + + + +24 + +packet_inspector + + + +24->23 + + + + + +25 + +playground + + + +25->23 + + + + + +26 + +stresser + + + +26->6 + + + + + diff --git a/crates/README.md b/crates/README.md index 73e0b6226..882d633e4 100644 --- a/crates/README.md +++ b/crates/README.md @@ -2,27 +2,10 @@ The standard crates used in Valence projects. -All crates here are exported by the main `valence` crate. `valence` is the intended interface for both end users and plugin authors. +All crates here are exported by the main `valence` crate. `valence` is the intended interface for both end users and third-party plugin authors. Crates are versioned in lockstep with the exception of `valence_nbt`. -Ignoring transitive dependencies and `valence_core`, the dependency graph can be described like this: +The output of `cargo depgraph --workspace-only | tred | dot -Tsvg -o depgraph.svg` looks like this: -```mermaid -graph TD - network --> client - client --> instance - biome --> registry - dimension --> registry - instance --> biome - instance --> dimension - instance --> entity - player_list --> client - inventory --> client - anvil --> client - entity --> block - advancement --> client - world_border --> client - boss_bar --> client - weather --> client -``` +![dependency graph](../assets/depgraph.svg) From e50a06800be97ebf9a1fc13e5a3ccc5d9572d68b Mon Sep 17 00:00:00 2001 From: Ryan Date: Mon, 7 Aug 2023 08:52:13 -0700 Subject: [PATCH 08/17] clippy --- crates/valence_math/src/aabb.rs | 1 - crates/valence_server_core/src/lib.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/valence_math/src/aabb.rs b/crates/valence_math/src/aabb.rs index 8be33c53e..48b02e2f7 100644 --- a/crates/valence_math/src/aabb.rs +++ b/crates/valence_math/src/aabb.rs @@ -42,7 +42,6 @@ impl Aabb { /// Returns a new AABB containing a single point `p`. pub fn new_point(p: DVec3) -> Self { - let p = p.into(); Self::new(p, p) } diff --git a/crates/valence_server_core/src/lib.rs b/crates/valence_server_core/src/lib.rs index ca47d39c4..fbec52fa6 100644 --- a/crates/valence_server_core/src/lib.rs +++ b/crates/valence_server_core/src/lib.rs @@ -28,10 +28,10 @@ use bevy_app::prelude::*; use bevy_app::ScheduleRunnerPlugin; use bevy_ecs::prelude::*; pub use despawn::*; -pub use uuid::*; use valence_protocol::CompressionThreshold; use crate::despawn::despawn_marked_entities; +pub use crate::uuid::*; /// Minecraft's standard ticks per second (TPS). pub const DEFAULT_TPS: NonZeroU32 = match NonZeroU32::new(20) { From db21fcb043643dc59005f2bb2500f0e68180d307 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 05:31:52 -0700 Subject: [PATCH 09/17] Add abilities plugin to main plugin group --- src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index fc7b660f5..a94058194 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,6 +49,7 @@ pub use valence_player_list as player_list; use valence_registry::RegistryPlugin; #[cfg(feature = "scoreboard")] pub use valence_scoreboard as scoreboard; +use valence_server::abilities::AbilitiesPlugin; use valence_server::action::ActionPlugin; use valence_server::client::ClientPlugin; use valence_server::client_command::ClientCommandPlugin; @@ -183,7 +184,8 @@ impl PluginGroup for DefaultPlugins { .add(InteractItemPlugin) .add(OpLevelPlugin) .add(ResourcePackPlugin) - .add(StatusPlugin); + .add(StatusPlugin) + .add(AbilitiesPlugin); #[cfg(feature = "log")] { From dcbf2cf90ee4a48c64ada05ce3ef785d53cb237c Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 08:30:32 -0700 Subject: [PATCH 10/17] More documentation --- crates/valence_generated/README.md | 4 ++ crates/valence_ident/README.md | 3 ++ crates/valence_ident/src/lib.rs | 2 + crates/valence_ident_macros/README.md | 3 ++ crates/valence_ident_macros/src/lib.rs | 2 + crates/valence_lang/README.md | 5 ++ crates/valence_lang/src/lib.rs | 2 + crates/valence_math/README.md | 6 +++ crates/valence_math/src/lib.rs | 2 + crates/valence_protocol/README.md | 47 +++++++++++++++++++ crates/valence_protocol/src/decode.rs | 8 ++-- crates/valence_protocol/src/encode.rs | 8 +++- crates/valence_protocol/src/lib.rs | 26 +++++----- crates/valence_protocol/src/packets.rs | 5 ++ .../src/packets/play/difficulty_s2c.rs | 2 +- crates/valence_protocol_macros/README.md | 4 +- crates/valence_registry/README.md | 6 +-- crates/valence_server/README.md | 5 ++ crates/valence_server/src/lib.rs | 4 +- crates/valence_server_core/README.md | 4 +- crates/valence_text/README.md | 3 ++ crates/valence_text/src/lib.rs | 2 +- 22 files changed, 123 insertions(+), 30 deletions(-) create mode 100644 crates/valence_generated/README.md create mode 100644 crates/valence_ident/README.md create mode 100644 crates/valence_ident_macros/README.md create mode 100644 crates/valence_lang/README.md create mode 100644 crates/valence_math/README.md create mode 100644 crates/valence_protocol/README.md create mode 100644 crates/valence_server/README.md create mode 100644 crates/valence_text/README.md diff --git a/crates/valence_generated/README.md b/crates/valence_generated/README.md new file mode 100644 index 000000000..33fba36c1 --- /dev/null +++ b/crates/valence_generated/README.md @@ -0,0 +1,4 @@ +# valence_generated + +Contains the majority of Valence's generated Rust code for use with Minecraft's protocol. +This is currently meant to be an implementation detail of `valence_protocol`. diff --git a/crates/valence_ident/README.md b/crates/valence_ident/README.md new file mode 100644 index 000000000..dd84ba7b2 --- /dev/null +++ b/crates/valence_ident/README.md @@ -0,0 +1,3 @@ +# valence_ident + +A library for parsing Minecraft's [resource locations](https://minecraft.fandom.com/wiki/Resource_location) (also known as "resource identifiers" and "namespaced IDs") \ No newline at end of file diff --git a/crates/valence_ident/src/lib.rs b/crates/valence_ident/src/lib.rs index bf27b2124..fe6579f83 100644 --- a/crates/valence_ident/src/lib.rs +++ b/crates/valence_ident/src/lib.rs @@ -1,3 +1,5 @@ +#![doc = include_str!("../README.md")] + //! Resource identifiers. use std::borrow::{Borrow, Cow}; diff --git a/crates/valence_ident_macros/README.md b/crates/valence_ident_macros/README.md new file mode 100644 index 000000000..d6c164fc4 --- /dev/null +++ b/crates/valence_ident_macros/README.md @@ -0,0 +1,3 @@ +# valence_ident_macros + +Proc macros for `valence_ident`. diff --git a/crates/valence_ident_macros/src/lib.rs b/crates/valence_ident_macros/src/lib.rs index 8b1fdf53a..a8abb77ce 100644 --- a/crates/valence_ident_macros/src/lib.rs +++ b/crates/valence_ident_macros/src/lib.rs @@ -1,3 +1,5 @@ +#![doc = include_str!("../README.md")] + use proc_macro::TokenStream as StdTokenStream; use proc_macro2::TokenStream; use quote::quote; diff --git a/crates/valence_lang/README.md b/crates/valence_lang/README.md new file mode 100644 index 000000000..648333bc9 --- /dev/null +++ b/crates/valence_lang/README.md @@ -0,0 +1,5 @@ +# valence_lang + +Contains code for managing Minecraft's languages and translation keys. + +Currently, this only contains Minecraft's translation keys as Rust constants. In the future it may be expanded to include language registries, functions to resolve translation keys at runtime, etc. diff --git a/crates/valence_lang/src/lib.rs b/crates/valence_lang/src/lib.rs index 8c450a67c..0f8f3b934 100644 --- a/crates/valence_lang/src/lib.rs +++ b/crates/valence_lang/src/lib.rs @@ -1,3 +1,5 @@ +#![doc = include_str!("../README.md")] + /// Contains Rust constants for all of Minecraft's standard translation keys. /// /// Use these with `Text::translate`. diff --git a/crates/valence_math/README.md b/crates/valence_math/README.md new file mode 100644 index 000000000..d7f7f9189 --- /dev/null +++ b/crates/valence_math/README.md @@ -0,0 +1,6 @@ +# valence_math + +Common math utilities for Valence. + +This crate re-exports the contents of [`glam`](https://docs.rs/glam/latest/glam/) along with our own types such as [`Aabb`]. +For more information, please see `glam`'s documentation. diff --git a/crates/valence_math/src/lib.rs b/crates/valence_math/src/lib.rs index f7f1344cf..bf3db2c01 100644 --- a/crates/valence_math/src/lib.rs +++ b/crates/valence_math/src/lib.rs @@ -1,3 +1,5 @@ +#![doc = include_str!("../README.md")] + mod aabb; pub use aabb::Aabb; diff --git a/crates/valence_protocol/README.md b/crates/valence_protocol/README.md new file mode 100644 index 000000000..c84494473 --- /dev/null +++ b/crates/valence_protocol/README.md @@ -0,0 +1,47 @@ +# valence_protocol + +A protocol library for _Minecraft: Java Edition_. Use this to build clients, servers, proxies, or something novel! + +`valence_protocol` is primarily concerned with defining all of Minecraft's [network packets](packets) and the process for encoding and decoding them. To encode and decode packets, use the [`PacketEncoder`] and [`PacketDecoder`] types. + +```rust +use valence_protocol::{PacketEncoder, PacketDecoder, Difficulty}; +use valence_protocol::packets::play::DifficultyS2c; + +let mut encoder = PacketEncoder::new(); + +let packet = DifficultyS2c { + difficulty: Difficulty::Peaceful, + locked: true, +}; + +// Encode our packet struct. +encoder.append_packet(&packet); + +// Take our encoded packet(s) out of the encoder. +let bytes = encoder.take(); + +let mut decoder = PacketDecoder::new(); + +// Put it in the decoder. +decoder.queue_bytes(bytes); + +// Get the next packet "frame" from the decoder and use that to decode the body of the packet. +// Packet frames can be thought of as type-erased packet structs. +let frame = decoder.try_next_packet().unwrap().unwrap(); +let decoded_packet = frame.decode::().unwrap(); + +// Check that our original packet struct is the same as the one we just decoded. +assert_eq!(&packet, &decoded_packet); +``` + +## Supported Minecraft Versions + +Currently, `valence_protocol` only intends to support the most recent stable version of Minecraft. New Minecraft versions often entail a major version bump, since breaking changes to packet definitions are frequent. + +The currently targeted Minecraft version and protocol version can be checked using the [`MINECRAFT_VERSION`] and [`PROTOCOL_VERSION`] constants. + +## Feature Flags + +- `encryption`: Enables support for packet encryption. +- `compression`: Enables support for packet compression. diff --git a/crates/valence_protocol/src/decode.rs b/crates/valence_protocol/src/decode.rs index 5fa431175..9988ec75d 100644 --- a/crates/valence_protocol/src/decode.rs +++ b/crates/valence_protocol/src/decode.rs @@ -1,12 +1,12 @@ #[cfg(feature = "encryption")] -use aes::cipher::generic_array::GenericArray; -#[cfg(feature = "encryption")] -use aes::cipher::{BlockDecryptMut, BlockSizeUser, KeyIvInit}; +use aes::cipher::{generic_array::GenericArray, BlockDecryptMut, BlockSizeUser, KeyIvInit}; use anyhow::{bail, ensure, Context}; use bytes::{Buf, BytesMut}; use crate::var_int::{VarInt, VarIntDecodeError}; -use crate::{CompressionThreshold, Decode, Packet, MAX_PACKET_SIZE}; +#[cfg(feature = "encryption")] +use crate::CompressionThreshold; +use crate::{Decode, Packet, MAX_PACKET_SIZE}; /// The AES block cipher with a 128 bit key, using the CFB-8 mode of /// operation. diff --git a/crates/valence_protocol/src/encode.rs b/crates/valence_protocol/src/encode.rs index 474ecf771..9018bdbc4 100644 --- a/crates/valence_protocol/src/encode.rs +++ b/crates/valence_protocol/src/encode.rs @@ -167,10 +167,14 @@ impl PacketEncoder { self.threshold = threshold; } - /// Encrypts all future packets **and any packets that have - /// not been [taken] yet.** + /// Initializes the cipher with the given key. All future packets **and any + /// that have not been [taken] yet** are encrypted. /// /// [taken]: Self::take + /// + /// # Panics + /// + /// Panics if encryption is already enabled. #[cfg(feature = "encryption")] pub fn enable_encryption(&mut self, key: &[u8; 16]) { assert!(self.cipher.is_none(), "encryption is already enabled"); diff --git a/crates/valence_protocol/src/lib.rs b/crates/valence_protocol/src/lib.rs index 4ef9822e4..a551e35be 100644 --- a/crates/valence_protocol/src/lib.rs +++ b/crates/valence_protocol/src/lib.rs @@ -1,8 +1,8 @@ -// #![doc = include_str!("../README.md")] +#![doc = include_str!("../README.md")] #![deny( rustdoc::broken_intra_doc_links, rustdoc::private_intra_doc_links, - // rustdoc::missing_crate_level_docs, + rustdoc::missing_crate_level_docs, rustdoc::invalid_codeblock_attributes, rustdoc::invalid_rust_codeblocks, rustdoc::bare_urls, @@ -59,6 +59,7 @@ pub use block_pos::BlockPos; pub use byte_angle::ByteAngle; pub use chunk_pos::ChunkPos; pub use decode::PacketDecoder; +pub use difficulty::Difficulty; pub use direction::Direction; pub use encode::{PacketEncoder, WritePacket}; pub use game_mode::GameMode; @@ -110,9 +111,10 @@ pub type CompressionThreshold = Option; /// type definition. /// /// For enums, the variant to encode is marked by a leading [`VarInt`] -/// discriminant (tag). The discriminant value can be changed using the `#[tag = -/// ...]` attribute on the variant in question. Discriminant values are assigned -/// to variants using rules similar to regular enum discriminants. +/// discriminant (tag). The discriminant value can be changed using the +/// `#[packet(tag = ...)]` attribute on the variant in question. Discriminant +/// values are assigned to variants using rules similar to regular enum +/// discriminants. /// /// ``` /// use valence_protocol::Encode; @@ -165,9 +167,10 @@ pub trait Encode { /// what the default implementation does), but a more efficient /// implementation may be used. /// - /// This optimization is very important for some types like `u8` where - /// [`write_all`] is used. Because impl specialization is unavailable in - /// stable Rust, we must make the slice specialization part of this trait. + /// This method is important for some types like `u8` where the entire slice + /// can be encoded in a single call to [`write_all`]. Because impl + /// specialization is unavailable in stable Rust at the time of writing, + /// we must make the slice specialization part of this trait. /// /// [`write_all`]: Write::write_all fn encode_slice(slice: &[Self], mut w: impl Write) -> anyhow::Result<()> @@ -196,9 +199,10 @@ pub trait Encode { /// type definition. /// /// For enums, the variant to decode is determined by a leading [`VarInt`] -/// discriminant (tag). The discriminant value can be changed using the `#[tag = -/// ...]` attribute on the variant in question. Discriminant values are assigned -/// to variants using rules similar to regular enum discriminants. +/// discriminant (tag). The discriminant value can be changed using the +/// `#[packet(tag = ...)]` attribute on the variant in question. Discriminant +/// values are assigned to variants using rules similar to regular enum +/// discriminants. /// /// ``` /// use valence_protocol::Decode; diff --git a/crates/valence_protocol/src/packets.rs b/crates/valence_protocol/src/packets.rs index d377d5fc1..c0708ff4f 100644 --- a/crates/valence_protocol/src/packets.rs +++ b/crates/valence_protocol/src/packets.rs @@ -1,3 +1,8 @@ +//! All of Minecraft's network packets. +//! +//! Packets are grouped in submodules according to the protocol stage they're +//! used in. Names are derived from the FabricMC Yarn mappings for consistency. + use std::borrow::Cow; use std::io::Write; diff --git a/crates/valence_protocol/src/packets/play/difficulty_s2c.rs b/crates/valence_protocol/src/packets/play/difficulty_s2c.rs index b3d298587..ba9a521a9 100644 --- a/crates/valence_protocol/src/packets/play/difficulty_s2c.rs +++ b/crates/valence_protocol/src/packets/play/difficulty_s2c.rs @@ -1,6 +1,6 @@ use super::*; -#[derive(Copy, Clone, Debug, Encode, Decode, Packet)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Encode, Decode, Packet)] #[packet(id = packet_id::DIFFICULTY_S2C)] pub struct DifficultyS2c { pub difficulty: Difficulty, diff --git a/crates/valence_protocol_macros/README.md b/crates/valence_protocol_macros/README.md index aa4a88066..fc74027cc 100644 --- a/crates/valence_protocol_macros/README.md +++ b/crates/valence_protocol_macros/README.md @@ -1,3 +1,3 @@ -# valence_core_macros +# valence_protocol_macros -Procedural macros for `valence_core` +Procedural macros for `valence_protocol` diff --git a/crates/valence_registry/README.md b/crates/valence_registry/README.md index 9a598ac9e..088afc7c2 100644 --- a/crates/valence_registry/README.md +++ b/crates/valence_registry/README.md @@ -1,7 +1,3 @@ # valence_registry -Manages Minecraft's networked registries in a generic way. This includes the registry codec sent to clients during the initial join. - -Consumers of `registry` such as `biome` and `dimension` are expected to update themselves in the registries defined here. Minecraft's default registry codec is loaded by default. - -End users are not expected to use this module directly. +Contains Minecraft's networked registries. This includes the registry codec sent to clients during the initial join. diff --git a/crates/valence_server/README.md b/crates/valence_server/README.md new file mode 100644 index 000000000..13c1fdc91 --- /dev/null +++ b/crates/valence_server/README.md @@ -0,0 +1,5 @@ +# valence_server + +Defines the "core" of the Valence server that plugins depend on. If a plugin module here is large enough, it may be split off into its own crate to reduce compile times. + +The contents of `valence_server` are re-exported from the main `valence` crate, so end users should not interact with this crate directly. diff --git a/crates/valence_server/src/lib.rs b/crates/valence_server/src/lib.rs index 1c4798c54..51b518f96 100644 --- a/crates/valence_server/src/lib.rs +++ b/crates/valence_server/src/lib.rs @@ -46,8 +46,8 @@ pub use event_loop::{EventLoopPostUpdate, EventLoopPreUpdate, EventLoopUpdate}; pub use layer::{ChunkLayer, EntityLayer, Layer, LayerBundle}; pub use valence_protocol::{ block, ident, item, math, text, uuid, BlockPos, BlockState, ChunkPos, CompressionThreshold, - Direction, GameMode, Hand, Ident, ItemKind, ItemStack, PlayerTextures, Text, MINECRAFT_VERSION, - PROTOCOL_VERSION, + Difficulty, Direction, GameMode, Hand, Ident, ItemKind, ItemStack, PlayerTextures, Text, + MINECRAFT_VERSION, PROTOCOL_VERSION, }; pub use valence_server_core::*; pub use { diff --git a/crates/valence_server_core/README.md b/crates/valence_server_core/README.md index 9a5df31cd..f59b33aed 100644 --- a/crates/valence_server_core/README.md +++ b/crates/valence_server_core/README.md @@ -1,3 +1,3 @@ -# valence_core +# valence_server_core -Contains foundational code or modules too small to deserve their own crate. The contents of `valence_core` are re-exported by the main `valence` crate. \ No newline at end of file +Contains some miscellaneous types for the `valence_server` family of crates, like `valence_entity`. `valence_registry`, and `valence_server`. diff --git a/crates/valence_text/README.md b/crates/valence_text/README.md new file mode 100644 index 000000000..ad3a1fa3f --- /dev/null +++ b/crates/valence_text/README.md @@ -0,0 +1,3 @@ +# valence_text + +A library for parsing and writing Minecraft's [JSON text format](https://minecraft.fandom.com/wiki/Raw_JSON_text_format) diff --git a/crates/valence_text/src/lib.rs b/crates/valence_text/src/lib.rs index 508d3747b..fde4cb1f9 100644 --- a/crates/valence_text/src/lib.rs +++ b/crates/valence_text/src/lib.rs @@ -1,4 +1,4 @@ -//! Formatted text. +#![doc = include_str!("../README.md")] use std::borrow::Cow; use std::ops::{Deref, DerefMut}; From 323721fd53dab9b05855fb2dc43fcf38c7d6caa5 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 08:37:47 -0700 Subject: [PATCH 11/17] clippy --- examples/cow_sphere.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/cow_sphere.rs b/examples/cow_sphere.rs index 5c4cfe6f0..e9f9ba124 100644 --- a/examples/cow_sphere.rs +++ b/examples/cow_sphere.rs @@ -2,11 +2,11 @@ use std::f64::consts::TAU; +use valence::abilities::{PlayerStartFlyingEvent, PlayerStopFlyingEvent}; use valence::math::{DQuat, EulerRot}; +use valence::message::SendMessage; use valence::prelude::*; -use valence_client::abilities::{PlayerStartFlyingEvent, PlayerStopFlyingEvent}; -use valence_client::message::SendMessage; -use valence_core::text::color::NamedColor; +use valence_text::color::NamedColor; type SpherePartBundle = valence::entity::cow::CowEntityBundle; From 434cba19b7d2354f2cfd89b059ae333799cf10cf Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 08:42:47 -0700 Subject: [PATCH 12/17] doc --- crates/valence_server/src/abilities.rs | 17 +++++++++++------ crates/valence_server/src/lib.rs | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/valence_server/src/abilities.rs b/crates/valence_server/src/abilities.rs index 824016092..3de9a30e1 100644 --- a/crates/valence_server/src/abilities.rs +++ b/crates/valence_server/src/abilities.rs @@ -44,14 +44,19 @@ pub struct PlayerStopFlyingEvent { pub client: Entity, } -/// Order of execution : -/// 1. [`update_game_mode`] : Watch [`GameMode`] changes => Send -/// [`GameStateChangeS2c`] to update the client's gamemode -/// 2. [`update_client_player_abilities`] : Watch [`PlayerAbilitiesFlags`], +/// Order of execution: +/// 1. `update_game_mode`: Watch [`GameMode`] changes => Send +/// `GameStateChangeS2c` to update the client's gamemode +/// +/// 2. `update_client_player_abilities`: Watch [`PlayerAbilitiesFlags`], /// [`FlyingSpeed`] and [`FovModifier`] changes => Send [`PlayerAbilitiesS2c`] -/// to update the client's abilities 3. [`update_player_abilities`] : Watch +/// to update the client's abilities +/// +/// 3. `update_player_abilities`: Watch /// [`GameMode`] changes => Update [`PlayerAbilitiesFlags`] according to the -/// [`GameMode`] 4. [`update_server_player_abilities`] : Watch +/// [`GameMode`] +/// +/// 4. `update_server_player_abilities`: Watch /// [`UpdatePlayerAbilitiesC2s`] packets => Update [`PlayerAbilitiesFlags`] /// according to the packet pub struct AbilitiesPlugin; diff --git a/crates/valence_server/src/lib.rs b/crates/valence_server/src/lib.rs index 51b518f96..4b29dd3ac 100644 --- a/crates/valence_server/src/lib.rs +++ b/crates/valence_server/src/lib.rs @@ -1,4 +1,4 @@ -// #![doc = include_str!("../README.md")] +#![doc = include_str!("../README.md")] #![deny( rustdoc::broken_intra_doc_links, rustdoc::private_intra_doc_links, From 6be6fe81cd5e1014bc48a1145db02319741f18b8 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 08:43:53 -0700 Subject: [PATCH 13/17] fmt --- crates/valence_server/src/abilities.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/valence_server/src/abilities.rs b/crates/valence_server/src/abilities.rs index 3de9a30e1..45dcb2ca5 100644 --- a/crates/valence_server/src/abilities.rs +++ b/crates/valence_server/src/abilities.rs @@ -47,15 +47,15 @@ pub struct PlayerStopFlyingEvent { /// Order of execution: /// 1. `update_game_mode`: Watch [`GameMode`] changes => Send /// `GameStateChangeS2c` to update the client's gamemode -/// +/// /// 2. `update_client_player_abilities`: Watch [`PlayerAbilitiesFlags`], /// [`FlyingSpeed`] and [`FovModifier`] changes => Send [`PlayerAbilitiesS2c`] /// to update the client's abilities -/// +/// /// 3. `update_player_abilities`: Watch /// [`GameMode`] changes => Update [`PlayerAbilitiesFlags`] according to the /// [`GameMode`] -/// +/// /// 4. `update_server_player_abilities`: Watch /// [`UpdatePlayerAbilitiesC2s`] packets => Update [`PlayerAbilitiesFlags`] /// according to the packet From 75b7ee05069ad40bf54ffcab07008fe155481ddb Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 09:31:28 -0700 Subject: [PATCH 14/17] fix tests --- Cargo.toml | 1 - crates/valence_server/src/client.rs | 2 ++ src/tests/client.rs | 27 +++++++++++++-------------- src/tests/weather.rs | 5 ++--- src/tests/world_border.rs | 7 +++---- 5 files changed, 20 insertions(+), 22 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index afba9b398..b30fc7bcd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,6 @@ anyhow.workspace = true bevy_app.workspace = true bevy_ecs.workspace = true bevy_log = { workspace = true, optional = true } -glam.workspace = true uuid.workspace = true bytes.workspace = true rand.workspace = true diff --git a/crates/valence_server/src/client.rs b/crates/valence_server/src/client.rs index 7232a697f..5f444ca41 100644 --- a/crates/valence_server/src/client.rs +++ b/crates/valence_server/src/client.rs @@ -132,6 +132,7 @@ pub struct ClientBundle { pub portal_cooldown: crate::spawn::PortalCooldown, pub flying_speed: crate::abilities::FlyingSpeed, pub fov_modifier: crate::abilities::FovModifier, + pub player_abilities_flags: crate::abilities::PlayerAbilitiesFlags, pub player: PlayerEntityBundle, } @@ -172,6 +173,7 @@ impl ClientBundle { portal_cooldown: Default::default(), flying_speed: Default::default(), fov_modifier: Default::default(), + player_abilities_flags: Default::default(), player: PlayerEntityBundle { uuid: UniqueId(args.uuid), ..Default::default() diff --git a/src/tests/client.rs b/src/tests/client.rs index 2ed99a38e..0055469f3 100644 --- a/src/tests/client.rs +++ b/src/tests/client.rs @@ -1,13 +1,12 @@ -use glam::DVec3; - use crate::abilities::PlayerAbilitiesFlags; use crate::layer::chunk::UnloadedChunk; use crate::layer::ChunkLayer; +use crate::math::DVec3; use crate::protocol::packets::play::{ FullC2s, MoveRelativeS2c, PlayerPositionLookS2c, TeleportConfirmC2s, }; use crate::testing::{create_mock_client, ScenarioSingleClient}; -use crate::ChunkPos; +use crate::{ChunkPos, GameMode}; #[test] fn client_teleport_and_move() { @@ -64,38 +63,38 @@ fn client_teleport_and_move() { #[test] fn client_gamemode_changed_ability() { - let mut senario = ScenarioSingleClient::new(); + let mut scenario = ScenarioSingleClient::new(); - *senario + *scenario .app .world - .get_mut::(senario.client) + .get_mut::(scenario.client) .unwrap() = GameMode::Creative; - senario.app.update(); + scenario.app.update(); - let abilities = senario + let abilities = scenario .app .world - .get::(senario.client) + .get::(scenario.client) .unwrap(); assert!(abilities.allow_flying()); assert!(abilities.instant_break()); assert!(abilities.invulnerable()); - *senario + *scenario .app .world - .get_mut::(senario.client) + .get_mut::(scenario.client) .unwrap() = GameMode::Adventure; - senario.app.update(); + scenario.app.update(); - let abilities = senario + let abilities = scenario .app .world - .get::(senario.client) + .get::(scenario.client) .unwrap(); assert!(!abilities.allow_flying()); diff --git a/src/tests/weather.rs b/src/tests/weather.rs index 9c2495a27..2a353754a 100644 --- a/src/tests/weather.rs +++ b/src/tests/weather.rs @@ -1,7 +1,6 @@ -use valence_packet::packets::play::GameStateChangeS2c; -use valence_weather::{Rain, Thunder, WeatherBundle}; - +use crate::protocol::packets::play::GameStateChangeS2c; use crate::testing::*; +use crate::weather::{Rain, Thunder, WeatherBundle}; #[test] fn test_client_initialization_on_join() { diff --git a/src/tests/world_border.rs b/src/tests/world_border.rs index dce82118a..274ae51a2 100644 --- a/src/tests/world_border.rs +++ b/src/tests/world_border.rs @@ -1,15 +1,14 @@ -use valence_packet::packets::play::{ +use crate::protocol::packets::play::{ WorldBorderCenterChangedS2c, WorldBorderInitializeS2c, WorldBorderInterpolateSizeS2c, WorldBorderSizeChangedS2c, WorldBorderWarningBlocksChangedS2c, WorldBorderWarningTimeChangedS2c, }; -use valence_world_border::{ +use crate::testing::*; +use crate::world_border::{ WorldBorderBundle, WorldBorderCenter, WorldBorderLerp, WorldBorderPortalTpBoundary, WorldBorderWarnBlocks, WorldBorderWarnTime, }; -use crate::testing::*; - #[test] fn test_intialize_on_join() { let ScenarioSingleClient { From c39bccb94f0439fa94db1eca8ad0390a83c32365 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 16:48:10 -0700 Subject: [PATCH 15/17] please work --- benches/many_players.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benches/many_players.rs b/benches/many_players.rs index 29fce678a..cb757ad68 100644 --- a/benches/many_players.rs +++ b/benches/many_players.rs @@ -2,12 +2,12 @@ use std::time::Duration; use bevy_app::prelude::*; use criterion::Criterion; -use glam::DVec3; use rand::Rng; use valence::entity::Position; use valence::keepalive::KeepaliveSettings; use valence::layer::chunk::UnloadedChunk; use valence::layer::LayerBundle; +use valence::math::DVec3; use valence::network::NetworkPlugin; use valence::protocol::packets::play::{FullC2s, HandSwingC2s}; use valence::registry::{BiomeRegistry, DimensionTypeRegistry}; From 57de93f84851ae8e1c86112af56d5a7092846322 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 17:05:46 -0700 Subject: [PATCH 16/17] please --- crates/valence_scoreboard/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/valence_scoreboard/README.md b/crates/valence_scoreboard/README.md index 65a04a85d..886df9e36 100644 --- a/crates/valence_scoreboard/README.md +++ b/crates/valence_scoreboard/README.md @@ -11,7 +11,7 @@ Example: ```rust # use bevy_ecs::prelude::*; use valence_scoreboard::*; -use valence_protocol::text::IntoText; +use valence_server::protocol::text::IntoText; fn spawn_scoreboard(mut commands: Commands) { commands.spawn(ObjectiveBundle { From cfba6d9fc590a271173d7140f084fd8f001e30ff Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 9 Aug 2023 17:25:26 -0700 Subject: [PATCH 17/17] we good? --- crates/valence_server/src/chunk_view.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/valence_server/src/chunk_view.rs b/crates/valence_server/src/chunk_view.rs index eb1503460..134949faf 100644 --- a/crates/valence_server/src/chunk_view.rs +++ b/crates/valence_server/src/chunk_view.rs @@ -62,8 +62,7 @@ impl ChunkView { /// # Examples /// /// ``` - /// use valence_protocol::chunk_pos::ChunkPos; - /// use valence_protocol::chunk_view::ChunkView; + /// use valence_server::{ChunkPos, ChunkView}; /// /// let view = ChunkView::new(ChunkPos::new(5, -4), 16); /// let (min, max) = view.bounding_box();