Merchant offers: preserve required potion components

Co-Authored-By: OpenAI Codex GPT-6.1 Sol <noreply@openai.com>
This commit is contained in:
rdbtCVS
2026-10-26 10:38:26 +00:00
parent c0171fa6bc
commit d25d0f025b
6 changed files with 207 additions and 22 deletions
@@ -133,7 +133,46 @@ impl World<'_> {
maps: None,
};
let random = self.sequences.get(&sequence, self.seed);
offers.extend(self.trades.offers_from_set(&ctx, set, random));
let generated = self.trades.offers_from_set(&ctx, set, random);
// Exercise the server/client offer boundary as well as the in-frame
// trade generation compared with vanilla below (notably water costs).
use horizon_protocol::{
buf::{Codec, Reader, Writer},
item::Stack,
packets::play::{NetOffer, Offers},
};
let cost = |stack: &ItemStack| {
horizon_client::lan::guest::stack_to_network(
|_| 1,
|registry, name| {
(registry == "minecraft:potion" && name == "minecraft:water").then_some(0)
},
&Some(stack.clone()),
)
.unwrap()
.into()
};
let wire: Vec<_> = generated
.iter()
.map(|offer| NetOffer {
cost_a: cost(&offer.base_cost_a.stack),
cost_b: offer.cost_b.as_ref().map(|c| cost(&c.stack)),
result: Stack::new(2, 1),
out_of_stock: false,
uses: 0,
max_uses: 2,
xp: 0,
special_price: 0,
price_multiplier: 0.0,
demand: 0,
})
.collect();
let mut w = Writer::new();
Offers::write(&wire, &mut w);
let mut r = Reader::new(&w.data);
assert_eq!(Offers::read(&mut r).unwrap(), wire);
assert_eq!(r.remaining(), 0);
offers.extend(generated);
}
fn merchant(&mut self, spec: &str, origin: [f64; 3]) -> Merchant {
let mut offers = Vec::new();
@@ -144,15 +144,16 @@ impl Game<'_> {
.offers
.iter()
.filter_map(|o| {
let cost =
|st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| play::NetCost {
item: hub.item_id(&st.item),
count: st.count as i32,
};
let cost = |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| {
hub.stack(&Some(st.clone())).map(play::NetCost::from)
};
Some(play::NetOffer {
cost_a: cost(&o.base_cost_a.stack, &mut host.hub),
cost_a: cost(&o.base_cost_a.stack, &mut host.hub)?,
result: host.hub.stack(&Some(o.result.clone()))?,
cost_b: o.cost_b.as_ref().map(|b| cost(&b.stack, &mut host.hub)),
cost_b: match &o.cost_b {
Some(b) => Some(cost(&b.stack, &mut host.hub)?),
None => None,
},
out_of_stock: o.out_of_stock(),
uses: o.uses,
max_uses: o.max_uses,
+8 -4
View File
@@ -4796,16 +4796,20 @@ impl Game<'_> {
if self.open_menu_name(p.container) != "minecraft:merchant" {
return;
}
let cost = |g: &Self, c: &play::NetCost| horizon_client::merchant::ItemCost {
stack: ItemStack::new(&g.item_name(c.item), c.count.max(0) as u32),
let cost = |g: &Self, c: &play::NetCost| {
g.to_stack(&Some(c.clone().into()))
.map(|stack| horizon_client::merchant::ItemCost { stack })
};
let offers: Vec<_> = p
.offers
.iter()
.filter_map(|o| {
let mut offer = horizon_client::merchant::MerchantOffer {
base_cost_a: cost(self, &o.cost_a),
cost_b: o.cost_b.as_ref().map(|b| cost(self, b)),
base_cost_a: cost(self, &o.cost_a)?,
cost_b: match &o.cost_b {
Some(b) => Some(cost(self, b)?),
None => None,
},
result: self.to_stack(&Some(o.result.clone()))?,
uses: o.uses,
max_uses: o.max_uses,
+77
View File
@@ -238,6 +238,83 @@ mod tests {
use super::*;
use horizon_protocol::registry::Ids;
#[test]
fn merchant_water_cost_survives_the_offer_packet() {
use horizon_protocol::{
buf::{Codec, Reader, Writer},
packets::play::{NetOffer, Offers},
};
let mut components = vec![String::new(); component::POTION_CONTENTS as usize + 1];
components[component::POTION_CONTENTS as usize] = "minecraft:potion_contents".into();
let builtin = Builtin {
registries: [
(
"minecraft:item".into(),
Ids::from_names(vec!["minecraft:potion".into(), "minecraft:emerald".into()]),
),
(
"minecraft:potion".into(),
Ids::from_names(vec!["minecraft:water".into()]),
),
(
"minecraft:data_component_type".into(),
Ids::from_names(components),
),
]
.into(),
};
let dynamic = Dynamic::default();
let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water");
let wire = crate::lan::guest::stack_to_network(
|name| builtin.get("minecraft:item").unwrap().id(name).unwrap(),
|registry, name| builtin.get(registry)?.id(name),
&Some(water.clone()),
)
.unwrap();
let offers = vec![NetOffer {
cost_a: wire.into(),
result: Stack::new(1, 1),
cost_b: Some(Stack::new(1, 2).into()),
out_of_stock: false,
uses: 0,
max_uses: 2,
xp: 0,
special_price: 0,
price_multiplier: 0.05,
demand: 0,
}];
let mut w = Writer::new();
Offers::write(&offers, &mut w);
let mut r = Reader::new(&w.data);
let decoded = Offers::read(&mut r).unwrap();
assert_eq!(r.remaining(), 0);
let cost = crate::merchant::ItemCost {
stack: from_network(&decoded[0].cost_a.clone().into(), &builtin, &dynamic),
};
assert_eq!(cost.stack, water);
assert_eq!(cost.stack.potion(), Some("minecraft:water"));
let authoritative = crate::merchant::ItemCost {
stack: water.clone(),
};
for payment in [
water,
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness"),
ItemStack::new("minecraft:potion", 1),
] {
assert_eq!(cost.test(&payment), authoritative.test(&payment));
}
assert!(cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water")));
assert!(!cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness")));
let emerald = crate::merchant::ItemCost {
stack: from_network(
&decoded[0].cost_b.clone().unwrap().into(),
&builtin,
&dynamic,
),
};
assert!(emerald.test(&ItemStack::new("minecraft:emerald", 2)));
}
/// What a creative client sends (`stack_to_network`) comes back whole on
/// the server: damage, both enchantment lists, repair cost, name, trim.
#[test]
+2 -2
View File
@@ -163,7 +163,7 @@ pub struct Profile {
pub properties: Vec<(String, String, Option<String>)>,
}
impl Component {
fn read(kind: i32, r: &mut Reader) -> Result<Self> {
pub(crate) fn read(kind: i32, r: &mut Reader) -> Result<Self> {
use component::*;
Ok(match kind {
MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID
@@ -337,7 +337,7 @@ impl Component {
}
})
}
fn write(&self, kind: i32, w: &mut Writer) {
pub(crate) fn write(&self, kind: i32, w: &mut Writer) {
match self {
Self::Raw(bytes) => w.bytes(bytes),
Self::Trim { material, pattern } => {
+72 -8
View File
@@ -8,7 +8,7 @@ use crate::{
},
chunk::{ChunkData, LightData},
entity_data::{EntityData, Particle, Value},
item::{Hashed, HashedSlot, Slot, Stack},
item::{Component, Hashed, HashedSlot, Slot, Stack},
packet, packet_enum,
packets::{
Empty,
@@ -88,11 +88,31 @@ packet!(ContainerSetContent {
carried: Option<Stack> => Slot,
});
/// ItemCost.STREAM_CODEC: item, count, then the exact component predicate
/// (Horizon sends and reads it as a component patch without removals).
/// (a list of typed component values, with no patch removal count).
#[derive(Clone, Debug, PartialEq)]
pub struct NetCost {
pub item: i32,
pub count: i32,
pub components: Vec<(i32, Component)>,
}
impl From<Stack> for NetCost {
fn from(stack: Stack) -> Self {
Self {
item: stack.item,
count: stack.count,
components: stack.added,
}
}
}
impl From<NetCost> for Stack {
fn from(cost: NetCost) -> Self {
Self {
item: cost.item,
count: cost.count,
added: cost.components,
removed: Vec::new(),
}
}
}
/// MerchantOffer.STREAM_CODEC.
#[derive(Clone, Debug, PartialEq)]
@@ -114,10 +134,17 @@ impl Codec<Vec<NetOffer>> for Offers {
fn cost(r: &mut Reader) -> Result<NetCost> {
let item = r.varint()?;
let count = r.varint()?;
if r.varint()? != 0 {
return Err(Error::new("item cost components are not supported"));
let n = r.count(r.remaining())?;
let mut components = Vec::with_capacity(n.min(64));
for _ in 0..n {
let kind = r.varint()?;
components.push((kind, Component::read(kind, r)?));
}
Ok(NetCost { item, count })
Ok(NetCost {
item,
count,
components,
})
}
let n = r.count(r.remaining())?;
let mut out = Vec::with_capacity(n.min(64));
@@ -144,7 +171,11 @@ impl Codec<Vec<NetOffer>> for Offers {
fn cost(c: &NetCost, w: &mut Writer) {
w.varint(c.item);
w.varint(c.count);
w.varint(0);
w.varint(c.components.len() as i32);
for (kind, value) in &c.components {
w.varint(*kind);
value.write(*kind, w);
}
}
w.varint(v.len() as i32);
for o in v {
@@ -2300,6 +2331,39 @@ mod tests {
use super::*;
use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal};
#[test]
fn merchant_cost_predicate_is_a_typed_list_without_patch_counts() {
// ItemCost.STREAM_CODEC: item=7, count=1, one typed component,
// potion_contents=53, potion present (water=0), no color/effects/name.
// Result: count=1, item=8, empty component patch. Secondary cost:
// item=9, count=2, empty predicate, followed by the offer fields.
let mut bytes = vec![1, 7, 1, 1, 53, 1, 0, 0, 0, 0, 1, 8, 0, 0, 1, 9, 2, 0, 0];
bytes.extend_from_slice(&[0; 4]); // uses
bytes.extend_from_slice(&2i32.to_be_bytes()); // max uses
bytes.extend_from_slice(&[0; 16]); // xp, special price, multiplier, demand
let mut r = Reader::new(&bytes);
let offers = Offers::read(&mut r).unwrap();
assert_eq!(r.remaining(), 0);
assert_eq!(
offers[0].cost_a.components,
vec![(
53,
Component::Potion {
potion: Some(0),
color: None,
rest: Vec::new()
}
)]
);
assert!(offers[0].cost_b.as_ref().unwrap().components.is_empty());
let mut w = Writer::new();
Offers::write(&offers, &mut w);
assert_eq!(w.data, bytes);
for len in 0..bytes.len() {
assert!(Offers::read(&mut Reader::new(&bytes[..len])).is_err());
}
}
#[test]
fn serverbound_abilities_carry_only_flying() {
// ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying.
@@ -2576,9 +2640,9 @@ mod tests {
Clientbound::MerchantOffers(MerchantOffers {
container: 3,
offers: vec![NetOffer {
cost_a: NetCost { item: 5, count: 24 },
cost_a: Stack::new(5, 24).into(),
result: Stack::new(7, 1),
cost_b: Some(NetCost { item: 9, count: 1 }),
cost_b: Some(Stack::new(9, 1).into()),
out_of_stock: false,
uses: 2,
max_uses: 16,