1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00

Entity metadata (#37)

* add example generated metadata.rs

* metadata.rs codegen

* add the files

* add comment to top of metadata.rs

* avoid clone

* metadata

* defaults

* defaults

* fix metadata readers and writers

* fix bad bitmasks and ignore some clippy warnings in generated code

* add set_index function to entity metadatas

* applying metadata
This commit is contained in:
mat 2022-11-06 14:05:01 -06:00 committed by GitHub
parent 9bc5175116
commit d112856ff6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 8358 additions and 167 deletions

15
Cargo.lock generated
View file

@ -329,6 +329,7 @@ dependencies = [
"azalea-core", "azalea-core",
"azalea-nbt", "azalea-nbt",
"azalea-registry", "azalea-registry",
"enum-as-inner 0.5.1",
"log", "log",
"nohash-hasher", "nohash-hasher",
"thiserror", "thiserror",
@ -649,6 +650,18 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "enum-as-inner"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "env_logger" name = "env_logger"
version = "0.9.1" version = "0.9.1"
@ -1969,7 +1982,7 @@ dependencies = [
"async-trait", "async-trait",
"cfg-if", "cfg-if",
"data-encoding", "data-encoding",
"enum-as-inner", "enum-as-inner 0.3.4",
"futures-channel", "futures-channel",
"futures-io", "futures-io",
"futures-util", "futures-util",

View file

@ -105,9 +105,14 @@ fn create_impl_mcbufreadable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
quote! { quote! {
impl azalea_buf::McBufReadable for #ident { impl azalea_buf::McBufReadable for #ident {
fn read_from(buf: &mut std::io::Cursor<&[u8]>) -> Result<Self, azalea_buf::BufReadError> fn read_from(buf: &mut std::io::Cursor<&[u8]>) -> Result<Self, azalea_buf::BufReadError> {
{
let id = azalea_buf::McBufVarReadable::var_read_from(buf)?; let id = azalea_buf::McBufVarReadable::var_read_from(buf)?;
Self::read_from_id(buf, id)
}
}
impl #ident {
pub fn read_from_id(buf: &mut std::io::Cursor<&[u8]>, id: u32) -> Result<Self, azalea_buf::BufReadError> {
match id { match id {
#match_contents #match_contents
// you'd THINK this throws an error, but mojang decided to make it default for some reason // you'd THINK this throws an error, but mojang decided to make it default for some reason
@ -170,6 +175,7 @@ fn create_impl_mcbufwritable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
// remember whether it's a data variant so we can do an optimization later // remember whether it's a data variant so we can do an optimization later
let mut is_data_enum = false; let mut is_data_enum = false;
let mut match_arms = quote!(); let mut match_arms = quote!();
let mut match_arms_without_id = quote!();
let mut variant_discrim: u32 = 0; let mut variant_discrim: u32 = 0;
let mut first = true; let mut first = true;
for variant in variants { for variant in variants {
@ -208,6 +214,9 @@ fn create_impl_mcbufwritable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
azalea_buf::McBufVarWritable::var_write_into(&#variant_discrim, buf)?; azalea_buf::McBufVarWritable::var_write_into(&#variant_discrim, buf)?;
} }
}); });
match_arms_without_id.extend(quote! {
Self::#variant_name => {}
});
} }
syn::Fields::Unnamed(_) => { syn::Fields::Unnamed(_) => {
is_data_enum = true; is_data_enum = true;
@ -218,6 +227,11 @@ fn create_impl_mcbufwritable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
azalea_buf::McBufWritable::write_into(data, buf)?; azalea_buf::McBufWritable::write_into(data, buf)?;
} }
}); });
match_arms_without_id.extend(quote! {
Self::#variant_name(data) => {
azalea_buf::McBufWritable::write_into(data, buf)?;
}
});
} }
} }
} }
@ -231,6 +245,14 @@ fn create_impl_mcbufwritable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
Ok(()) Ok(())
} }
} }
impl #ident {
pub fn write_without_id(&self, buf: &mut impl std::io::Write) -> Result<(), std::io::Error> {
match self {
#match_arms_without_id
}
Ok(())
}
}
} }
} else { } else {
// optimization: if it doesn't have data we can just do `as u32` // optimization: if it doesn't have data we can just do `as u32`

View file

@ -289,3 +289,9 @@ impl Display for Component {
} }
} }
} }
impl Default for Component {
fn default() -> Self {
Component::Text(TextComponent::default())
}
}

View file

@ -3,7 +3,7 @@ use std::fmt::Display;
use crate::{base_component::BaseComponent, style::ChatFormatting, Component}; use crate::{base_component::BaseComponent, style::ChatFormatting, Component};
/// A component that contains text that's the same in all locales. /// A component that contains text that's the same in all locales.
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct TextComponent { pub struct TextComponent {
pub base: BaseComponent, pub base: BaseComponent,
pub text: String, pub text: String,

View file

@ -28,7 +28,7 @@ use azalea_protocol::{
resolver, ServerAddress, resolver, ServerAddress,
}; };
use azalea_world::{ use azalea_world::{
entity::{EntityData, EntityMut, EntityRef}, entity::{metadata, EntityData, EntityMetadata, EntityMut, EntityRef},
Dimension, Dimension,
}; };
use log::{debug, error, warn}; use log::{debug, error, warn};
@ -399,7 +399,11 @@ impl Client {
// i'll make this an actual setting later // i'll make this an actual setting later
*dimension_lock = Dimension::new(16, height, min_y); *dimension_lock = Dimension::new(16, height, min_y);
let entity = EntityData::new(client.game_profile.uuid, Vec3::default()); let entity = EntityData::new(
client.game_profile.uuid,
Vec3::default(),
EntityMetadata::Player(metadata::Player::default()),
);
dimension_lock.add_entity(p.player_id, entity); dimension_lock.add_entity(p.player_id, entity);
let mut player_lock = client.player.lock(); let mut player_lock = client.player.lock();
@ -579,8 +583,11 @@ impl Client {
let entity = EntityData::from(p); let entity = EntityData::from(p);
client.dimension.lock().add_entity(p.id, entity); client.dimension.lock().add_entity(p.id, entity);
} }
ClientboundGamePacket::SetEntityData(_p) => { ClientboundGamePacket::SetEntityData(p) => {
// debug!("Got set entity data packet {:?}", p); debug!("Got set entity data packet {:?}", p);
let mut dimension = client.dimension.lock();
let mut entity = dimension.entity_mut(p.id).expect("Entity doesn't exist");
entity.apply_metadata(&p.packed_items.0);
} }
ClientboundGamePacket::UpdateAttributes(_p) => { ClientboundGamePacket::UpdateAttributes(_p) => {
// debug!("Got update attributes packet {:?}", p); // debug!("Got update attributes packet {:?}", p);

View file

@ -2,14 +2,15 @@ use azalea_buf::McBuf;
use crate::floor_mod; use crate::floor_mod;
#[derive(Clone, Copy, Debug, McBuf)] #[derive(Clone, Copy, Debug, McBuf, Default)]
pub enum Direction { pub enum Direction {
#[default]
Down = 0, Down = 0,
Up = 1, Up,
North = 2, North,
South = 3, South,
West = 4, West,
East = 5, East,
} }
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]

View file

@ -1,15 +1,14 @@
use crate::{BlockPos, Slot}; use crate::{BlockPos, Slot};
use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufVarReadable, McBufWritable}; use azalea_buf::McBuf;
use std::io::{Cursor, Write};
#[derive(Debug, Clone, McBuf)] #[derive(Debug, Clone, McBuf, Default)]
pub struct Particle { pub struct Particle {
#[var] #[var]
pub id: i32, pub id: i32,
pub data: ParticleData, pub data: ParticleData,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, McBuf, Default)]
pub enum ParticleData { pub enum ParticleData {
AmbientEntityEffect, AmbientEntityEffect,
AngryVillager, AngryVillager,
@ -32,6 +31,7 @@ pub enum ParticleData {
EnchantedHit, EnchantedHit,
Enchant, Enchant,
EndRod, EndRod,
#[default]
EntityEffect, EntityEffect,
ExplosionEmitter, ExplosionEmitter,
Explosion, Explosion,
@ -151,112 +151,3 @@ pub struct VibrationParticle {
#[var] #[var]
pub ticks: u32, pub ticks: u32,
} }
impl ParticleData {
pub fn read_from_particle_id(buf: &mut Cursor<&[u8]>, id: u32) -> Result<Self, BufReadError> {
Ok(match id {
0 => ParticleData::AmbientEntityEffect,
1 => ParticleData::AngryVillager,
2 => ParticleData::Block(BlockParticle::read_from(buf)?),
3 => ParticleData::BlockMarker(BlockParticle::read_from(buf)?),
4 => ParticleData::Bubble,
5 => ParticleData::Cloud,
6 => ParticleData::Crit,
7 => ParticleData::DamageIndicator,
8 => ParticleData::DragonBreath,
9 => ParticleData::DrippingLava,
10 => ParticleData::FallingLava,
11 => ParticleData::LandingLava,
12 => ParticleData::DrippingWater,
13 => ParticleData::FallingWater,
14 => ParticleData::Dust(DustParticle::read_from(buf)?),
15 => ParticleData::DustColorTransition(DustColorTransitionParticle::read_from(buf)?),
16 => ParticleData::Effect,
17 => ParticleData::ElderGuardian,
18 => ParticleData::EnchantedHit,
19 => ParticleData::Enchant,
20 => ParticleData::EndRod,
21 => ParticleData::EntityEffect,
22 => ParticleData::ExplosionEmitter,
23 => ParticleData::Explosion,
24 => ParticleData::FallingDust(BlockParticle::read_from(buf)?),
25 => ParticleData::Firework,
26 => ParticleData::Fishing,
27 => ParticleData::Flame,
28 => ParticleData::SoulFireFlame,
29 => ParticleData::Soul,
30 => ParticleData::Flash,
31 => ParticleData::HappyVillager,
32 => ParticleData::Composter,
33 => ParticleData::Heart,
34 => ParticleData::InstantEffect,
35 => ParticleData::Item(ItemParticle::read_from(buf)?),
36 => ParticleData::Vibration(VibrationParticle::read_from(buf)?),
37 => ParticleData::ItemSlime,
38 => ParticleData::ItemSnowball,
39 => ParticleData::LargeSmoke,
40 => ParticleData::Lava,
41 => ParticleData::Mycelium,
42 => ParticleData::Note,
43 => ParticleData::Poof,
44 => ParticleData::Portal,
45 => ParticleData::Rain,
46 => ParticleData::Smoke,
47 => ParticleData::Sneeze,
48 => ParticleData::Spit,
49 => ParticleData::SquidInk,
50 => ParticleData::SweepAttack,
51 => ParticleData::TotemOfUndying,
52 => ParticleData::Underwater,
53 => ParticleData::Splash,
54 => ParticleData::Witch,
55 => ParticleData::BubblePop,
56 => ParticleData::CurrentDown,
57 => ParticleData::BubbleColumnUp,
58 => ParticleData::Nautilus,
59 => ParticleData::Dolphin,
60 => ParticleData::CampfireCozySmoke,
61 => ParticleData::CampfireSignalSmoke,
62 => ParticleData::DrippingHoney,
63 => ParticleData::FallingHoney,
64 => ParticleData::LandingHoney,
65 => ParticleData::FallingNectar,
66 => ParticleData::FallingSporeBlossom,
67 => ParticleData::Ash,
68 => ParticleData::CrimsonSpore,
69 => ParticleData::WarpedSpore,
70 => ParticleData::SporeBlossomAir,
71 => ParticleData::DrippingObsidianTear,
72 => ParticleData::FallingObsidianTear,
73 => ParticleData::LandingObsidianTear,
74 => ParticleData::ReversePortal,
75 => ParticleData::WhiteAsh,
76 => ParticleData::SmallFlame,
77 => ParticleData::Snowflake,
78 => ParticleData::DrippingDripstoneLava,
79 => ParticleData::FallingDripstoneLava,
80 => ParticleData::DrippingDripstoneWater,
81 => ParticleData::FallingDripstoneWater,
82 => ParticleData::GlowSquidInk,
83 => ParticleData::Glow,
84 => ParticleData::WaxOn,
85 => ParticleData::WaxOff,
86 => ParticleData::ElectricSpark,
87 => ParticleData::Scrape,
_ => return Err(BufReadError::UnexpectedEnumVariant { id: id as i32 }),
})
}
}
impl McBufReadable for ParticleData {
fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
let id = u32::var_read_from(buf)?;
ParticleData::read_from_particle_id(buf, id)
}
}
impl McBufWritable for ParticleData {
fn write_into(&self, _buf: &mut impl Write) -> Result<(), std::io::Error> {
todo!()
}
}

View file

@ -3,8 +3,9 @@
use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
use std::io::{Cursor, Write}; use std::io::{Cursor, Write};
#[derive(Debug, Clone)] #[derive(Debug, Clone, Default)]
pub enum Slot { pub enum Slot {
#[default]
Empty, Empty,
Present(SlotData), Present(SlotData),
} }

View file

@ -1,7 +1,7 @@
use azalea_buf::McBuf; use azalea_buf::McBuf;
use azalea_core::Vec3; use azalea_core::Vec3;
use azalea_protocol_macros::ClientboundGamePacket; use azalea_protocol_macros::ClientboundGamePacket;
use azalea_world::entity::EntityData; use azalea_world::entity::{EntityData, EntityMetadata};
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone, Debug, McBuf, ClientboundGamePacket)] #[derive(Clone, Debug, McBuf, ClientboundGamePacket)]
@ -33,6 +33,8 @@ impl From<&ClientboundAddEntityPacket> for EntityData {
y: p.y, y: p.y,
z: p.z, z: p.z,
}, },
// default metadata for the entity type
EntityMetadata::from(p.entity_type),
) )
} }
} }

View file

@ -1,7 +1,7 @@
use azalea_buf::McBuf; use azalea_buf::McBuf;
use azalea_core::Vec3; use azalea_core::Vec3;
use azalea_protocol_macros::ClientboundGamePacket; use azalea_protocol_macros::ClientboundGamePacket;
use azalea_world::entity::EntityData; use azalea_world::entity::{metadata, EntityData, EntityMetadata};
use uuid::Uuid; use uuid::Uuid;
/// This packet is sent by the server when a player comes into visible range, not when a player joins. /// This packet is sent by the server when a player comes into visible range, not when a player joins.
@ -26,6 +26,7 @@ impl From<&ClientboundAddPlayerPacket> for EntityData {
y: p.y, y: p.y,
z: p.z, z: p.z,
}, },
EntityMetadata::Player(metadata::Player::default()),
) )
} }
} }

View file

@ -32,7 +32,7 @@ impl McBufReadable for ClientboundLevelParticlesPacket {
let max_speed = f32::read_from(buf)?; let max_speed = f32::read_from(buf)?;
let count = u32::read_from(buf)?; let count = u32::read_from(buf)?;
let data = ParticleData::read_from_particle_id(buf, particle_id)?; let data = ParticleData::read_from_id(buf, particle_id)?;
Ok(Self { Ok(Self {
particle_id, particle_id,

View file

@ -1,10 +1,10 @@
use azalea_buf::McBuf; use azalea_buf::McBuf;
use azalea_protocol_macros::ClientboundGamePacket; use azalea_protocol_macros::ClientboundGamePacket;
use azalea_world::entity::EntityMetadata; use azalea_world::entity::EntityMetadataItems;
#[derive(Clone, Debug, McBuf, ClientboundGamePacket)] #[derive(Clone, Debug, McBuf, ClientboundGamePacket)]
pub struct ClientboundSetEntityDataPacket { pub struct ClientboundSetEntityDataPacket {
#[var] #[var]
pub id: u32, pub id: u32,
pub packed_items: EntityMetadata, pub packed_items: EntityMetadataItems,
} }

View file

@ -15,6 +15,7 @@ azalea-chat = {path = "../azalea-chat", version = "^0.3.0" }
azalea-core = {path = "../azalea-core", version = "^0.3.0" } azalea-core = {path = "../azalea-core", version = "^0.3.0" }
azalea-nbt = {path = "../azalea-nbt", version = "^0.3.0" } azalea-nbt = {path = "../azalea-nbt", version = "^0.3.0" }
azalea-registry = {path = "../azalea-registry", version = "^0.3.0" } azalea-registry = {path = "../azalea-registry", version = "^0.3.0" }
enum-as-inner = "0.5.1"
log = "0.4.17" log = "0.4.17"
nohash-hasher = "0.2.0" nohash-hasher = "0.2.0"
thiserror = "1.0.34" thiserror = "1.0.34"

View file

@ -1,12 +1,16 @@
use azalea_block::BlockState;
use azalea_buf::{BufReadError, McBufVarReadable}; use azalea_buf::{BufReadError, McBufVarReadable};
use azalea_buf::{McBuf, McBufReadable, McBufWritable}; use azalea_buf::{McBuf, McBufReadable, McBufWritable};
use azalea_chat::Component; use azalea_chat::Component;
use azalea_core::{BlockPos, Direction, GlobalPos, Particle, Slot}; use azalea_core::{BlockPos, Direction, GlobalPos, Particle, Slot};
use enum_as_inner::EnumAsInner;
use log::warn;
use nohash_hasher::IntSet;
use std::io::{Cursor, Write}; use std::io::{Cursor, Write};
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct EntityMetadata(Vec<EntityDataItem>); pub struct EntityMetadataItems(pub Vec<EntityDataItem>);
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct EntityDataItem { pub struct EntityDataItem {
@ -16,7 +20,7 @@ pub struct EntityDataItem {
pub value: EntityDataValue, pub value: EntityDataValue,
} }
impl McBufReadable for EntityMetadata { impl McBufReadable for EntityMetadataItems {
fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
let mut metadata = Vec::new(); let mut metadata = Vec::new();
loop { loop {
@ -27,11 +31,11 @@ impl McBufReadable for EntityMetadata {
let value = EntityDataValue::read_from(buf)?; let value = EntityDataValue::read_from(buf)?;
metadata.push(EntityDataItem { index, value }); metadata.push(EntityDataItem { index, value });
} }
Ok(EntityMetadata(metadata)) Ok(EntityMetadataItems(metadata))
} }
} }
impl McBufWritable for EntityMetadata { impl McBufWritable for EntityMetadataItems {
fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> { fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
for item in &self.0 { for item in &self.0 {
item.index.write_into(buf)?; item.index.write_into(buf)?;
@ -42,10 +46,9 @@ impl McBufWritable for EntityMetadata {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, EnumAsInner)]
pub enum EntityDataValue { pub enum EntityDataValue {
Byte(u8), Byte(u8),
// varint
Int(i32), Int(i32),
Float(f32), Float(f32),
String(String), String(String),
@ -53,14 +56,14 @@ pub enum EntityDataValue {
OptionalComponent(Option<Component>), OptionalComponent(Option<Component>),
ItemStack(Slot), ItemStack(Slot),
Boolean(bool), Boolean(bool),
Rotations { x: f32, y: f32, z: f32 }, Rotations(Rotations),
BlockPos(BlockPos), BlockPos(BlockPos),
OptionalBlockPos(Option<BlockPos>), OptionalBlockPos(Option<BlockPos>),
Direction(Direction), Direction(Direction),
OptionalUuid(Option<Uuid>), OptionalUuid(Option<Uuid>),
// 0 for absent (implies air); otherwise, a block state ID as per the global palette // 0 for absent (implies air); otherwise, a block state ID as per the global palette
// this is a varint // this is a varint
OptionalBlockState(Option<i32>), OptionalBlockState(Option<BlockState>),
CompoundTag(azalea_nbt::Tag), CompoundTag(azalea_nbt::Tag),
Particle(Particle), Particle(Particle),
VillagerData(VillagerData), VillagerData(VillagerData),
@ -73,6 +76,13 @@ pub enum EntityDataValue {
PaintingVariant(azalea_registry::PaintingVariant), PaintingVariant(azalea_registry::PaintingVariant),
} }
#[derive(Clone, Debug, McBuf, Default)]
pub struct Rotations {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl McBufReadable for EntityDataValue { impl McBufReadable for EntityDataValue {
fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
let data_type = u32::var_read_from(buf)?; let data_type = u32::var_read_from(buf)?;
@ -85,21 +95,20 @@ impl McBufReadable for EntityDataValue {
5 => EntityDataValue::OptionalComponent(Option::<Component>::read_from(buf)?), 5 => EntityDataValue::OptionalComponent(Option::<Component>::read_from(buf)?),
6 => EntityDataValue::ItemStack(Slot::read_from(buf)?), 6 => EntityDataValue::ItemStack(Slot::read_from(buf)?),
7 => EntityDataValue::Boolean(bool::read_from(buf)?), 7 => EntityDataValue::Boolean(bool::read_from(buf)?),
8 => EntityDataValue::Rotations { 8 => EntityDataValue::Rotations(Rotations::read_from(buf)?),
x: f32::read_from(buf)?,
y: f32::read_from(buf)?,
z: f32::read_from(buf)?,
},
9 => EntityDataValue::BlockPos(BlockPos::read_from(buf)?), 9 => EntityDataValue::BlockPos(BlockPos::read_from(buf)?),
10 => EntityDataValue::OptionalBlockPos(Option::<BlockPos>::read_from(buf)?), 10 => EntityDataValue::OptionalBlockPos(Option::<BlockPos>::read_from(buf)?),
11 => EntityDataValue::Direction(Direction::read_from(buf)?), 11 => EntityDataValue::Direction(Direction::read_from(buf)?),
12 => EntityDataValue::OptionalUuid(Option::<Uuid>::read_from(buf)?), 12 => EntityDataValue::OptionalUuid(Option::<Uuid>::read_from(buf)?),
13 => EntityDataValue::OptionalBlockState({ 13 => EntityDataValue::OptionalBlockState({
let val = i32::var_read_from(buf)?; let val = u32::var_read_from(buf)?;
if val == 0 { if val == 0 {
None None
} else { } else {
Some(val) Some(BlockState::try_from(val - 1).unwrap_or_else(|_| {
warn!("Invalid block state ID {} in entity metadata", val - 1);
BlockState::Air
}))
} }
}), }),
14 => EntityDataValue::CompoundTag(azalea_nbt::Tag::read_from(buf)?), 14 => EntityDataValue::CompoundTag(azalea_nbt::Tag::read_from(buf)?),
@ -135,19 +144,20 @@ impl McBufWritable for EntityDataValue {
} }
} }
#[derive(Clone, Debug, Copy, McBuf)] #[derive(Clone, Debug, Copy, McBuf, Default)]
pub enum Pose { pub enum Pose {
#[default]
Standing = 0, Standing = 0,
FallFlying = 1, FallFlying,
Sleeping = 2, Sleeping,
Swimming = 3, Swimming,
SpinAttack = 4, SpinAttack,
Sneaking = 5, Sneaking,
LongJumping = 6, LongJumping,
Dying = 7, Dying,
} }
#[derive(Debug, Clone, McBuf)] #[derive(Debug, Clone, McBuf, Default)]
pub struct VillagerData { pub struct VillagerData {
#[var] #[var]
type_: u32, type_: u32,
@ -156,3 +166,32 @@ pub struct VillagerData {
#[var] #[var]
level: u32, level: u32,
} }
impl TryFrom<EntityMetadataItems> for Vec<EntityDataValue> {
type Error = String;
fn try_from(data: EntityMetadataItems) -> Result<Self, Self::Error> {
let mut data = data.0;
data.sort_by(|a, b| a.index.cmp(&b.index));
let mut prev_indexes = IntSet::default();
let len = data.len();
// check to make sure it's valid, in vanilla this is guaranteed to pass
// but it's possible there's mods that mess with it so we want to make
// sure it's good
for item in &data {
if prev_indexes.contains(&item.index) {
return Err(format!("Index {} is duplicated", item.index));
}
if item.index as usize > len {
return Err(format!("Index {} is too big", item.index));
}
prev_indexes.insert(item.index);
}
let data = data.into_iter().map(|d| d.value).collect();
Ok(data)
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,8 @@
mod data; mod data;
mod dimensions; mod dimensions;
pub mod metadata;
pub use self::metadata::EntityMetadata;
use crate::Dimension; use crate::Dimension;
use azalea_block::BlockState; use azalea_block::BlockState;
use azalea_core::{BlockPos, Vec3, AABB}; use azalea_core::{BlockPos, Vec3, AABB};
@ -142,6 +144,18 @@ impl<'d> EntityMut<'d> {
z: acceleration.z * (x_rot as f64) + acceleration.x * (y_rot as f64), z: acceleration.z * (x_rot as f64) + acceleration.x * (y_rot as f64),
} }
} }
/// Apply the given metadata items to the entity. Everything that isn't
/// included in items will be left unchanged. If an error occured, None
/// will be returned.
///
/// TODO: this should be changed to have a proper error.
pub fn apply_metadata(&mut self, items: &Vec<EntityDataItem>) -> Option<()> {
for item in items {
self.metadata.set_index(item.index, item.value.clone())?;
}
Some(())
}
} }
impl<'d> EntityMut<'d> { impl<'d> EntityMut<'d> {
@ -264,10 +278,13 @@ pub struct EntityData {
/// Whether the entity will try to jump every tick /// Whether the entity will try to jump every tick
/// (equivalent to the space key being held down in vanilla). /// (equivalent to the space key being held down in vanilla).
pub jumping: bool, pub jumping: bool,
/// Stores some extra data about the entity, including the entity type.
pub metadata: EntityMetadata,
} }
impl EntityData { impl EntityData {
pub fn new(uuid: Uuid, pos: Vec3) -> Self { pub fn new(uuid: Uuid, pos: Vec3, metadata: EntityMetadata) -> Self {
let dimensions = EntityDimensions { let dimensions = EntityDimensions {
width: 0.6, width: 0.6,
height: 1.8, height: 1.8,
@ -297,6 +314,8 @@ impl EntityData {
dimensions, dimensions,
jumping: false, jumping: false,
metadata,
} }
} }
@ -318,7 +337,14 @@ mod tests {
fn from_mut_entity_to_ref_entity() { fn from_mut_entity_to_ref_entity() {
let mut dim = Dimension::default(); let mut dim = Dimension::default();
let uuid = Uuid::from_u128(100); let uuid = Uuid::from_u128(100);
dim.add_entity(0, EntityData::new(uuid, Vec3::default())); dim.add_entity(
0,
EntityData::new(
uuid,
Vec3::default(),
EntityMetadata::Player(metadata::Player::default()),
),
);
let entity: EntityMut = dim.entity_mut(0).unwrap(); let entity: EntityMut = dim.entity_mut(0).unwrap();
let entity_ref: EntityRef = entity.into(); let entity_ref: EntityRef = entity.into();
assert_eq!(entity_ref.uuid, uuid); assert_eq!(entity_ref.uuid, uuid);

View file

@ -151,6 +151,8 @@ impl Default for EntityStorage {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::entity::{metadata, EntityMetadata};
use super::*; use super::*;
use azalea_core::Vec3; use azalea_core::Vec3;
@ -160,7 +162,14 @@ mod tests {
assert!(storage.get_by_id(0).is_none()); assert!(storage.get_by_id(0).is_none());
let uuid = Uuid::from_u128(100); let uuid = Uuid::from_u128(100);
storage.insert(0, EntityData::new(uuid, Vec3::default())); storage.insert(
0,
EntityData::new(
uuid,
Vec3::default(),
EntityMetadata::Player(metadata::Player::default()),
),
);
assert_eq!(storage.get_by_id(0).unwrap().uuid, uuid); assert_eq!(storage.get_by_id(0).unwrap().uuid, uuid);
storage.remove_by_id(0); storage.remove_by_id(0);

View file

@ -6,16 +6,16 @@
//! code, since everything from azalea_client is re-exported in azalea. //! code, since everything from azalea_client is re-exported in azalea.
//! //!
//! # Installation //! # Installation
//! //!
//! First, install Rust nightly with `rustup install nightly` and `rustup //! First, install Rust nightly with `rustup install nightly` and `rustup
//! default nightly`. //! default nightly`.
//! //!
//! Then, add one of the following lines to your Cargo.toml.\ //! Then, add one of the following lines to your Cargo.toml.\
//! Latest bleeding-edge version: //! Latest bleeding-edge version:
//! `azalea = { git="https://github.com/mat-1/Cargo.toml" }` //! `azalea = { git="https://github.com/mat-1/Cargo.toml" }`
//! Latest "stable" release: //! Latest "stable" release:
//! `azalea = "0.3"` //! `azalea = "0.3"`
//! //!
//! # Examples //! # Examples
//! //!
//! ```rust,no_run //! ```rust,no_run

19
codegen/genentities.py Normal file
View file

@ -0,0 +1,19 @@
import lib.code.version
import lib.code.entity
import lib.code.utils
import lib.download
import lib.extract
import sys
version_id = lib.code.version.get_version_id()
mappings = lib.download.get_mappings_for_version(version_id)
burger_data = lib.extract.get_burger_data_for_version(version_id)
burger_entity_data = burger_data[0]['entities']['entity']
lib.code.entity.generate_entity_metadata(burger_entity_data, mappings)
lib.code.utils.fmt()
print('Done!')

403
codegen/lib/code/entity.py Normal file
View file

@ -0,0 +1,403 @@
from lib.utils import to_camel_case, to_snake_case, get_dir_location, upper_first_letter
from lib.mappings import Mappings
from typing import Optional
import re
METADATA_RS_DIR = get_dir_location(
'../azalea-world/src/entity/metadata.rs')
def generate_entity_metadata(burger_entity_data: dict, mappings: Mappings):
# TODO: auto generate this and use it for generating the EntityDataValue enum
metadata_types = [
{'name': 'Byte', 'type': 'u8'},
{'name': 'Int', 'type': 'i32'},
{'name': 'Float', 'type': 'f32'},
{'name': 'String', 'type': 'String'},
{'name': 'Component', 'type': 'Component'},
{'name': 'OptionalComponent', 'type': 'Option<Component>'},
{'name': 'ItemStack', 'type': 'Slot'},
{'name': 'Boolean', 'type': 'bool'},
{'name': 'Rotations', 'type': 'Rotations'},
{'name': 'BlockPos', 'type': 'BlockPos'},
{'name': 'OptionalBlockPos', 'type': 'Option<BlockPos>'},
{'name': 'Direction', 'type': 'Direction'},
{'name': 'OptionalUuid', 'type': 'Option<Uuid>'},
{'name': 'OptionalBlockState', 'type': 'Option<BlockState>'},
{'name': 'CompoundTag', 'type': 'azalea_nbt::Tag'},
{'name': 'Particle', 'type': 'Particle'},
{'name': 'VillagerData', 'type': 'VillagerData'},
{'name': 'OptionalUnsignedInt', 'type': 'Option<u32>'},
{'name': 'Pose', 'type': 'Pose'},
{'name': 'CatVariant', 'type': 'azalea_registry::CatVariant'},
{'name': 'FrogVariant', 'type': 'azalea_registry::FrogVariant'},
{'name': 'GlobalPos', 'type': 'GlobalPos'},
{'name': 'PaintingVariant', 'type': 'azalea_registry::PaintingVariant'}
]
code = []
code.append('// This file is generated from codegen/lib/code/entity.py.')
code.append("// Don't change it manually!")
code.append('')
code.append('#![allow(clippy::clone_on_copy, clippy::derivable_impls)]')
code.append('use super::{EntityDataValue, Rotations, VillagerData, Pose};')
code.append('use azalea_block::BlockState;')
code.append('use azalea_chat::Component;')
code.append('use azalea_core::{BlockPos, Direction, Particle, Slot};')
code.append('use std::{collections::VecDeque, ops::Deref};')
code.append('use uuid::Uuid;')
code.append('')
entity_structs = []
parent_field_name = None
for entity_id in burger_entity_data:
entity_parents = get_entity_parents(entity_id, burger_entity_data)
entity_metadata = get_entity_metadata(entity_id, burger_entity_data)
entity_metadata_names = get_entity_metadata_names(
entity_id, burger_entity_data, mappings)
struct_name: str = upper_first_letter(
to_camel_case(entity_parents[0].replace('~', '')))
parent_struct_name: Optional[str] = upper_first_letter(to_camel_case(
entity_parents[1].replace('~', ''))) if (len(entity_parents) >= 2) else None
if parent_struct_name:
parent_field_name = to_snake_case(parent_struct_name)
if not entity_parents[0].startswith('~'):
entity_structs.append(struct_name)
reader_code = []
writer_code = []
set_index_code = []
field_names = []
code.append(f'#[derive(Debug, Clone)]')
code.append(f'pub struct {struct_name} {{')
if parent_struct_name:
assert parent_field_name
code.append(f'pub {parent_field_name}: {parent_struct_name},')
reader_code.append(
f'let {parent_field_name} = {parent_struct_name}::read(metadata)?;')
writer_code.append(
f'metadata.extend(self.{parent_field_name}.write());')
for index, name_or_bitfield in entity_metadata_names.items():
if isinstance(name_or_bitfield, str):
# normal field (can be any type)
name = name_or_bitfield
if name == 'type':
name = 'kind'
field_names.append(name)
type_id = next(filter(lambda i: i['index'] == index, entity_metadata))[
'type_id']
metadata_type_data = metadata_types[type_id]
rust_type = metadata_type_data['type']
type_name = metadata_type_data['name']
code.append(f'pub {name}: {rust_type},')
type_name_field = to_snake_case(type_name)
reader_code.append(
f'let {name} = metadata.pop_front()?.into_{type_name_field}().ok()?;')
writer_code.append(
f'metadata.push(EntityDataValue::{type_name}(self.{name}.clone()));')
# 1 => self.dancing = value.into_boolean().ok()?,
set_index_code.append(
f'{index} => self.{name} = value.into_{type_name_field}().ok()?,'
)
else:
# bitfield (sent as a byte, each bit in the byte is used as a boolean)
reader_code.append(
'let bitfield = metadata.pop_front()?.into_byte().ok()?;')
writer_code.append('let mut bitfield = 0u8;')
set_index_code.append(f'{index} => {{')
set_index_code.append(
f'let bitfield = value.into_byte().ok()?;')
for mask, name in name_or_bitfield.items():
if name == 'type':
name = 'kind'
field_names.append(name)
code.append(f'pub {name}: bool,')
reader_code.append(f'let {name} = bitfield & {mask} != 0;')
writer_code.append(
f'if self.{name} {{ bitfield &= {mask}; }}')
set_index_code.append(
f'self.{name} = bitfield & {mask} != 0;')
writer_code.append(
'metadata.push(EntityDataValue::Byte(bitfield));')
set_index_code.append('},')
code.append('}')
code.append('')
code.append(f'impl {struct_name} {{')
code.append(
'pub fn read(metadata: &mut VecDeque<EntityDataValue>) -> Option<Self> {')
code.extend(reader_code)
self_args = []
if parent_struct_name:
self_args.append(
f'{parent_field_name}')
self_args.extend(field_names)
code.append(f'Some(Self {{ {",".join(self_args)} }})')
code.append('}')
code.append('')
code.append('pub fn write(&self) -> Vec<EntityDataValue> {')
code.append('let mut metadata = Vec::new();')
code.extend(writer_code)
code.append('metadata')
code.append('}')
code.append('}')
code.append('')
# default
code.append(f'impl Default for {struct_name} {{')
code.append('fn default() -> Self {')
default_fields_code = []
if parent_struct_name:
assert parent_field_name
default_fields_code.append(
f'{parent_field_name}: Default::default()')
for index, name_or_bitfield in entity_metadata_names.items():
default = next(filter(lambda i: i['index'] == index, entity_metadata)).get(
'default', 'Default::default()')
if isinstance(name_or_bitfield, str):
type_id = next(filter(lambda i: i['index'] == index, entity_metadata))[
'type_id']
metadata_type_data = metadata_types[type_id]
type_name = metadata_type_data['name']
# TODO: burger doesn't get the default if it's a complex type
# like `Rotations`, so entities like armor stands will have the
# wrong default metadatas. This should be added to Burger.
if default is None:
# some types don't have Default implemented
if type_name == 'CompoundTag':
default = 'azalea_nbt::Tag::Compound(Default::default())'
elif type_name == 'CatVariant':
default = 'azalea_registry::CatVariant::Tabby'
elif type_name == 'PaintingVariant':
default = 'azalea_registry::PaintingVariant::Kebab'
elif type_name == 'FrogVariant':
default = 'azalea_registry::FrogVariant::Temperate'
else:
default = 'Default::default()'
else:
if type_name == 'Boolean':
default = 'true' if default else 'false'
elif type_name == 'String':
string_escaped = default.replace('"', '\\"')
default = f'"{string_escaped}".to_string()'
elif type_name == 'BlockPos':
default = f'BlockPos::new{default}'
elif type_name == 'OptionalBlockPos': # Option<BlockPos>
default = f'Some(BlockPos::new{default})' if default != 'Empty' else 'None'
elif type_name == 'OptionalUuid':
default = f'Some(uuid::uuid!({default}))' if default != 'Empty' else 'None'
elif type_name == 'OptionalUnsignedInt':
default = f'Some({default})' if default != 'Empty' else 'None'
elif type_name == 'ItemStack':
default = f'Slot::Present({default})' if default != 'Empty' else 'Slot::Empty'
elif type_name == 'OptionalBlockState':
default = f'Some({default})' if default != 'Empty' else 'None'
elif type_name == 'OptionalComponent':
default = f'Some({default})' if default != 'Empty' else 'None'
elif type_name == 'CompoundTag':
default = f'azalea_nbt::Tag::Compound({default})' if default != 'Empty' else 'azalea_nbt::Tag::Compound(Default::default())'
print(default, name_or_bitfield, type_name)
name = name_or_bitfield
if name == 'type':
name = 'kind'
default_fields_code.append(f'{name}: {default}')
else:
# if it's a bitfield, we'll have to extract the default for
# each bool from each bit in the default
for mask, name in name_or_bitfield.items():
if name == 'type':
name = 'kind'
mask = int(mask, 0)
field_names.append(name)
bit_default = 'true' if (default & mask != 0) else 'false'
default_fields_code.append(f'{name}: {bit_default}')
# Self { abstract_creature: Default::default(), dancing: Default::default(), can_duplicate: Default::default() }
code.append(f'Self {{ {", ".join(default_fields_code)} }}')
code.append('}')
code.append('}')
code.append('')
# impl Allay {
# pub fn set_index(&mut self, index: u8, value: EntityDataValue) -> Option<()> {
# match index {
# 0..=0 => self.abstract_creature.set_index(index, value),
# 1 => self.dancing = value.into_boolean().ok()?,
# 2 => self.can_duplicate = value.into_boolean().ok()?,
# _ => {}
# }
# Some(())
# }
# }
code.append(f'impl {struct_name} {{')
code.append(
'pub fn set_index(&mut self, index: u8, value: EntityDataValue) -> Option<()> {')
if len(entity_metadata_names) > 0:
code.append('match index {')
# get the smallest index for this entity
smallest_index = min(entity_metadata_names.keys())
if parent_struct_name:
code.append(
f'0..={smallest_index-1} => self.{parent_field_name}.set_index(index, value)?,')
code.extend(set_index_code)
code.append('_ => {}')
code.append('}')
code.append('Some(())')
elif parent_struct_name:
code.append(f'self.{parent_field_name}.set_index(index, value)')
else:
code.append('Some(())')
code.append('}')
code.append('}')
# deref
if parent_struct_name:
code.append(f'impl Deref for {struct_name} {{')
code.append(f'type Target = {parent_struct_name};')
code.append(
f'fn deref(&self) -> &Self::Target {{ &self.{parent_field_name} }}')
code.append('}')
code.append('')
# make the EntityMetadata enum from entity_structs
code.append(f'#[derive(Debug, Clone)]')
code.append('pub enum EntityMetadata {')
for struct_name in entity_structs:
code.append(f'{struct_name}({struct_name}),')
code.append('}')
code.append('')
# impl From<azalea_registry::EntityType> for EntityMetadata {
code.append('impl From<azalea_registry::EntityType> for EntityMetadata {')
code.append('fn from(value: azalea_registry::EntityType) -> Self {')
code.append('match value {')
# azalea_registry::EntityType::Allay => EntityMetadata::Allay(Allay::default()),
for struct_name in entity_structs:
code.append(
f'azalea_registry::EntityType::{struct_name} => EntityMetadata::{struct_name}({struct_name}::default()),')
code.append('}')
code.append('}')
code.append('}')
code.append('')
# impl EntityMetadata
# pub fn set_index(&mut self, index: u8, value: EntityDataValue)
code.append('impl EntityMetadata {')
code.append(
'pub fn set_index(&mut self, index: u8, value: EntityDataValue) -> Option<()> {')
code.append('match self {')
# EntityMetadata::Allay(allay) => allay.set_index(index, value),
for struct_name in entity_structs:
code.append(
f'EntityMetadata::{struct_name}(entity) => entity.set_index(index, value),')
code.append('}')
code.append('}')
code.append('}')
code.append('')
with open(METADATA_RS_DIR, 'w') as f:
f.write('\n'.join(code))
def get_entity_parents(entity_id: str, burger_entity_data: dict):
parents = []
while entity_id:
parents.append(entity_id)
entity_id = get_entity_parent(entity_id, burger_entity_data)
return parents
def get_entity_parent(entity_id: str, burger_entity_data: dict):
entity_metadata = burger_entity_data[entity_id]['metadata']
first_metadata = entity_metadata[0]
return first_metadata.get('entity')
def get_entity_metadata(entity_id: str, burger_entity_data: dict):
entity_metadata = burger_entity_data[entity_id]['metadata']
entity_useful_metadata = []
for metadata_item in entity_metadata:
if 'data' in metadata_item:
for metadata_attribute in metadata_item['data']:
entity_useful_metadata.append({
'index': metadata_attribute['index'],
'type_id': metadata_attribute['serializer_id'],
'default': metadata_attribute.get('default')
})
return entity_useful_metadata
def get_entity_metadata_names(entity_id: str, burger_entity_data: dict, mappings: Mappings):
entity_metadata = burger_entity_data[entity_id]['metadata']
mapped_metadata_names = {}
for metadata_item in entity_metadata:
if 'data' in metadata_item:
obfuscated_class = metadata_item['class']
mojang_class = mappings.get_class(obfuscated_class)
first_byte_index = None
for metadata_attribute in metadata_item['data']:
obfuscated_field = metadata_attribute['field']
mojang_field = mappings.get_field(
obfuscated_class, obfuscated_field)
pretty_mojang_name = prettify_mojang_field(mojang_field)
mapped_metadata_names[metadata_attribute['index']
] = pretty_mojang_name
if metadata_attribute['serializer'] == 'Byte' and first_byte_index is None:
first_byte_index = metadata_attribute['index']
if metadata_item['bitfields'] and first_byte_index is not None:
clean_bitfield = {}
for bitfield_item in metadata_item['bitfields']:
bitfield_item_obfuscated_class = bitfield_item.get(
'class', obfuscated_class)
mojang_bitfield_item_name = mappings.get_method(
bitfield_item_obfuscated_class, bitfield_item['method'], '')
bitfield_item_name = prettify_mojang_method(
mojang_bitfield_item_name)
bitfield_hex_mask = hex(bitfield_item['mask'])
clean_bitfield[bitfield_hex_mask] = bitfield_item_name
mapped_metadata_names[first_byte_index] = clean_bitfield
return mapped_metadata_names
def prettify_mojang_field(mojang_field: str):
# mojang names are like "DATA_AIR_SUPPLY" and that's ugly
better_name = mojang_field
if better_name.startswith('DATA_'):
better_name = better_name[5:]
# remove the weird "Id" from the end of names
if better_name.endswith('_ID'):
better_name = better_name[:-3]
# remove the weird "id" from the front of names
if better_name.startswith('ID_'):
better_name = better_name[3:]
return better_name.lower()
def prettify_mojang_method(mojang_method: str):
better_name = mojang_method
if better_name.endswith('()'):
better_name = better_name[:-2]
if re.match(r'is[A-Z]', better_name):
better_name = better_name[2:]
return to_snake_case(better_name)

View file

@ -1,7 +1,7 @@
from typing import Optional
from lib.code.utils import burger_type_to_rust_type, write_packet_file
from lib.utils import padded_hex, to_snake_case, to_camel_case, get_dir_location from lib.utils import padded_hex, to_snake_case, to_camel_case, get_dir_location
from lib.code.utils import burger_type_to_rust_type, write_packet_file
from lib.mappings import Mappings from lib.mappings import Mappings
from typing import Optional
import os import os
import re import re

View file

@ -1,6 +1,6 @@
from typing import Optional
from lib.utils import to_snake_case, upper_first_letter, get_dir_location, to_camel_case from lib.utils import to_snake_case, upper_first_letter, get_dir_location, to_camel_case
from ..mappings import Mappings from ..mappings import Mappings
from typing import Optional
import re import re
REGISTRIES_DIR = get_dir_location('../azalea-registry/src/lib.rs') REGISTRIES_DIR = get_dir_location('../azalea-registry/src/lib.rs')

View file

@ -71,7 +71,7 @@ class Mappings:
return self.classes[obfuscated_class_name] return self.classes[obfuscated_class_name]
def get_method(self, obfuscated_class_name, obfuscated_method_name, obfuscated_signature): def get_method(self, obfuscated_class_name, obfuscated_method_name, obfuscated_signature):
print(obfuscated_class_name, self.methods[obfuscated_class_name]) # print(obfuscated_class_name, self.methods[obfuscated_class_name])
return self.methods[obfuscated_class_name][f'{obfuscated_method_name}({obfuscated_signature})'] return self.methods[obfuscated_class_name][f'{obfuscated_method_name}({obfuscated_signature})']
def get_field_type(self, obfuscated_class_name, obfuscated_field_name) -> str: def get_field_type(self, obfuscated_class_name, obfuscated_field_name) -> str: