diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..1b4989055 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1216,21 +1216,22 @@ impl Game<'_> { host: &LanHost, stack: &Option, ) -> Option { - use horizon_protocol::item::{Component, component}; let s = stack.as_ref()?; let name = host .hub .item_name(s.item) .unwrap_or_else(|| "minecraft:air".into()); let mut out = ItemStack::new(&name, s.count.max(1) as u32); - out.damage = s.damage().max(0) as u32; - if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) { - for (id, level) in list { - if let Some(e) = host.hub.enchantment_name(*id) { - out.enchant(&e, *level as u32); - } - } - } + // The same components the encoder wrote, so a creative slot keeps what + // the client held instead of just damage and enchantments. + horizon_client::item_sync::apply( + s, + &mut out, + |id| host.hub.enchantment_name(id).map(|n| n.into()), + |id| host.hub.trim_name("minecraft:trim_material", id), + |id| host.hub.trim_name("minecraft:trim_pattern", id), + ); + out.tidy(); Some(out) } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a3ab8d281..bbd688eef 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -761,10 +761,14 @@ impl Game<'_> { fn to_network(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(self.item_id(&s.item), s.count as i32); - if s.damage > 0 { - stack.added.push(( - horizon_protocol::item::component::DAMAGE, - horizon_protocol::item::Component::Int(s.damage as i32), + // The components the client models, with the synced registries' ids: + // without them the server's echo hands back a bare item. + if let Some(r) = self.remote.as_ref() { + stack.added.extend(horizon_client::item_sync::encode( + s, + |name| r.registries.id("minecraft:enchantment", name), + |name| r.registries.id("minecraft:trim_material", name), + |name| r.registries.id("minecraft:trim_pattern", name), )); } Some(stack) diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index c07e2f352..00fd0f074 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -291,7 +291,7 @@ fn filterable_text(t: &Tag) -> Option { None => read_text(t), } } -fn read_text(t: &Tag) -> Option { +pub(crate) fn read_text(t: &Tag) -> Option { match t { Tag::String(s) => Some(s.to_string_lossy()), // A component's root `text` may be empty with the visible words in diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs new file mode 100644 index 000000000..4e48498ac --- /dev/null +++ b/crates/horizon-client/src/item_sync.rs @@ -0,0 +1,170 @@ +//! The data components a stack keeps when it crosses the wire, and how the +//! other side reads them back. A creative slot's packet carries a component +//! patch, and before this the encoder wrote damage alone, so everything else +//! (enchantments, a custom name, trim, repair cost) was gone once the server +//! echoed the inventory back. +use crate::item_data::{Levels, StackData}; +use crate::items::ItemStack; +use horizon_protocol::item::{Component, Stack, component}; +use horizon_world::nbt::Tag; +use std::sync::Arc; + +/// `Slot.STREAM_CODEC`'s patch for the components Horizon models, with the +/// registries' ids for enchantments and trim. A name the registry does not +/// know is left out: id 0 is a different entry, not a missing one. +pub fn encode( + stack: &ItemStack, + enchantment: impl Fn(&str) -> Option, + trim_material: impl Fn(&str) -> Option, + trim_pattern: impl Fn(&str) -> Option, +) -> Vec<(i32, Component)> { + let mut out = Vec::new(); + if stack.damage > 0 { + out.push((component::DAMAGE, Component::Int(stack.damage as i32))); + } + let Some(d) = stack.data() else { + return out; + }; + let levels = |levels: &Levels| -> Option { + let list: Vec<(i32, i32)> = levels + .iter() + .filter_map(|(name, level)| Some((enchantment(name)?, *level as i32))) + .collect(); + (!list.is_empty()).then_some(Component::Enchantments(list)) + }; + if let Some(c) = levels(&d.enchantments) { + out.push((component::ENCHANTMENTS, c)); + } + if let Some(c) = levels(&d.stored_enchantments) { + out.push((component::STORED_ENCHANTMENTS, c)); + } + if d.repair_cost > 0 { + out.push((component::REPAIR_COST, Component::Int(d.repair_cost as i32))); + } + if let Some(name) = &d.custom_name { + // A plain string is a valid text component, and `decode_components` + // reads it back as one. + out.push(( + component::CUSTOM_NAME, + Component::Text(Tag::String(name.as_str().into())), + )); + } + if let Some((material, pattern)) = &d.trim + && let (Some(material), Some(pattern)) = (trim_material(material), trim_pattern(pattern)) + { + out.push((component::TRIM, Component::Trim { material, pattern })); + } + out +} + +/// The same patch read back into `out`, the fields `item_data::decode_components` +/// fills from the equivalent `components` compound. +pub fn apply( + stack: &Stack, + out: &mut ItemStack, + enchantment: impl Fn(i32) -> Option>, + trim_material: impl Fn(i32) -> Option>, + trim_pattern: impl Fn(i32) -> Option>, +) { + out.damage = stack.damage().max(0) as u32; + let read_levels = |kind: i32, into: &mut Levels| { + if let Some(Component::Enchantments(list)) = stack.component(kind) { + for (id, level) in list { + if let Some(name) = enchantment(*id) { + into.push((name, (*level).max(0) as u32)); + } + } + } + }; + let data: &mut StackData = out.data_mut(); + read_levels(component::ENCHANTMENTS, &mut data.enchantments); + read_levels( + component::STORED_ENCHANTMENTS, + &mut data.stored_enchantments, + ); + if let Some(Component::Int(v)) = stack.component(component::REPAIR_COST) { + data.repair_cost = (*v).max(0) as u32; + } + if let Some(Component::Text(t)) = stack.component(component::CUSTOM_NAME) { + data.custom_name = crate::item_data::read_text(t); + } + if let Some(Component::Trim { material, pattern }) = stack.component(component::TRIM) + && let (Some(material), Some(pattern)) = (trim_material(*material), trim_pattern(*pattern)) + { + data.trim = Some((material, pattern)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn named(name: &str) -> Option { + Some(match name { + "minecraft:sharpness" => 3, + "minecraft:gold" => 7, + "minecraft:sentry" => 2, + _ => return None, + }) + } + fn name_of(id: i32) -> Option> { + Some(Arc::from(match id { + 3 => "minecraft:sharpness", + 7 => "minecraft:gold", + 2 => "minecraft:sentry", + _ => return None, + })) + } + + fn stack_with_data() -> ItemStack { + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + stack.damage = 5; + let d = stack.data_mut(); + d.enchantments.push((Arc::from("minecraft:sharpness"), 4)); + d.stored_enchantments + .push((Arc::from("minecraft:sharpness"), 2)); + d.repair_cost = 9; + d.custom_name = Some("Keeper".to_owned()); + d.trim = Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry"))); + stack + } + + /// Every modelled component survives the packet, so the server's echo does + /// not hand back a bare item. + #[test] + fn a_stack_keeps_its_components_across_the_wire() { + let stack = stack_with_data(); + let mut packet = Stack::new(1, 1); + packet.added = encode(&stack, named, named, named); + + let mut back = ItemStack::new("minecraft:diamond_sword", 1); + apply(&packet, &mut back, name_of, name_of, name_of); + back.tidy(); + + assert_eq!(back.damage, 5); + let d = back.data().expect("components"); + assert_eq!(d.enchantments, vec![(Arc::from("minecraft:sharpness"), 4)]); + assert_eq!( + d.stored_enchantments, + vec![(Arc::from("minecraft:sharpness"), 2)] + ); + assert_eq!(d.repair_cost, 9); + assert_eq!(d.custom_name.as_deref(), Some("Keeper")); + assert_eq!( + d.trim, + Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry"))) + ); + } + + /// A name the registry does not know is a missing id, not id 0, which would + /// name the registry's first entry instead. + #[test] + fn an_unknown_enchantment_is_left_out_rather_than_sent_as_zero() { + let mut stack = ItemStack::new("minecraft:book", 1); + stack + .data_mut() + .enchantments + .push((Arc::from("mod:unknown"), 1)); + assert!(encode(&stack, named, named, named).is_empty()); + } +} diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index dd0a32f22..2667b1fed 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2293,6 +2293,14 @@ impl Hub { .name("minecraft:enchantment", id) .map(str::to_owned) } + /// An entry of a synced registry by id, for the components a packet + /// carries by id (`minecraft:trim_material`, `minecraft:trim_pattern`). + pub fn trim_name(&self, registry: &str, id: i32) -> Option> { + self.sync + .dynamic + .name(registry, id) + .map(std::sync::Arc::from) + } /// ServerLevel.removePlayerImmediately, then addRespawnedPlayer: the other players /// lose the dead player's entity (ServerEntity.removePairing) and are sent the diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ae95e1bdb..ad05153eb 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -96,6 +96,7 @@ pub mod inv_sort; pub mod inventory_effects; pub mod item_data; pub mod item_render; +pub mod item_sync; pub mod item_tooltip; pub mod items; pub mod java_text; diff --git a/crates/horizon-protocol/src/registry.rs b/crates/horizon-protocol/src/registry.rs index f97401670..400c21a37 100644 --- a/crates/horizon-protocol/src/registry.rs +++ b/crates/horizon-protocol/src/registry.rs @@ -102,6 +102,12 @@ impl Dynamic { .get(i) .map(|(n, _)| n.as_str()) } + /// The id of an entry by name, the reverse of `name`. A registry has one + /// entry per id, so the first match is the only one. + pub fn id(&self, registry: &str, name: &str) -> Option { + let list = self.registries.get(registry)?; + list.iter().position(|(n, _)| n == name).map(|i| i as i32) + } pub fn data(&self, registry: &str, id: i32) -> Option<&Tag> { let i = usize::try_from(id).ok()?; self.registries.get(registry)?.get(i)?.1.as_ref()