From a3dd34a8f3e6d7f77c26d940051d220d995e9cfc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:25:27 +0200 Subject: [PATCH] Trading parity harness: offers, prices, restocks, the merchant menu and NBT against vanilla VanillaTradingOracle runs villagers, wandering traders and MerchantMenu on a real flat server; trading_fixture runs horizon_client::merchant and a new merchant kind of the menu engine (MerchantContainer, MerchantResultSlot, tryMoveItems, quick move) over a merchant::Session. Generation now covers random dyes, random potions, stew effects, exploration maps (a MapMaker hook), sum/binomial providers and the trade's max uses / xp / discount providers; getRecipeFor honours the selection hint as vanilla, Offers leave defaults out. Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 1 + .../horizon-client/examples/menu_fixture.rs | 1 + .../examples/place_recipe_fixture.rs | 1 + .../examples/trading_fixture.rs | 548 ++++++++++++++ crates/horizon-client/src/crafting.rs | 2 +- crates/horizon-client/src/entity_nbt.rs | 105 ++- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/trading.rs | 2 + crates/horizon-client/src/item_data.rs | 10 +- crates/horizon-client/src/menu.rs | 242 +++++- crates/horizon-client/src/menu/place.rs | 2 +- crates/horizon-client/src/merchant.rs | 713 +++++++++++++----- crates/horizon-client/src/random_sequences.rs | 8 + crates/horizon-client/src/stations.rs | 2 + .../parity/VanillaTradingOracle.java | 624 +++++++++++++++ tools/test_trading_parity.py | 245 ++++++ 16 files changed, 2282 insertions(+), 225 deletions(-) create mode 100644 crates/horizon-client/examples/trading_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java create mode 100644 tools/test_trading_parity.py diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 7de043b11..584425ced 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -87,6 +87,7 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + trade: None, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 0d1d496ed..2434a5b5d 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -41,6 +41,7 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + trade: None, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index e919c1e05..45d763980 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -43,6 +43,7 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + trade: None, }; let mut out = String::new(); for (line, order) in cases.lines().zip(orders.lines()) { diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs new file mode 100644 index 000000000..a560b1c06 --- /dev/null +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -0,0 +1,548 @@ +//! Trading for tools/test_trading_parity.py: runs each case of INPUT as +//! VanillaTradingOracle does (offer generation, special prices, restocks, +//! the merchant menu, NBT) and prints the same lines. +//! +//! usage: trading_fixture RESOURCES INPUT VANILLA_OUTPUT OUTPUT +use horizon_client::{ + enchant::Enchantments, + entity_nbt, + gossip::{GossipType, Gossips}, + items::{ItemStack, Items}, + menu::{Env, Input, Kind, Menu}, + merchant::{self, Event, MerchantOffer, Session, TradeContext, TradeEnv, Trader, Trades}, + random_sequences::RandomSequences, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::nbt::Tag; +use std::{collections::HashMap, fmt::Write as _, fs, path::Path}; + +const PLAYER: [i32; 4] = [0, 0x1234, 0, 0x5678]; + +/// Canonical NBT text, as VanillaTradingOracle prints it. +fn canon(t: &Tag, out: &mut String) { + match t { + Tag::Compound(c) => { + out.push('{'); + let mut keys: Vec = c.keys().map(|k| k.to_string_lossy()).collect(); + keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16())); + for (i, k) in keys.iter().enumerate() { + if i > 0 { + out.push(','); + } + quote(k, out); + out.push(':'); + canon(t.get(k).expect("key"), out); + } + out.push('}'); + } + Tag::List(l) => { + out.push('['); + for (i, v) in l.iter().enumerate() { + if i > 0 { + out.push(','); + } + canon(v, out); + } + out.push(']'); + } + Tag::String(s) => quote(&s.to_string_lossy(), out), + Tag::Byte(v) => write!(out, "{v}b").unwrap(), + Tag::Short(v) => write!(out, "{v}s").unwrap(), + Tag::Int(v) => write!(out, "{v}").unwrap(), + Tag::Long(v) => write!(out, "{v}L").unwrap(), + Tag::Float(v) => write!(out, "f:{v:x}").unwrap(), + Tag::Double(v) => write!(out, "d:{v:x}").unwrap(), + Tag::ByteArray(v) => { + out.push_str("[B;"); + let s: Vec = v.iter().map(|b| (*b as i8).to_string()).collect(); + out.push_str(&s.join(",")); + out.push(']'); + } + Tag::IntArray(v) => { + out.push_str("[I;"); + let s: Vec = v.iter().map(i32::to_string).collect(); + out.push_str(&s.join(",")); + out.push(']'); + } + Tag::LongArray(v) => { + out.push_str("[L;"); + let s: Vec = v.iter().map(i64::to_string).collect(); + out.push_str(&s.join(",")); + out.push(']'); + } + Tag::End => out.push_str("?End"), + } +} +fn quote(s: &str, out: &mut String) { + out.push('"'); + for c in s.chars() { + if c == '"' || c == '\\' { + out.push('\\'); + } + out.push(c); + } + out.push('"'); +} +fn canon_str(t: &Tag) -> String { + let mut s = String::new(); + canon(t, &mut s); + s +} +fn stack(s: Option<&ItemStack>) -> String { + match s { + None => "-".into(), + Some(s) => canon_str(&horizon_client::save::item_to_nbt(s)), + } +} + +struct World<'a> { + items: &'a Items, + enchantments: &'a Enchantments, + trades: &'a Trades, + sequences: RandomSequences, + seed: i64, +} +/// A merchant from PROF:TYPE:LEVEL or "wt", generated level by level. +struct Merchant { + villager: bool, + profession: String, + variant: String, + level: i32, + trader: Trader, +} +impl World<'_> { + fn reset(&mut self, seed: i64) { + self.sequences = RandomSequences::default(); + self.seed = seed; + } + fn add_set( + &mut self, + offers: &mut Vec, + set: &str, + variant: &str, + origin: [f64; 3], + ) { + let Some(sequence) = self.trades.sequence(set) else { + return; + }; + let ctx = TradeContext { + items: self.items, + enchantments: self.enchantments, + variant, + origin, + maps: None, + }; + let random = self.sequences.get(&sequence, self.seed); + offers.extend(self.trades.offers_from_set(&ctx, set, random)); + } + fn merchant(&mut self, spec: &str, origin: [f64; 3]) -> Merchant { + let mut offers = Vec::new(); + if spec == "wt" { + for set in ["buying", "uncommon", "common"] { + self.add_set( + &mut offers, + &format!("minecraft:wandering_trader/{set}"), + "minecraft:plains", + origin, + ); + } + return Merchant { + villager: false, + profession: "minecraft:wandering_trader".into(), + variant: "minecraft:plains".into(), + level: 1, + trader: Trader { + offers, + ..Default::default() + }, + }; + } + let p: Vec<&str> = spec.split(':').collect(); + let (profession, variant) = (format!("minecraft:{}", p[0]), format!("minecraft:{}", p[1])); + let max: i32 = p[2].parse().unwrap_or(1); + for level in 1..=max { + let set = Trades::set_for(&profession, level); + if self.trades.sets.contains_key(&set) { + self.add_set(&mut offers, &set, &variant, origin); + } + } + Merchant { + villager: true, + profession, + variant, + level: max, + trader: Trader { + offers, + ..Default::default() + }, + } + } +} + +fn kv(fields: &[&str]) -> HashMap { + let mut m: HashMap = HashMap::new(); + for f in &fields[2..] { + if let Some((k, v)) = f.split_once('=') { + m.entry(k.to_owned()) + .and_modify(|e| { + e.push(' '); + e.push_str(v); + }) + .or_insert_with(|| v.to_owned()); + } + } + m +} + +/// Uses, demand, gossip, xp and restock state, as the oracle's `prepare`. +fn prepare(m: &mut Merchant, gossips: &mut Gossips, kv: &HashMap) { + for key in ["uses", "demand"] { + let Some(list) = kv.get(key) else { continue }; + for s in list.split(' ') { + let mut f = s.split(':'); + let i: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0); + let n: i32 = f.next().and_then(|v| v.parse().ok()).unwrap_or(0); + let Some(o) = m.trader.offers.get_mut(i) else { + continue; + }; + if key == "uses" { + o.uses += n; + } else { + o.demand = n; + } + } + } + if let Some(list) = kv.get("gossip") { + for s in list.split(' ') { + let (kind, n) = s.split_once(':').unwrap_or((s, "0")); + if let Some(kind) = GossipType::from_id(kind) { + gossips.add(PLAYER, kind, n.parse().unwrap_or(0)); + } + } + } + if let Some(xp) = kv.get("xp") { + m.trader.xp = xp.parse().unwrap_or(0); + } + if let Some(v) = kv.get("lastrestock") { + m.trader.last_restock = v.parse().unwrap_or(0); + } + if let Some(v) = kv.get("restocks") { + m.trader.restocks_today = v.parse().unwrap_or(0); + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: trading_fixture RESOURCES INPUT VANILLA_OUTPUT OUTPUT"; + let root = Path::new(args.get(1).ok_or(usage)?); + let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?; + let items = Items::catalog(root)?; + let enchantments = Enchantments::load(root); + let trades = Trades::load(root); + let recipes = horizon_client::crafting::Recipes::load(root, &items)?; + let brewing = horizon_client::brewing::Brewing::load(root, &items); + let banners = horizon_client::banner::Banners::load(root); + let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)? + .types + .into_iter() + .map(|(k, v)| (k, std::sync::Arc::new(v))) + .collect(); + // The vanilla villagers the nbt cases read. + let snbt: HashMap<&str, &str> = vanilla + .lines() + .filter_map(|l| { + let (name, rest) = l.split_once(' ')?; + Some((name, rest.strip_prefix("snbt ")?)) + }) + .collect(); + let mut world = World { + items: &items, + enchantments: &enchantments, + trades: &trades, + sequences: RandomSequences::default(), + seed: 0, + }; + let mut out = String::new(); + for line in input.lines().filter(|l| !l.trim().is_empty()) { + let fields: Vec<&str> = line.split(' ').collect(); + let (kind, name) = (fields[0], fields[1]); + let kv = kv(&fields); + let seed: i64 = kv.get("seed").and_then(|s| s.parse().ok()).unwrap_or(0); + world.reset(seed); + let origin = [0.5, -60.0, 0.5]; + match kind { + "gen" => { + let specs: Vec = kv["v"].split(' ').map(str::to_owned).collect(); + for (k, spec) in specs.iter().enumerate() { + let m = world.merchant(spec, origin); + writeln!( + out, + "{name} v{k} {}", + canon_str(&entity_nbt::offers_to_nbt(&m.trader.offers)) + )?; + } + let mut line = format!("{name} draws"); + for id in trades.sequences() { + write!(line, " {}", world.sequences.get(&id, seed).next_int())?; + } + writeln!(out, "{line}")?; + } + "price" => { + let mut m = world.merchant(&kv["v"], origin); + let mut gossips = Gossips::default(); + prepare(&mut m, &mut gossips, &kv); + let hero = kv.get("hero").and_then(|h| h.parse().ok()); + let rep = gossips.reputation(PLAYER); + merchant::update_special_prices(&mut m.trader.offers, rep, hero); + let mut line = format!("{name} rep {rep}"); + for o in &m.trader.offers { + write!(line, " {}/{}", o.cost_a_count(&items), o.special_price_diff)?; + } + writeln!(out, "{line}")?; + } + "restock" => { + let mut m = world.merchant(&kv["v"], origin); + let mut gossips = Gossips::default(); + prepare(&mut m, &mut gossips, &kv); + let steps = kv.get("steps").cloned().unwrap_or_default(); + for (k, s) in steps.split(',').filter(|s| !s.is_empty()).enumerate() { + let f: Vec<&str> = s.split(':').collect(); + let mut line = format!("{name} {k} {s}"); + match f[0] { + "use" => { + let i: usize = f[1].parse().unwrap_or(0); + if let Some(o) = m.trader.offers.get_mut(i) { + o.uses += f[2].parse::().unwrap_or(0); + } + } + "check" => { + let time: i64 = f[1].parse().unwrap_or(0); + let day: i64 = f[2].parse().unwrap_or(0); + let should = m.trader.should_restock(time, day); + if should { + m.trader.restock(time); + } + write!(line, " {should}")?; + } + _ => {} + } + write!( + line, + " lr {} rt {} cd {}", + m.trader.last_restock, m.trader.restocks_today, m.trader.check_day + )?; + for o in &m.trader.offers { + write!(line, " {}/{}", o.uses, o.demand)?; + } + writeln!(out, "{line}")?; + } + } + "nbt" => { + let text = snbt.get(name).ok_or("missing vanilla snbt")?; + let (tag, _) = horizon_world::nbt::parse_snbt(text)?; + let id = if kv["v"] == "wt" { + "minecraft:wandering_trader" + } else { + "minecraft:villager" + }; + let mut tag = tag; + if let Tag::Compound(c) = &mut tag { + c.insert("id".into(), Tag::String(id.into())); + } + let mob = entity_nbt::mob_from_nbt(&tag, &types, 1).ok_or("unreadable villager")?; + let back = entity_nbt::mob_to_nbt(&mob, [0; 4], None); + writeln!(out, "{name} snbt {text}")?; + let mut kept = horizon_world::nbt::Compound::new(); + for key in [ + "Offers", + "Xp", + "LastRestock", + "RestocksToday", + "VillagerData", + ] { + if let Some(v) = back.get(key) { + kept.insert(key.into(), v.clone()); + } + } + writeln!(out, "{name} canon {}", canon_str(&Tag::Compound(kept)))?; + } + "trade" => { + let env_trade = TradeEnv { + trades: &trades, + enchantments: &enchantments, + maps: None, + }; + let env = Env { + items: &items, + recipes: &recipes, + brewing: &brewing, + banners: &banners, + trade: Some(&env_trade), + }; + trade(&mut out, name, &kv, &mut world, &env, origin)?; + } + _ => return Err(format!("unknown case {kind}").into()), + } + } + fs::write(args.get(4).ok_or(usage)?, out)?; + Ok(()) +} + +fn trade( + out: &mut String, + name: &str, + kv: &HashMap, + world: &mut World, + env: &Env, + origin: [f64; 3], +) -> horizon_client::Result<()> { + let vseed: i64 = kv.get("vseed").and_then(|s| s.parse().ok()).unwrap_or(0); + let mut m = world.merchant(&kv["v"], origin); + let mut gossips = Gossips::default(); + if m.villager { + prepare(&mut m, &mut gossips, kv); + } + let hero: Option = kv.get("hero").and_then(|h| h.parse().ok()); + let mut menu = Menu::new(Kind::Merchant); + if let Some(inv) = kv.get("inv") { + for s in inv.split(',') { + let (slot, rest) = s.split_once(':').ok_or("inv")?; + let (item, count) = rest.rsplit_once('*').ok_or("inv")?; + let item = if item.contains(':') { + item.to_owned() + } else { + format!("minecraft:{item}") + }; + menu.set_player_item(slot.parse()?, Some(ItemStack::new(&item, count.parse()?))); + } + } + menu.selected = kv.get("hand").and_then(|h| h.parse().ok()).unwrap_or(8); + // Villager.mobInteract / WanderingTrader.mobInteract. + let open = !m.trader.offers.is_empty(); + let unhappy = if m.villager && !open { 40 } else { 0 }; + let mut voice = LegacyRandom::new(vseed); + if unhappy > 0 { + // setUnhappy: makeSound(VILLAGER_NO) draws the voice pitch. + voice.next_float(); + voice.next_float(); + } + writeln!(out, "{name} open {open} unhappy {unhappy}")?; + let mut session = Session::new(m.trader.offers.clone(), m.villager); + session.xp = m.trader.xp; + session.level = m.level; + session.profession = m.profession.clone(); + session.variant = m.variant.clone(); + session.random = voice.clone(); + session.origin = origin; + session.reputation = gossips.reputation(PLAYER); + session.hero = hero; + for id in Session::sequences_needed(world.trades, &m.profession, m.level) { + let r = world.sequences.lend(&id, world.seed); + session.sequences.insert(id, r); + } + session.update_special_prices(); + let mut regen = false; + let mut open_menu = open; + if open_menu { + menu.merchant = Some(Box::new(session)); + } + let steps = kv.get("steps").cloned().unwrap_or_default(); + let mut session_after: Option> = None; + for (k, s) in steps.split(',').filter(|s| !s.is_empty()).enumerate() { + let f: Vec<&str> = s.split(':').collect(); + match f[0] { + "select" if open_menu => menu.merchant_select(env, f[1].parse().unwrap_or(0)), + "click" if open_menu => { + let input = Input::parse(&f[3].to_uppercase()).ok_or("input")?; + let _ = menu.click(env, f[1].parse()?, f[2].parse()?, input); + } + "tick" => { + let sess = menu.merchant.as_mut().or(session_after.as_mut()); + if let Some(sess) = sess + && sess.villager + && sess.last_traded + { + sess.last_traded = false; + gossips.add(PLAYER, GossipType::Trading, 2); + sess.reputation = gossips.reputation(PLAYER); + if open_menu { + sess.update_special_prices(); + menu.merchant_update(env); + } + } + } + "close" if open_menu => { + menu.merchant_close(env); + open_menu = false; + session_after = Some(menu.merchant.take().ok_or("session")?); + } + _ => {} + } + let mut line = format!("{name} {k} {s} menu {open_menu}"); + if open_menu { + for i in 0..3 { + write!(line, " {}", stack(menu.slot(i)))?; + } + write!( + line, + " fxp {}", + menu.merchant.as_ref().map_or(0, |s| s.future_xp) + )?; + } + write!(line, " carried {}", stack(menu.carried.as_ref()))?; + line.push_str(" inv"); + for i in 0..36 { + if let Some(st) = menu.player_item(i) { + write!(line, " {i}={}", stack(Some(st)))?; + } + } + let sess = menu + .merchant + .as_deref_mut() + .or(session_after.as_deref_mut()); + let (xp, level, offers, orbs) = match sess { + Some(sess) => { + let mut orbs = Vec::new(); + for e in sess.events.drain(..) { + match e { + Event::Orb(v) => orbs.push(v), + Event::LevelUp(_) => regen = true, + _ => {} + } + } + (sess.xp, sess.level, sess.offers.clone(), orbs) + } + None => (m.trader.xp, m.level, m.trader.offers.clone(), Vec::new()), + }; + write!(line, " xp {xp}")?; + if m.villager { + write!( + line, + " lvl {level} rep {} regen {regen}", + gossips.reputation(PLAYER) + )?; + } + line.push_str(" offers"); + for o in &offers { + write!( + line, + " {}/{}/{}", + o.uses, + o.special_price_diff, + o.cost_a_count(env.items) + )?; + } + line.push_str(" orbs"); + for v in orbs { + write!(line, " {v}")?; + } + writeln!(out, "{line}")?; + } + let random = match menu.merchant.as_mut().or(session_after.as_mut()) { + Some(s) => s.random.next_int(), + None => voice.next_int(), + }; + writeln!(out, "{name} next {random}")?; + Ok(()) +} diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index f6ec337d3..e4a70811a 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1061,7 +1061,7 @@ impl Special { } } /// `DyedItemColor.applyDyes` over dye indexes. -fn apply_dyes(current: Option, dyes: &[usize]) -> i32 { +pub(crate) fn apply_dyes(current: Option, dyes: &[usize]) -> i32 { let (mut r, mut g, mut b, mut intensity, mut n) = (0i32, 0i32, 0i32, 0i32, 0i32); let mut add = |rgb: u32| { let (red, green, blue) = ( diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 6745c5335..03b3030ca 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1257,19 +1257,41 @@ fn villager_data(m: &Mob) -> Tag { /// `AbstractVillager` "Offers" (`MerchantOffers.CODEC`). fn put_offers(map: &mut Compound, m: &Mob) { let Some(t) = &m.extra.trade else { return }; - let recipes = t - .offers + map.insert("Offers".into(), offers_to_nbt(&t.offers)); +} +/// `ItemCost.CODEC`: id, count (always written) and the exact components. +fn item_cost_to_nbt(stack: &crate::items::ItemStack) -> Tag { + let mut tag = item_to_nbt(stack); + if let Tag::Compound(c) = &mut tag + && !c.contains_key(&"count".into()) + { + c.insert("count".into(), Tag::Int(stack.count as i32)); + } + tag +} +/// `MerchantOffers.CODEC`: `{Recipes: [...]}`, each offer without the +/// fields at their defaults. +pub fn offers_to_nbt(offers: &[crate::merchant::MerchantOffer]) -> Tag { + let recipes = offers .iter() .map(|o| { let mut entries = vec![ - ("buy", item_to_nbt(&o.base_cost_a.stack)), + ("buy", item_cost_to_nbt(&o.base_cost_a.stack)), ("sell", item_to_nbt(&o.result)), - ("uses", Tag::Int(o.uses)), - ("maxUses", Tag::Int(o.max_uses)), - ("priceMultiplier", Tag::Float(o.price_multiplier.to_bits())), - ("xp", Tag::Int(o.xp)), ]; // `MerchantOffer.CODEC` omits fields at their defaults. + if o.uses != 0 { + entries.push(("uses", Tag::Int(o.uses))); + } + if o.max_uses != 4 { + entries.push(("maxUses", Tag::Int(o.max_uses))); + } + if o.price_multiplier != 0.0 { + entries.push(("priceMultiplier", Tag::Float(o.price_multiplier.to_bits()))); + } + if o.xp != 1 { + entries.push(("xp", Tag::Int(o.xp))); + } if !o.reward_exp { entries.push(("rewardExp", Tag::Byte(0))); } @@ -1280,15 +1302,45 @@ fn put_offers(map: &mut Compound, m: &Mob) { entries.push(("demand", Tag::Int(o.demand))); } if let Some(b) = &o.cost_b { - entries.push(("buyB", item_to_nbt(&b.stack))); + entries.push(("buyB", item_cost_to_nbt(&b.stack))); } Tag::compound(entries) }) - .collect(); - map.insert( - "Offers".into(), - Tag::compound([("Recipes", Tag::List(recipes))]), - ); + .collect::>(); + // An empty list is the field's default: left out. + if recipes.is_empty() { + return Tag::Compound(Compound::new()); + } + Tag::compound([("Recipes", Tag::List(recipes))]) +} +/// The offers of a `MerchantOffers.CODEC` tag. +pub fn offers_from_nbt(tag: &Tag) -> Vec { + use crate::merchant::{ItemCost, MerchantOffer}; + let Some(Tag::List(recipes)) = tag.get("Recipes") else { + return Vec::new(); + }; + recipes + .iter() + .filter_map(|r| { + let cost = |key| { + r.get(key) + .and_then(item_from_nbt) + .map(|stack| ItemCost { stack }) + }; + Some(MerchantOffer { + base_cost_a: cost("buy")?, + cost_b: cost("buyB"), + result: r.get("sell").and_then(item_from_nbt)?, + uses: number(r.get("uses")).unwrap_or(0) as i32, + max_uses: number(r.get("maxUses")).unwrap_or(4) as i32, + reward_exp: number(r.get("rewardExp")).unwrap_or(1) != 0, + special_price_diff: number(r.get("specialPrice")).unwrap_or(0) as i32, + demand: number(r.get("demand")).unwrap_or(0) as i32, + price_multiplier: float(r.get("priceMultiplier")).unwrap_or(0.0) as f32, + xp: number(r.get("xp")).unwrap_or(1) as i32, + }) + }) + .collect() } /// The villager brain's `job_site`, `home` and `meeting_point` memories. fn put_memories(map: &mut Compound, m: &Mob) { @@ -1314,7 +1366,7 @@ fn put_memories(map: &mut Compound, m: &Mob) { } fn read_villager(m: &mut Mob, tag: &Tag) { use crate::{ - merchant::{ItemCost, MerchantOffer, Trader}, + merchant::Trader, mobs::render::{PROFESSIONS, VILLAGER_TYPES}, }; if let Some(data) = tag.get("VillagerData") { @@ -1343,31 +1395,10 @@ fn read_villager(m: &mut Mob, tag: &Tag) { if m.species() == crate::mobs::Species::Villager { crate::mobs::villager::read_nbt(m, tag); } - let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else { + let Some(offers_tag) = tag.get("Offers") else { return; }; - let offers = recipes - .iter() - .filter_map(|r| { - let cost = |key| { - r.get(key) - .and_then(item_from_nbt) - .map(|stack| ItemCost { stack }) - }; - Some(MerchantOffer { - base_cost_a: cost("buy")?, - cost_b: cost("buyB"), - result: r.get("sell").and_then(item_from_nbt)?, - uses: number(r.get("uses")).unwrap_or(0) as i32, - max_uses: number(r.get("maxUses")).unwrap_or(4) as i32, - reward_exp: number(r.get("rewardExp")).unwrap_or(1) != 0, - special_price_diff: number(r.get("specialPrice")).unwrap_or(0) as i32, - demand: number(r.get("demand")).unwrap_or(0) as i32, - price_multiplier: float(r.get("priceMultiplier")).unwrap_or(0.0) as f32, - xp: number(r.get("xp")).unwrap_or(1) as i32, - }) - }) - .collect(); + let offers = offers_from_nbt(offers_tag); m.extra.trade = Some(Box::new(Trader { xp: number(tag.get("Xp")).unwrap_or(0) as i32, offers, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7f02bf53b..54f0700a3 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3896,6 +3896,7 @@ impl Game<'_> { recipes: &self.res.recipes, brewing: &self.res.stations.brewing, banners: &self.res.stations.banners, + trade: None, }; menu.creative = creative; menu.selected = self.selected; diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 65141f060..dcf572d04 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -96,6 +96,8 @@ impl Game<'_> { items: &self.res.items, enchantments: &self.res.stations.enchantments, variant, + origin: [0.0; 3], + maps: None, }; self.res.stations.trades.offers_from_set(&ctx, set, random) } diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 10a5b6ecc..d54564b7a 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -573,10 +573,12 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { d.stew_effects .iter() .map(|(id, duration)| { - Tag::compound([ - ("id", Tag::String((&**id).into())), - ("duration", Tag::Int(*duration)), - ]) + // The codec leaves out the default duration (160). + let mut e = vec![("id", Tag::String((&**id).into()))]; + if *duration != 160 { + e.push(("duration", Tag::Int(*duration))); + } + Tag::compound(e) }) .collect(), ), diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index d917479a2..8c3e4e340 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3,7 +3,9 @@ //! craft drags, pickup all) for the player inventory, the crafting table, the //! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing //! stand, the crafter (its client menu and the block entity's server menu with -//! `setSlotState`) and the loom (`clickMenuButton`, `slotsChanged`). +//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`) and the +//! merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the +//! result slot's trade, `tryMoveItems`). //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. use crate::{ @@ -22,6 +24,8 @@ pub struct Env<'a> { pub recipes: &'a Recipes, pub brewing: &'a Brewing, pub banners: &'a Banners, + /// What a merchant menu needs for offers made while it is open (level-ups). + pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -67,6 +71,8 @@ pub enum Kind { /// result follows the grid, and filling a disabled slot enables it. CrafterBlock, Loom, + /// `MerchantMenu`: two payment slots, the result, then the inventory. + Merchant, } impl Kind { @@ -87,6 +93,7 @@ impl Kind { "crafter" => Self::Crafter, "crafter_be" => Self::CrafterBlock, "loom" => Self::Loom, + "merchant" => Self::Merchant, _ => return None, }) } @@ -120,6 +127,8 @@ enum Role { LoomPattern, /// The loom's result slot (a plain slot whose `onTake` uses the inputs). LoomResult, + /// `MerchantResultSlot`. + MerchantResult, } #[derive(Clone, Copy)] @@ -161,6 +170,8 @@ pub struct Menu { pub sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, + /// The merchant a merchant menu trades with. + pub merchant: Option>, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -297,6 +308,16 @@ impl Menu { player(&mut slots); data = 1; } + Kind::Merchant => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::MerchantResult, + }); + player(&mut slots); + } Kind::Brewing => { containers[MAIN] = vec![None; 5]; for (index, role) in [ @@ -360,6 +381,7 @@ impl Menu { loom_patterns: Vec::new(), sounds: Vec::new(), crafted: Vec::new(), + merchant: None, } } @@ -470,6 +492,11 @@ impl Menu { /// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs, /// the block crafter refreshes its result. fn slot_changed(&mut self, env: &Env, s: usize) { + // MerchantContainer.setChanged: every slot of it, the result too. + if self.kind == Kind::Merchant && self.slots[s].container != PLAYER { + self.merchant_update(env); + return; + } if self.slots[s].container != MAIN { return; } @@ -586,7 +613,7 @@ impl Menu { Role::LoomBanner => Self::is_banner(stack), Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), - Role::LoomResult => false, + Role::LoomResult | Role::MerchantResult => false, } } @@ -595,9 +622,20 @@ impl Menu { stack.item.ends_with("_banner") } - fn may_pickup(&self, s: usize) -> bool { + fn may_pickup(&self, env: &Env, s: usize) -> bool { match self.slots[s].role { Role::Inert => false, + Role::MerchantResult => self + .merchant + .as_ref() + .and_then(|m| m.offers.get(m.active?)) + .is_some_and(|o| { + let (a, b) = ( + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ); + o.satisfied_by(env.items, a, b) || o.satisfied_by(env.items, b, a) + }), Role::Armor(_) => match self.slot(s) { Some(stack) => { self.creative || stack.enchantment_level("minecraft:binding_curse") == 0 @@ -661,8 +699,9 @@ impl Menu { if out.is_some() && slot.container == GRID { self.recompute(env); } - // SimpleContainer.removeItem calls setChanged when it took something. - if out.is_some() && self.kind == Kind::Loom { + // SimpleContainer.removeItem calls setChanged when it took something; + // MerchantContainer.removeItem updates the result after a payment slot. + if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant) { self.slot_changed(env, s); } out @@ -682,6 +721,10 @@ impl Menu { /// `ResultSlot.onTake` and the other `Slot.onTake` overrides. fn on_take(&mut self, env: &Env, s: usize) { + if self.slots[s].role == Role::MerchantResult { + self.merchant_take(env); + return; + } if self.slots[s].role == Role::LoomResult { // LoomMenu's result onTake: one banner and one dye are used up. self.remove(env, 0, 1); @@ -764,7 +807,7 @@ impl Menu { amount: u32, max_amount: u32, ) -> Option { - if !self.may_pickup(s) { + if !self.may_pickup(env, s) { return None; } if !self.allow_modification(env, s) && max_amount < self.slot(s).map_or(0, |c| c.count) { @@ -778,7 +821,7 @@ impl Menu { } fn allow_modification(&self, env: &Env, s: usize) -> bool { - self.may_pickup(s) + self.may_pickup(env, s) && match self.slot(s) { Some(stack) => self.may_place(env, s, stack), None => true, @@ -1119,6 +1162,29 @@ impl Menu { return None; } } + Kind::Merchant => { + after_take = true; + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + if let Some(m) = self.merchant.as_mut() { + m.events.push(crate::merchant::Event::TradeSound); + } + } else if index != 0 && index != 1 { + if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } Kind::Crafter | Kind::CrafterBlock => { after_take = true; if index < 9 { @@ -1364,7 +1430,7 @@ impl Menu { return Err(OUT_OF_BOUNDS); } let s = slot_index as usize; - if !self.may_pickup(s) { + if !self.may_pickup(env, s) { return Ok(()); } let mut clicked = self.quick_move(env, s); @@ -1459,7 +1525,7 @@ impl Menu { tidy(&mut self.carried); } } - Some(clicked) if self.may_pickup(s) => match self.carried.take() { + Some(clicked) if self.may_pickup(env, s) => match self.carried.take() { None => { let amount = if primary { clicked.count @@ -1518,7 +1584,7 @@ impl Menu { } match (source, target_stack) { (None, Some(taken)) => { - if self.may_pickup(target) { + if self.may_pickup(env, target) { self.containers[PLAYER][inv_slot] = Some(taken.clone()); self.put(env, target, None); self.on_take(env, target); @@ -1538,7 +1604,7 @@ impl Menu { } } (Some(mut source), Some(mut taken)) => { - if self.may_pickup(target) && self.may_place(env, target, &source) { + if self.may_pickup(env, target) && self.may_place(env, target, &source) { let max = self.slot_max(env, target, &source); if source.count > max { let part = split(&mut source, max); @@ -1564,7 +1630,7 @@ impl Menu { let Some(carried) = self.carried.clone() else { return; }; - if self.has_item(s) && self.may_pickup(s) { + if self.has_item(s) && self.may_pickup(env, s) { return; } let total = self.slots.len() as i32; @@ -1577,9 +1643,11 @@ impl Menu { let t = i as usize; i += step; let have = self.carried.clone().expect("some"); - if self.has_item(t) + // MerchantMenu.canTakeItemForPickAll is always false. + if self.kind != Kind::Merchant + && self.has_item(t) && self.quick_replace(t, &have, env) - && self.may_pickup(t) + && self.may_pickup(env, t) && (self.slots[t].container != RESULT || self.kind == Kind::Loom) { let item = self.slot(t).expect("has item").clone(); @@ -1596,3 +1664,149 @@ impl Menu { } } } + +/// `MerchantMenu` and `MerchantContainer` over the menu's `merchant` session. +impl Menu { + /// `MerchantContainer.updateSellItem`. + pub fn merchant_update(&mut self, env: &Env) { + let Some(m) = self.merchant.as_mut() else { + return; + }; + let (a, b) = ( + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ); + let (a, b) = if a.is_none() { (b, None) } else { (a, b) }; + m.active = None; + if a.is_none() { + self.containers[RESULT][0] = None; + m.future_xp = 0; + return; + } + if !m.offers.is_empty() { + let (active, result) = + crate::merchant::sell_item(&m.offers, env.items, a, b, Some(m.selection_hint)); + m.active = active; + m.future_xp = if result.is_some() { + active.map_or(0, |i| m.offers[i].xp) + } else { + 0 + }; + self.containers[RESULT][0] = result; + } + let has = self.containers[RESULT][0].is_some(); + m.notify_trade_updated(has); + } + /// `MerchantResultSlot.onTake`: the payment is taken and the merchant + /// told (`notifyTrade`). + fn merchant_take(&mut self, env: &Env) { + let Some(m) = self.merchant.as_mut() else { + return; + }; + let Some(i) = m.active else { return }; + let Some(offer) = m.offers.get(i).cloned() else { + return; + }; + let (mut a, mut b) = ( + self.containers[MAIN][0].take(), + self.containers[MAIN][1].take(), + ); + let took = offer.take(env.items, &mut a, &mut b) || offer.take(env.items, &mut b, &mut a); + // The payment stacks shrink in place, before the merchant hears of it. + self.containers[MAIN][0] = a; + self.containers[MAIN][1] = b; + if took { + let prices = m.notify_trade(i, env.trade, env.items); + if prices { + self.merchant_update(env); + } + // setItem(0, buyA), setItem(1, buyB). + self.merchant_update(env); + self.merchant_update(env); + } + } + /// `MerchantMenu.tryMoveItems` (the select trade packet, with the + /// selection hint set first). + pub fn merchant_select(&mut self, env: &Env, index: usize) { + let Some(m) = self.merchant.as_mut() else { + return; + }; + // MerchantContainer.setSelectionHint updates the result. + m.selection_hint = index; + let count = m.offers.len(); + self.merchant_update(env); + if index >= count { + return; + } + for slot in [0usize, 1] { + if let Some(mut old) = self.containers[MAIN][slot].clone() { + if !self.move_to(env, &mut old, 3, 39, true) { + return; + } + self.containers[MAIN][slot] = (old.count > 0).then_some(old); + self.put(env, slot, self.containers[MAIN][slot].clone()); + } + } + if self.containers[MAIN][0].is_some() || self.containers[MAIN][1].is_some() { + return; + } + let Some(offer) = self + .merchant + .as_ref() + .and_then(|m| m.offers.get(index)) + .cloned() + else { + return; + }; + self.merchant_fill(env, 0, &offer.base_cost_a); + if let Some(b) = &offer.cost_b { + self.merchant_fill(env, 1, b); + } + } + /// `MerchantMenu.moveFromInventoryToPaymentSlot`. + fn merchant_fill(&mut self, env: &Env, payment: usize, cost: &crate::merchant::ItemCost) { + for i in 3..39 { + let Some(have) = self.slot(i).cloned() else { + continue; + }; + if !cost.test(&have) { + continue; + } + let current = self.containers[MAIN][payment].clone(); + if current + .as_ref() + .is_some_and(|c| !c.same_item_same_components(&have)) + { + continue; + } + let max = Self::max_stack(env, &have); + let current_count = current.as_ref().map_or(0, |c| c.count); + let moved = max.saturating_sub(current_count).min(have.count); + let payment_stack = ItemStack { + count: current_count + moved, + ..have.clone() + }; + let slot = self.slots[i]; + let mut left = have; + left.count -= moved; + self.containers[slot.container][slot.index] = (left.count > 0).then_some(left); + self.put(env, payment, Some(payment_stack.clone())); + if payment_stack.count >= max { + break; + } + } + } + /// `MerchantMenu.removed` for a living player: the payment goes back to + /// the inventory (`placeItemBackInInventory`), or is dropped. + pub fn merchant_close(&mut self, env: &Env) { + // AbstractContainerMenu.removed: the carried stack first. + if let Some(mut carried) = self.carried.take() { + self.place_back(env, &mut carried); + } + for slot in [0usize, 1] { + if let Some(mut stack) = self.containers[MAIN][slot].take() { + self.place_back(env, &mut stack); + } + } + } +} diff --git a/crates/horizon-client/src/menu/place.rs b/crates/horizon-client/src/menu/place.rs index 85f537146..0a7fb607c 100644 --- a/crates/horizon-client/src/menu/place.rs +++ b/crates/horizon-client/src/menu/place.rs @@ -538,7 +538,7 @@ impl Menu { } /// `Inventory.placeItemBackInInventory`. - fn place_back(&mut self, env: &Env, stack: &mut ItemStack) { + pub(super) fn place_back(&mut self, env: &Env, stack: &mut ItemStack) { while stack.count > 0 { let slot = self .slot_with_space(env, stack) diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index a3dde71a9..936eab0aa 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -146,8 +146,9 @@ impl MerchantOffer { /// `getModifiedCostCount` for cost A. pub fn cost_a_count(&self, items: &Items) -> u32 { let base = self.base_cost_a.stack.count as i32; + // Mth.floor(basePrice * demand * priceMultiplier): an int product, then the float. let demand_diff = - ((base as f32 * self.demand as f32 * self.price_multiplier).floor() as i32).max(0); + ((base.wrapping_mul(self.demand) as f32 * self.price_multiplier).floor() as i32).max(0); (base + demand_diff + self.special_price_diff) .clamp(1, Self::max_stack(items, &self.base_cost_a.stack) as i32) as u32 } @@ -210,7 +211,8 @@ impl MerchantOffer { true } } -/// `MerchantOffers.getRecipeFor`: the hinted offer if it fits, else the first that does. +/// `MerchantOffers.getRecipeFor`: a hint past the first offer names the only +/// offer that may match; otherwise the first offer that fits. pub fn recipe_for( offers: &[MerchantOffer], items: &Items, @@ -219,9 +221,10 @@ pub fn recipe_for( hint: Option, ) -> Option { if let Some(h) = hint - && offers.get(h).is_some_and(|o| o.satisfied_by(items, a, b)) + && h > 0 + && h < offers.len() { - return Some(h); + return offers[h].satisfied_by(items, a, b).then_some(h); } offers.iter().position(|o| o.satisfied_by(items, a, b)) } @@ -259,12 +262,187 @@ pub fn sequence_random(world_seed: i64, id: &str) -> XoroshiroRandom { XoroshiroRandom::from_state(mix_stafford13(lo ^ key[0]), mix_stafford13(hi ^ key[1])) } +/// What a trade screen's session changes besides the menu, for the caller. +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// An experience orb of this value at the merchant (`rewardTradeXp`). + Orb(i32), + /// The villager reached this level (regeneration for 200 ticks). + LevelUp(i32), + /// `notifyTradeUpdated`: the merchant says yes (a result) or no, at + /// this pitch. + TradeUpdated(bool, f32), + /// `MerchantMenu.playTradeSound` (a shift-clicked trade). + TradeSound, + /// A trade of this offer was made (`notifyTrade`). + Traded(usize), +} +/// What the world lends a trading session for offers made while it is open. +pub struct TradeEnv<'a> { + pub trades: &'a Trades, + pub enchantments: &'a Enchantments, + pub maps: Option<&'a dyn MapMaker>, +} +/// The merchant side of an open trading screen: `AbstractVillager` / +/// `Villager` / `WanderingTrader` as `MerchantMenu` sees it (offers, +/// experience, level-ups, special prices for the trading player) and the +/// `MerchantContainer` state (selection hint, active offer, future xp). +#[derive(Clone, Debug)] +pub struct Session { + pub offers: Vec, + pub xp: i32, + pub level: i32, + /// A villager (progress bar, restocks, level-ups), not a wandering trader. + pub villager: bool, + /// `minecraft:` ids of the profession and villager type. + pub profession: String, + pub variant: String, + /// The merchant's own random (`rewardTradeXp`). + pub random: horizon_core::random::LegacyRandom, + pub origin: [f64; 3], + /// The trading player's reputation and Hero of the Village amplifier. + pub reputation: i32, + pub hero: Option, + /// Trade set sequences the session may draw from (the next levels'), lent + /// by the world's `RandomSequences` and given back when it closes. + pub sequences: std::collections::BTreeMap, + pub selection_hint: usize, + pub active: Option, + pub future_xp: i32, + /// `Mob.ambientSoundTime`. + pub ambient_sound_time: i32, + /// `Villager.lastTradedPlayer` is set: the TRADE reputation event is due. + pub last_traded: bool, + pub events: Vec, +} +impl Session { + pub fn new(offers: Vec, villager: bool) -> Self { + Self { + offers, + xp: 0, + level: 1, + villager, + profession: String::new(), + variant: "minecraft:plains".into(), + random: horizon_core::random::LegacyRandom::new(0), + origin: [0.0; 3], + reputation: 0, + hero: None, + sequences: Default::default(), + selection_hint: 0, + active: None, + future_xp: 0, + ambient_sound_time: 0, + last_traded: false, + events: Vec::new(), + } + } + /// `Merchant.showProgressBar` / `canRestock`. + pub fn show_progress(&self) -> bool { + self.villager + } + /// The trade sets whose sequences a villager of `profession` at `level` + /// may draw while trading: those of the levels above it. + pub fn sequences_needed(trades: &Trades, profession: &str, level: i32) -> Vec { + (level + 1..=5) + .filter_map(|l| trades.sequence(&Trades::set_for(profession, l))) + .collect() + } + /// `Villager.updateSpecialPrices` for the trading player. + pub fn update_special_prices(&mut self) { + if self.villager { + update_special_prices(&mut self.offers, self.reputation, self.hero); + } + } + /// `AbstractVillager.notifyTrade`: the offer's use, then `rewardTradeXp` + /// (and a level-up with its offers). True when the special prices were + /// recomputed (the menu then updates its result). + pub fn notify_trade( + &mut self, + index: usize, + env: Option<&TradeEnv<'_>>, + items: &Items, + ) -> bool { + let Some(offer) = self.offers.get_mut(index) else { + return false; + }; + offer.uses += 1; + let offer = offer.clone(); + self.ambient_sound_time = -80; + self.events.push(Event::Traded(index)); + let mut prices = false; + if self.villager { + let mut pop = 3 + self.random.next_int_bound(4).unwrap_or(0); + self.xp += offer.xp; + self.last_traded = true; + if can_level_up(self.level) && self.xp >= max_xp(self.level) { + self.level += 1; + if let Some(env) = env { + let set = Trades::set_for(&self.profession, self.level); + if env.trades.sets.contains_key(&set) { + let more = self.offers_from_set(env, items, &set); + self.offers.extend(more); + self.update_special_prices(); + prices = true; + } + } + self.events.push(Event::LevelUp(self.level)); + pop += 5; + } + if offer.reward_exp { + self.events.push(Event::Orb(pop)); + } + } else if offer.reward_exp { + let pop = 3 + self.random.next_int_bound(4).unwrap_or(0); + self.events.push(Event::Orb(pop)); + } + prices + } + fn offers_from_set( + &mut self, + env: &TradeEnv<'_>, + items: &Items, + set: &str, + ) -> Vec { + let Some(sequence) = env.trades.sequence(set) else { + return Vec::new(); + }; + let Some(mut random) = self.sequences.remove(&sequence) else { + return Vec::new(); + }; + let ctx = TradeContext { + items, + enchantments: env.enchantments, + variant: &self.variant, + origin: self.origin, + maps: env.maps, + }; + let out = env.trades.offers_from_set(&ctx, set, &mut random); + self.sequences.insert(sequence, random); + out + } + /// `AbstractVillager.notifyTradeUpdated`. + pub fn notify_trade_updated(&mut self, has_result: bool) { + if self.ambient_sound_time > -80 + 20 { + self.ambient_sound_time = -80; + let pitch = self.voice_pitch(); + self.events.push(Event::TradeUpdated(has_result, pitch)); + } + } + /// `LivingEntity.getVoicePitch` of an adult merchant. + pub fn voice_pitch(&mut self) -> f32 { + (self.random.next_float() - self.random.next_float()) * 0.2 + 1.0 + } +} + /// The trade registries. pub struct Trades { pub trades: HashMap, /// villager_trade tags, ordered. pub tags: HashMap>, pub sets: HashMap, + /// potion tags, ordered (`set_random_potion` options). + pub potion_tags: HashMap>, } fn walk(dir: &Path, base: &Path, out: &mut HashMap) { let Ok(entries) = fs::read_dir(dir) else { @@ -304,6 +482,24 @@ impl Trades { &mut raw_tags, ); walk(&data.join("trade_set"), &data.join("trade_set"), &mut sets); + let mut raw_potions = HashMap::new(); + walk( + &data.join("tags/potion"), + &data.join("tags/potion"), + &mut raw_potions, + ); + let values = |v: Value| -> Vec { + v["values"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| e.as_str().map(str::to_owned)) + .collect() + }; + let raw_potions: HashMap> = raw_potions + .into_iter() + .map(|(k, v)| (k, values(v))) + .collect(); let raw: HashMap> = raw_tags .into_iter() .map(|(k, v)| { @@ -333,15 +529,35 @@ impl Trades { } } } - let tags = raw - .keys() - .map(|k| { - let mut v = Vec::new(); - expand(k, &raw, &mut v, 0); - (k.clone(), v) - }) - .collect(); - Self { trades, tags, sets } + let expand_all = |raw: &HashMap>| { + raw.keys() + .map(|k| { + let mut v = Vec::new(); + expand(k, raw, &mut v, 0); + (k.clone(), v) + }) + .collect() + }; + Self { + trades, + tags: expand_all(&raw), + sets, + potion_tags: expand_all(&raw_potions), + } + } + /// The random sequence of a trade set (`TradeSet.randomSequence`). + pub fn sequence(&self, set_id: &str) -> Option { + self.sets + .get(set_id)? + .get("random_sequence")? + .as_str() + .map(str::to_owned) + } + /// Every trade set's random sequence, sorted. + pub fn sequences(&self) -> Vec { + let mut v: Vec = self.sets.keys().filter_map(|k| self.sequence(k)).collect(); + v.sort(); + v } /// `VillagerProfession.getTrades(level)`. pub fn set_for(profession: &str, level: i32) -> String { @@ -387,7 +603,7 @@ impl Trades { match self .trades .get(&id) - .and_then(|t| offer_from(ctx, t, random)) + .and_then(|t| self.offer_from(ctx, t, random)) { Some(o) => out.push(o), None if duplicates => { @@ -405,6 +621,31 @@ pub struct TradeContext<'a> { pub enchantments: &'a Enchantments, /// Villager type (`minecraft:plains`, ...), for `merchant_predicate`. pub variant: &'a str, + /// The merchant's position (the loot context's origin). + pub origin: [f64; 3], + /// Finds structures for exploration maps; None finds nothing. + pub maps: Option<&'a dyn MapMaker>, +} +/// `ExplorationMapFunction`: `ServerLevel.findNearestMapStructure` and the +/// map it makes, for the world the merchant is in. +pub trait MapMaker { + /// The map for the nearest structure in `destination` (a structure tag) + /// within `radius` chunks of `origin`, or the stack unchanged when none is + /// found. + fn exploration_map( + &self, + stack: ItemStack, + map: &ExplorationMap, + origin: [f64; 3], + ) -> ItemStack; +} +/// An `exploration_map` function's settings. +pub struct ExplorationMap { + pub destination: String, + pub decoration: String, + pub zoom: u8, + pub search_radius: i32, + pub skip_existing_chunks: bool, } fn int_provider(v: &Value, random: &mut R) -> i32 { match v { @@ -422,18 +663,55 @@ fn int_provider(v: &Value, random: &mut R) -> i32 { } } "minecraft:constant" => o["value"].as_i64().unwrap_or(0) as i32, + // Sum: inputs in order, summed in a long and clamped. + "minecraft:add" => { + let mut total = 0i64; + for input in o["inputs"].as_array().into_iter().flatten() { + total += i64::from(int_provider(input, random)); + } + total.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32 + } + "minecraft:binomial" => { + let n = int_provider(&o["n"], random); + let p = float_provider(&o["p"], random); + (0..n).filter(|_| random.next_float() < p).count() as i32 + } _ => o.get("value").and_then(Value::as_i64).unwrap_or(0) as i32, }, _ => 0, } } +fn float_provider(v: &Value, random: &mut R) -> f32 { + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, + Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("") { + "minecraft:uniform" => { + let min = float_provider(&o["min"], random); + let max = float_provider(&o["max"], random); + // Mth.randomBetween + random.next_float() * (max - min) + min + } + _ => o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32, + }, + _ => 0.0, + } +} +/// `MobEffect.isInstantaneous`. +fn instantaneous(effect: &str) -> bool { + matches!( + effect, + "minecraft:saturation" | "minecraft:instant_health" | "minecraft:instant_damage" + ) +} fn cost(items: &Items, v: &Value, additional: i32) -> ItemCost { let id = v["id"].as_str().unwrap_or("minecraft:air"); let max = items.get(id).map_or(64, |i| i.max_stack) as i32; let count = (v["count"].as_i64().unwrap_or(1) as i32 + additional).clamp(0, max); - ItemCost { - stack: ItemStack::new(id, count as u32), + let mut stack = ItemStack::new(id, count as u32); + if let Some(potion) = v["components"]["minecraft:potion_contents"]["potion"].as_str() { + stack = stack.with_potion(potion); } + ItemCost { stack } } fn variant_ok(pred: &Value, variant: &str) -> bool { match &pred["predicate"]["minecraft:predicates"]["minecraft:villager/variant"] { @@ -442,162 +720,254 @@ fn variant_ok(pred: &Value, variant: &str) -> bool { _ => true, } } -/// `VillagerTrade.getOffer`. -pub fn offer_from( - ctx: &TradeContext<'_>, - t: &Value, - random: &mut R, -) -> Option { - if let Some(p) = t.get("merchant_predicate") - && !variant_ok(p, ctx.variant) - { - return None; - } - let gives = &t["gives"]; - let mut result = ItemStack::new( - gives["id"].as_str()?, - gives["count"].as_u64().unwrap_or(1) as u32, - ); - let mut additional = 0; - let modifiers: Vec<&Value> = match &t["given_item_modifier"] { - Value::Array(a) => a.iter().collect(), - v @ Value::Object(_) => vec![v], - _ => vec![], - }; - for m in modifiers { - let (stack, extra) = apply_modifier(ctx, m, result, random)?; - result = stack; - additional += extra; - } - if let Some(Value::String(tag)) = t.get("double_trade_price_enchantments") - && result - .stored_enchantments() - .iter() - .any(|(e, _)| ctx.enchantments.in_tag(tag, e)) - { - additional *= 2; - } - let a = cost(ctx.items, &t["wants"], additional); - if a.stack.count < 1 { - return None; - } - let b = t.get("additional_wants").map(|w| cost(ctx.items, w, 0)); - if b.as_ref().is_some_and(|b| b.stack.count < 1) { - return None; - } - Some(MerchantOffer { - base_cost_a: a, - cost_b: b, - result, - uses: 0, - max_uses: (t["max_uses"].as_i64().unwrap_or(4) as i32).max(1), - reward_exp: true, - special_price_diff: 0, - demand: 0, - price_multiplier: (t["reputation_discount"].as_f64().unwrap_or(0.0) as f32).max(0.0), - xp: (t["xp"].as_i64().unwrap_or(1) as i32).max(0), - }) -} -/// The loot functions trades use; None discards the offer. -fn apply_modifier( - ctx: &TradeContext<'_>, - m: &Value, - stack: ItemStack, - random: &mut R, -) -> Option<(ItemStack, i32)> { - let e = ctx.enchantments; - let pool = |options: &Value| -> Vec> { - match options { - Value::String(s) if s.starts_with('#') => e.tag(s).to_vec(), - Value::String(s) => vec![Arc::from(s.as_str())], - Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(Arc::from)).collect(), - _ => e.list.iter().map(|x| x.id.clone()).collect(), +impl Trades { + /// `VillagerTrade.getOffer`. + pub fn offer_from( + &self, + ctx: &TradeContext<'_>, + t: &Value, + random: &mut R, + ) -> Option { + if let Some(p) = t.get("merchant_predicate") + && !variant_ok(p, ctx.variant) + { + return None; } - }; - match m["type"].as_str().or(m["function"].as_str()).unwrap_or("") { - "minecraft:enchant_with_levels" => { - let levels = int_provider(&m["levels"], random); - // EnchantmentHelper.enchantItem on the loot context's random. - let chosen = e.select(ctx.items, random, &stack.item, levels, &pool(&m["options"])); - let mut out = if &*stack.item == "minecraft:book" { - ItemStack::new("minecraft:enchanted_book", stack.count) - } else { - stack - }; - for (id, l) in chosen { - out.enchant(&id, l); + let gives = &t["gives"]; + let mut result = ItemStack::new( + gives["id"].as_str()?, + gives["count"].as_u64().unwrap_or(1) as u32, + ); + let mut additional = 0; + let modifiers: Vec<&Value> = match &t["given_item_modifier"] { + Value::Array(a) => a.iter().collect(), + v @ Value::Object(_) => vec![v], + _ => vec![], + }; + for m in modifiers { + let (stack, extra) = self.apply_modifier(ctx, m, result, random)?; + result = stack; + additional += extra; + } + if let Some(Value::String(tag)) = t.get("double_trade_price_enchantments") + && result + .stored_enchantments() + .iter() + .any(|(e, _)| ctx.enchantments.in_tag(tag, e)) + { + additional *= 2; + } + let a = cost(ctx.items, &t["wants"], additional); + if a.stack.count < 1 { + return None; + } + let b = t.get("additional_wants").map(|w| cost(ctx.items, w, 0)); + if b.as_ref().is_some_and(|b| b.stack.count < 1) { + return None; + } + let max_uses = match t.get("max_uses") { + Some(v) => int_provider(v, random), + None => 4, + }; + let xp = match t.get("xp") { + Some(v) => int_provider(v, random), + None => 1, + }; + let discount = match t.get("reputation_discount") { + Some(v) => float_provider(v, random), + None => 0.0, + }; + Some(MerchantOffer { + base_cost_a: a, + cost_b: b, + result, + uses: 0, + max_uses: max_uses.max(1), + reward_exp: true, + special_price_diff: 0, + demand: 0, + price_multiplier: discount.max(0.0), + xp: xp.max(0), + }) + } + /// The loot functions trades use; None discards the offer. + fn apply_modifier( + &self, + ctx: &TradeContext<'_>, + m: &Value, + stack: ItemStack, + random: &mut R, + ) -> Option<(ItemStack, i32)> { + let e = ctx.enchantments; + let pool = |options: &Value| -> Vec> { + match options { + Value::String(s) if s.starts_with('#') => e.tag(s).to_vec(), + Value::String(s) => vec![Arc::from(s.as_str())], + Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(Arc::from)).collect(), + _ => e.list.iter().map(|x| x.id.clone()).collect(), } - let extra = if m["include_additional_cost_component"] - .as_bool() - .unwrap_or(false) - && levels > 0 - { - levels - } else { - 0 - }; - Some((out, extra)) - } - "minecraft:enchant_randomly" => { - let book = &*stack.item == "minecraft:book"; - let only_compatible = m["only_compatible"].as_bool().unwrap_or(true); - let options: Vec> = pool(&m["options"]) - .into_iter() - .filter(|id| book || !only_compatible || e.can_enchant(ctx.items, id, &stack.item)) - .collect(); - if options.is_empty() { - return Some((stack, 0)); + }; + match m["type"].as_str().or(m["function"].as_str()).unwrap_or("") { + "minecraft:enchant_with_levels" => { + let levels = int_provider(&m["levels"], random); + // EnchantmentHelper.enchantItem on the loot context's random. + let chosen = e.select(ctx.items, random, &stack.item, levels, &pool(&m["options"])); + let mut out = if &*stack.item == "minecraft:book" { + ItemStack::new("minecraft:enchanted_book", stack.count) + } else { + stack + }; + for (id, l) in chosen { + out.enchant(&id, l); + } + let extra = if m["include_additional_cost_component"] + .as_bool() + .unwrap_or(false) + && levels > 0 + { + levels + } else { + 0 + }; + Some((out, extra)) } - let id = - options[random.next_int_bound(options.len() as i32).unwrap_or(0) as usize].clone(); - let max = e.get(&id).map_or(1, |d| d.max_level) as i32; - let level = if max <= 1 { - 1 - } else { - 1 + random.next_int_bound(max).unwrap_or(0) - }; - let mut out = if book { - ItemStack::new("minecraft:enchanted_book", 1) - } else { - stack - }; - out.enchant(&id, level as u32); - let extra = if m["include_additional_cost_component"] - .as_bool() - .unwrap_or(false) - { - 2 + random.next_int_bound(5 + level * 10).unwrap_or(0) + 3 * level - } else { - 0 - }; - Some((out, extra)) - } - "minecraft:filtered" => { - let filter = &m["item_filter"]; - let item_ok = filter["items"].as_str().is_none_or(|i| i == &*stack.item); - let needs = - |key: &str, have: bool| filter["predicates"][key].as_array().is_none_or(|_| have); - let ok = item_ok - && needs("minecraft:enchantments", !stack.enchantments().is_empty()) - && needs( - "minecraft:stored_enchantments", - !stack.stored_enchantments().is_empty(), - ); - if ok { - Some((stack, 0)) - } else if m["on_fail"]["type"] == "minecraft:discard" { - None - } else { - Some((stack, 0)) + "minecraft:enchant_randomly" => { + let book = &*stack.item == "minecraft:book"; + let only_compatible = m["only_compatible"].as_bool().unwrap_or(true); + let options: Vec> = pool(&m["options"]) + .into_iter() + .filter(|id| { + book || !only_compatible || e.can_enchant(ctx.items, id, &stack.item) + }) + .collect(); + if options.is_empty() { + return Some((stack, 0)); + } + let id = options[random.next_int_bound(options.len() as i32).unwrap_or(0) as usize] + .clone(); + let max = e.get(&id).map_or(1, |d| d.max_level) as i32; + let level = if max <= 1 { + 1 + } else { + 1 + random.next_int_bound(max).unwrap_or(0) + }; + let mut out = if book { + ItemStack::new("minecraft:enchanted_book", 1) + } else { + stack + }; + out.enchant(&id, level as u32); + let extra = if m["include_additional_cost_component"] + .as_bool() + .unwrap_or(false) + { + 2 + random.next_int_bound(5 + level * 10).unwrap_or(0) + 3 * level + } else { + 0 + }; + Some((out, extra)) } + "minecraft:filtered" => { + let filter = &m["item_filter"]; + let item_ok = filter["items"].as_str().is_none_or(|i| i == &*stack.item); + let needs = |key: &str, have: bool| filter["predicates"].get(key).is_none() || have; + let data = stack.data(); + let ok = item_ok + && needs("minecraft:enchantments", !stack.enchantments().is_empty()) + && needs( + "minecraft:stored_enchantments", + !stack.stored_enchantments().is_empty(), + ) + && needs( + "minecraft:dyed_color", + data.is_some_and(|d| d.dyed_color.is_some()), + ) + && needs("minecraft:map_id", data.is_some_and(|d| d.map_id.is_some())); + if ok { + Some((stack, 0)) + } else if m["on_fail"]["type"] == "minecraft:discard" { + None + } else { + Some((stack, 0)) + } + } + "minecraft:set_potion" => Some(( + stack.with_potion(m["id"].as_str().unwrap_or("minecraft:water")), + 0, + )), + "minecraft:discard" => None, + "minecraft:set_random_dyes" => { + let rolls = int_provider(&m["number_of_dyes"], random); + if rolls <= 0 { + return Some((stack, 0)); + } + let dyes: Vec = (0..rolls) + .map(|_| random.next_int_bound(16).unwrap_or(0) as usize) + .collect(); + // DyedItemColor.applyDyes: one item, the colours mixed in. + let current = stack.data().and_then(|d| d.dyed_color); + let mut out = ItemStack { count: 1, ..stack }; + out.data_mut().dyed_color = Some(crate::crafting::apply_dyes(current, &dyes)); + Some((out, 0)) + } + "minecraft:set_random_potion" => { + let options: Vec = match &m["options"] { + Value::String(s) => match s.strip_prefix('#') { + Some(tag) => self.potion_tags.get(tag).cloned().unwrap_or_default(), + None => vec![s.clone()], + }, + Value::Array(a) => a + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), + _ => vec![], + }; + if options.is_empty() { + return Some((stack, 0)); + } + let pick = random.next_int_bound(options.len() as i32).unwrap_or(0) as usize; + Some((stack.with_potion(&options[pick]), 0)) + } + "minecraft:set_stew_effect" => { + let effects = m["effects"].as_array().cloned().unwrap_or_default(); + if &*stack.item != "minecraft:suspicious_stew" || effects.is_empty() { + return Some((stack, 0)); + } + let entry = + &effects[random.next_int_bound(effects.len() as i32).unwrap_or(0) as usize]; + let effect = entry["type"].as_str().unwrap_or("").to_owned(); + let mut duration = int_provider(&entry["duration"], random); + if !instantaneous(&effect) { + duration *= 20; + } + let mut out = stack; + let d = out.data_mut(); + // SuspiciousStewEffects.withEffectAdded + d.stew_effects.push((Arc::from(effect.as_str()), duration)); + Some((out, 0)) + } + "minecraft:exploration_map" => { + let Some(maps) = ctx.maps else { + return Some((stack, 0)); + }; + let map = ExplorationMap { + destination: m["destination"] + .as_str() + .unwrap_or("#minecraft:on_treasure_maps") + .trim_start_matches('#') + .to_owned(), + decoration: m["decoration"] + .as_str() + .unwrap_or("minecraft:mansion") + .to_owned(), + zoom: m["zoom"].as_u64().unwrap_or(2) as u8, + search_radius: m["search_radius"].as_i64().unwrap_or(50) as i32, + skip_existing_chunks: m["skip_existing_chunks"].as_bool().unwrap_or(true), + }; + Some((maps.exploration_map(stack, &map, ctx.origin), 0)) + } + _ => Some((stack, 0)), } - "minecraft:set_potion" => Some(( - stack.with_potion(m["id"].as_str().unwrap_or("minecraft:water")), - 0, - )), - "minecraft:discard" => None, - // Dyes, stew effects, random potions and exploration maps keep the plain item. - _ => Some((stack, 0)), } } @@ -773,11 +1143,18 @@ mod tests { "minecraft:t/level_1".into(), json!({"amount": 5, "trades": "#minecraft:t/level_1"}), ); - let t = Trades { trades, tags, sets }; + let t = Trades { + trades, + tags, + sets, + potion_tags: HashMap::new(), + }; let ctx = TradeContext { items: &items, enchantments: &e, variant: "minecraft:plains", + origin: [0.0; 3], + maps: None, }; let offers = t.offers_from_set(&ctx, "minecraft:t/level_1", &mut sequence_random(1, "x")); // The desert-only trade is skipped for a plains villager; no duplicates. diff --git a/crates/horizon-client/src/random_sequences.rs b/crates/horizon-client/src/random_sequences.rs index f176f3c22..b37cfa3bc 100644 --- a/crates/horizon-client/src/random_sequences.rs +++ b/crates/horizon-client/src/random_sequences.rs @@ -41,6 +41,14 @@ impl RandomSequences { .entry(id.to_owned()) .or_insert_with(|| create(id, world_seed, salt, w, i)) } + /// Lends sequence `id` out (created if missing); `give_back` returns it. + pub fn lend(&mut self, id: &str, world_seed: i64) -> XoroshiroRandom { + self.get(id, world_seed); + self.sequences.remove(id).expect("created") + } + pub fn give_back(&mut self, id: String, random: XoroshiroRandom) { + self.sequences.insert(id, random); + } pub fn ids(&self) -> Vec { self.sequences.keys().cloned().collect() } diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index dd67312db..d1582a6b8 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -887,6 +887,8 @@ mod tests { items: &items, enchantments: e, variant: "minecraft:plains", + origin: [0.0; 3], + maps: None, }; for p in crate::merchant::PROFESSIONS { let set = crate::merchant::Trades::set_for(p, 1); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java new file mode 100644 index 000000000..e73dae2ea --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java @@ -0,0 +1,624 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import com.mojang.serialization.Lifecycle; +import io.netty.channel.embedded.EmbeddedChannel; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.TreeSet; +import java.util.UUID; +import java.util.function.BooleanSupplier; +import net.minecraft.SystemReport; +import net.minecraft.commands.Commands; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.gametest.framework.GameTestServer; +import net.minecraft.gizmos.GizmoCollector; +import net.minecraft.gizmos.Gizmos; +import net.minecraft.nbt.*; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.Services; +import net.minecraft.server.WorldLoader; +import net.minecraft.server.WorldStem; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.progress.LoggingLevelLoadListener; +import net.minecraft.server.network.CommonListenerCookie; +import net.minecraft.server.notifications.EmptyNotificationService; +import net.minecraft.server.notifications.NotificationManager; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.permissions.LevelBasedPermissionSet; +import net.minecraft.server.permissions.PermissionSet; +import net.minecraft.server.players.NameAndId; +import net.minecraft.server.players.PlayerList; +import net.minecraft.util.ProblemReporter; +import net.minecraft.util.Util; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.util.debugchart.LocalSampleLogger; +import net.minecraft.util.debugchart.SampleLogger; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.RandomSequences; +import net.minecraft.world.clock.WorldClocks; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.ai.gossip.GossipType; +import net.minecraft.world.entity.ai.village.ReputationEventType; +import net.minecraft.world.entity.npc.villager.AbstractVillager; +import net.minecraft.world.entity.npc.villager.Villager; +import net.minecraft.world.entity.npc.villager.VillagerData; +import net.minecraft.world.entity.npc.villager.VillagerProfession; +import net.minecraft.world.entity.npc.villager.VillagerType; +import net.minecraft.world.entity.npc.wanderingtrader.WanderingTrader; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.ContainerInput; +import net.minecraft.world.inventory.MerchantMenu; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.trading.MerchantOffer; +import net.minecraft.world.item.trading.MerchantOffers; +import net.minecraft.world.item.trading.TradeSet; +import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.WorldDimensions; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.levelgen.presets.WorldPresets; +import net.minecraft.world.level.storage.LevelDataAndDimensions; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.PrimaryLevelData; +import net.minecraft.world.level.storage.TagValueOutput; +import net.minecraft.world.phys.AABB; + +/** + * Trading oracle: villagers and wandering traders on a real (headless, flat, structure-free) + * vanilla server level, so exploration maps find nothing and are discarded. + * + *

Each case resets every trade set's random sequence to the case's world seed, then: + *

    + *
  • {@code gen}: villagers reach their levels one by one (updateTrades per level, as + * increaseMerchantCareer does) and wandering traders get their offers, in order; prints each + * one's Offers as saved, then the next int of every trade set sequence.
  • + *
  • {@code price}: a villager's offers after Villager.updateSpecialPrices for a player with + * gossip and Hero of the Village, with uses and demand set first.
  • + *
  • {@code restock}: uses, then Villager.shouldRestock / restock at given game times and days.
  • + *
  • {@code trade}: the player opens the trading screen (mobInteract) and selects offers, + * clicks slots, ticks (the TRADE reputation event) and closes it; the menu, the villager and the + * orbs it drops are printed after each step.
  • + *
  • {@code nbt}: the villager as saved (SNBT), for the Rust side to read and write back.
  • + *
+ * NBT is printed in a canonical form: sorted compound keys, typed numbers, floats as raw bits. + */ +public final class VanillaTradingOracle { + static final List CASES = new ArrayList<>(); + static PrintWriter out; + static Path UNIVERSE; + static final UUID PLAYER_UUID = new UUID(0x1234L, 0x5678L); + + public static void main(String[] args) throws Exception { + for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) { + if (!line.isBlank()) CASES.add(line.trim().split(" ")); + } + out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + Path universe = Path.of(args[2]); + Files.createDirectories(universe); + net.minecraft.SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + Util.startTimerHackThread(); + UNIVERSE = universe; + LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("tradeworld"); + PackRepository packs = ServerPacksSource.createPackRepository(access); + MinecraftServer.spin(thread -> Server.create(thread, access, packs)); + } + + static Field field(Class c, String name) throws Exception { + for (Class k = c; k != null; k = k.getSuperclass()) { + try { + Field f = k.getDeclaredField(name); + f.setAccessible(true); + return f; + } catch (NoSuchFieldException e) { + // keep looking + } + } + throw new NoSuchFieldException(name); + } + + static Method method(Class c, String name, Class... types) throws Exception { + for (Class k = c; k != null; k = k.getSuperclass()) { + try { + Method m = k.getDeclaredMethod(name, types); + m.setAccessible(true); + return m; + } catch (NoSuchMethodException e) { + // keep looking + } + } + throw new NoSuchMethodException(name); + } + + /** Canonical NBT text, the same on both sides. */ + static void canon(Tag t, StringBuilder sb) { + switch (t) { + case CompoundTag c -> { + sb.append('{'); + boolean first = true; + for (String k : new TreeSet<>(c.keySet())) { + if (!first) sb.append(','); + first = false; + quote(k, sb); + sb.append(':'); + canon(c.get(k), sb); + } + sb.append('}'); + } + case ListTag l -> { + sb.append('['); + for (int i = 0; i < l.size(); i++) { + if (i > 0) sb.append(','); + canon(l.get(i), sb); + } + sb.append(']'); + } + case StringTag s -> quote(s.value(), sb); + case ByteTag b -> sb.append(b.value()).append('b'); + case ShortTag s -> sb.append(s.value()).append('s'); + case IntTag i -> sb.append(i.value()); + case LongTag l -> sb.append(l.value()).append('L'); + case FloatTag f -> sb.append("f:").append(Integer.toHexString(Float.floatToRawIntBits(f.value()))); + case DoubleTag d -> sb.append("d:").append(Long.toHexString(Double.doubleToRawLongBits(d.value()))); + case ByteArrayTag a -> { + sb.append("[B;"); + byte[] v = a.getAsByteArray(); + for (int i = 0; i < v.length; i++) sb.append(i > 0 ? "," : "").append(v[i]); + sb.append(']'); + } + case IntArrayTag a -> { + sb.append("[I;"); + int[] v = a.getAsIntArray(); + for (int i = 0; i < v.length; i++) sb.append(i > 0 ? "," : "").append(v[i]); + sb.append(']'); + } + case LongArrayTag a -> { + sb.append("[L;"); + long[] v = a.getAsLongArray(); + for (int i = 0; i < v.length; i++) sb.append(i > 0 ? "," : "").append(v[i]); + sb.append(']'); + } + default -> sb.append("?").append(t.getClass().getSimpleName()); + } + } + + static void quote(String s, StringBuilder sb) { + sb.append('"'); + for (char c : s.toCharArray()) { + if (c == '"' || c == '\\') sb.append('\\'); + sb.append(c); + } + sb.append('"'); + } + + static String canon(Tag t) { + StringBuilder sb = new StringBuilder(); + canon(t, sb); + return sb.toString(); + } + + static final class Server extends MinecraftServer { + // A default world: the vanilla pack and features only (no trade rebalance). + static final FeatureFlagSet FEATURES = FeatureFlags.DEFAULT_FLAGS; + final LocalSampleLogger sampleLogger = new LocalSampleLogger(4); + int phase = 0; + ServerPlayer player; + + static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs) { + try { + packs.reload(); + ArrayList enabled = new ArrayList<>(List.of("vanilla")); + WorldDataConfiguration config = new WorldDataConfiguration(new DataPackConfig(enabled, List.of()), FEATURES); + LevelSettings settings = new LevelSettings("Trade Level", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, true, config); + WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packs, config, false, true); + WorldLoader.InitConfig init = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER); + WorldStem stem = Util.blockUntilDone(executor -> WorldLoader.load(init, context -> { + Registry none = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze(); + WorldDimensions dims = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET) + .getOrThrow(WorldPresets.FLAT).value().createWorldDimensions(); + WorldDimensions.Complete complete = dims.bake(none); + PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle()); + return new WorldLoader.DataLoadOutput<>( + new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(new WorldOptions(0L, false, false), dims)), + complete.dimensionsRegistryAccess()); + }, WorldStem::new, Util.backgroundExecutor(), executor)).get(); + GameRules rules = new GameRules(FEATURES); + rules.set(GameRules.SPAWN_MOBS, false, null); + rules.set(GameRules.SPAWN_MONSTERS, false, null); + rules.set(GameRules.SPAWN_PATROLS, false, null); + rules.set(GameRules.SPAWN_PHANTOMS, false, null); + rules.set(GameRules.SPAWN_WANDERING_TRADERS, false, null); + rules.set(GameRules.SPAWN_WARDENS, false, null); + rules.set(GameRules.ADVANCE_TIME, false, null); + rules.set(GameRules.ADVANCE_WEATHER, false, null); + rules.set(GameRules.RAIDS, false, null); + Field nf = GameTestServer.class.getDeclaredField("NO_SERVICES"); + nf.setAccessible(true); + return new Server(thread, access, packs, stem, rules, (Services) nf.get(null)); + } catch (Exception e) { + e.printStackTrace(); + System.exit(2); + throw new IllegalStateException(e); + } + } + + Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, GameRules rules, Services services) { + super(thread, access, packs, stem, Optional.of(rules), Proxy.NO_PROXY, DataFixers.getDataFixer(), services, + LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager()); + } + + @Override + protected boolean initServer() { + this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) { + @Override + public void broadcast(Player except, double x, double y, double z, double range, ResourceKey dim, Packet packet) { + } + }); + Gizmos.withCollector(GizmoCollector.NOOP); + this.loadLevel(); + return true; + } + + @Override + protected void tickServer(BooleanSupplier haveTime) { + try { + step(haveTime); + } catch (Throwable t) { + t.printStackTrace(); + out.flush(); + System.exit(3); + } + } + + void step(BooleanSupplier haveTime) throws Exception { + ServerLevel level = this.overworld(); + if (phase == 0) { + for (int dx = -1; dx <= 1; dx++) + for (int dz = -1; dz <= 1; dz++) + level.setChunkForced(dx, dz, true); + phase = 1; + super.tickServer(haveTime); + return; + } + super.tickServer(haveTime); + if (!level.isPositionEntityTicking(new BlockPos(0, -60, 0))) return; + for (String[] c : CASES) { + try { + run(c, level); + } catch (Exception e) { + out.println(c[1] + " error " + e); + e.printStackTrace(); + } + } + out.close(); + try (var paths = Files.walk(UNIVERSE)) { + paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); + } catch (Exception e) { + // best effort + } + Runtime.getRuntime().halt(0); + } + + Map kv(String[] c) { + Map m = new HashMap<>(); + for (int i = 2; i < c.length; i++) { + int eq = c[i].indexOf('='); + if (eq > 0) m.merge(c[i].substring(0, eq), c[i].substring(eq + 1), (a, b) -> a + " " + b); + } + return m; + } + + void resetSequences(ServerLevel level, long seed) { + RandomSequences rs = this.getRandomSequences(); + rs.clear(); + level.registryAccess().lookupOrThrow(Registries.TRADE_SET).listElements() + .forEach(h -> h.value().randomSequence().ifPresent(id -> rs.reset(id, seed))); + } + + ServerPlayer player(ServerLevel level) throws Exception { + if (player == null) { + CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(PLAYER_UUID, "horizon-trade"), false); + player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation()); + Connection connection = new Connection(PacketFlow.SERVERBOUND); + new EmbeddedChannel(connection); + this.getPlayerList().placeNewPlayer(connection, player, cookie); + method(player.connection.getClass(), "markClientLoaded").invoke(player.connection); + } + if (player.containerMenu != player.inventoryMenu) player.closeContainer(); + player.getInventory().clearContent(); + player.removeAllEffects(); + player.setGameMode(GameType.SURVIVAL); + player.snapTo(1.5, -60.0, 0.5, 0.0F, 0.0F); + return player; + } + + /** A villager or wandering trader from spec PROF:TYPE:LEVEL or "wt", generated as it levels up. */ + AbstractVillager merchant(ServerLevel level, String spec, double[] at, Long randomSeed) throws Exception { + AbstractVillager v; + if (spec.equals("wt")) { + v = net.minecraft.world.entity.EntityTypes.WANDERING_TRADER.create(level, EntitySpawnReason.COMMAND); + } else { + String[] p = spec.split(":"); + Villager villager = net.minecraft.world.entity.EntityTypes.VILLAGER.create(level, EntitySpawnReason.COMMAND); + Holder type = BuiltInRegistries.VILLAGER_TYPE.getOrThrow( + ResourceKey.create(Registries.VILLAGER_TYPE, Identifier.withDefaultNamespace(p[1]))); + Holder prof = BuiltInRegistries.VILLAGER_PROFESSION.getOrThrow( + ResourceKey.create(Registries.VILLAGER_PROFESSION, Identifier.withDefaultNamespace(p[0]))); + villager.setVillagerData(new VillagerData(type, prof, 1)); + v = villager; + } + v.snapTo(at[0], at[1], at[2], 0.0F, 0.0F); + if (randomSeed != null) field(Entity.class, "random").set(v, new net.minecraft.world.level.levelgen.LegacyRandomSource(randomSeed)); + v.getOffers(); + if (v instanceof Villager villager) { + int max = Integer.parseInt(spec.split(":")[2]); + Method update = method(Villager.class, "updateTrades", ServerLevel.class); + for (int l = 2; l <= max; l++) { + villager.setVillagerData(villager.getVillagerData().withLevel(l)); + update.invoke(villager, level); + } + } + return v; + } + + String offersNbt(ServerLevel level, MerchantOffers offers) { + return canon(MerchantOffers.CODEC.encodeStart(level.registryAccess().createSerializationContext(NbtOps.INSTANCE), offers).getOrThrow()); + } + + String stack(ServerLevel level, ItemStack s) { + if (s.isEmpty()) return "-"; + return canon(ItemStack.CODEC.encodeStart(level.registryAccess().createSerializationContext(NbtOps.INSTANCE), s).getOrThrow()); + } + + double[] origin(Map kv) { + String[] o = kv.getOrDefault("origin", "0.5,-60,0.5").split(","); + return new double[] {Double.parseDouble(o[0]), Double.parseDouble(o[1]), Double.parseDouble(o[2])}; + } + + void run(String[] c, ServerLevel level) throws Exception { + String kind = c[0], name = c[1]; + Map kv = kv(c); + long seed = Long.parseLong(kv.getOrDefault("seed", "0")); + resetSequences(level, seed); + double[] at = origin(kv); + switch (kind) { + case "gen" -> { + int k = 0; + for (String spec : kv.get("v").split(" ")) { + AbstractVillager v = merchant(level, spec, at, null); + out.println(name + " v" + (k++) + " " + offersNbt(level, v.getOffers())); + } + StringBuilder sb = new StringBuilder(name + " draws"); + level.registryAccess().lookupOrThrow(Registries.TRADE_SET).listElements() + .map(h -> h.value().randomSequence()) + .flatMap(Optional::stream) + .map(Identifier::toString) + .sorted() + .forEach(id -> sb.append(' ').append(this.getRandomSequence(Identifier.parse(id)).nextInt())); + out.println(sb); + } + case "price" -> { + Villager v = (Villager) merchant(level, kv.get("v"), at, null); + prepare(v, kv); + ServerPlayer p = player(level); + if (kv.containsKey("hero")) p.addEffect(new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE, 1000, Integer.parseInt(kv.get("hero")))); + method(Villager.class, "updateSpecialPrices", Player.class).invoke(v, p); + StringBuilder sb = new StringBuilder(name + " rep " + v.getPlayerReputation(p)); + for (MerchantOffer o : v.getOffers()) sb.append(' ').append(o.getCostA().getCount()).append('/').append(o.getSpecialPriceDiff()); + out.println(sb); + } + case "restock" -> { + Villager v = (Villager) merchant(level, kv.get("v"), at, null); + prepare(v, kv); + var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD); + int k = 0; + for (String s : kv.getOrDefault("steps", "").split(",")) { + if (s.isEmpty()) continue; + String[] f = s.split(":"); + StringBuilder sb = new StringBuilder(name + " " + (k++) + " " + s); + switch (f[0]) { + case "use" -> { + if (Integer.parseInt(f[1]) >= v.getOffers().size()) break; + MerchantOffer o = v.getOffers().get(Integer.parseInt(f[1])); + for (int n = Integer.parseInt(f[2]); n > 0; n--) o.increaseUses(); + } + case "check" -> { + this.getWorldData().overworldData().setGameTime(Long.parseLong(f[1])); + this.clockManager().setTotalTicks(clock, Long.parseLong(f[2]) * 24000L + 1000L); + boolean should = v.shouldRestock(level); + if (should) v.restock(); + sb.append(' ').append(should); + } + default -> throw new IllegalArgumentException(s); + } + sb.append(" lr ").append(field(Villager.class, "lastRestockGameTime").getLong(v)) + .append(" rt ").append(field(Villager.class, "numberOfRestocksToday").getInt(v)) + .append(" cd ").append(field(Villager.class, "lastRestockCheckDay").getLong(v)); + for (MerchantOffer o : v.getOffers()) sb.append(' ').append(o.getUses()).append('/').append(o.getDemand()); + out.println(sb); + } + } + case "nbt" -> { + AbstractVillager v = merchant(level, kv.get("v"), at, null); + if (v instanceof Villager villager) prepare(villager, kv); + TagValueOutput output = TagValueOutput.createWithContext(ProblemReporter.DISCARDING, level.registryAccess()); + v.saveWithoutId(output); + CompoundTag tag = output.buildResult(); + out.println(name + " snbt " + tag); + CompoundTag kept = new CompoundTag(); + for (String key : List.of("Offers", "Xp", "LastRestock", "RestocksToday", "VillagerData")) { + if (tag.contains(key)) kept.put(key, tag.get(key)); + } + out.println(name + " canon " + canon(kept)); + } + case "trade" -> trade(name, kv, level, at); + default -> throw new IllegalArgumentException(kind); + } + } + + /** Uses, demand, xp, gossip and restock state set on a villager before a case runs. */ + void prepare(Villager v, Map kv) throws Exception { + for (String key : List.of("uses", "demand")) { + if (!kv.containsKey(key)) continue; + for (String s : kv.get(key).split(" ")) { + String[] f = s.split(":"); + // Offers past the end are skipped. + if (Integer.parseInt(f[0]) >= v.getOffers().size()) continue; + MerchantOffer o = v.getOffers().get(Integer.parseInt(f[0])); + if (key.equals("uses")) { + for (int n = Integer.parseInt(f[1]); n > 0; n--) o.increaseUses(); + } else { + field(MerchantOffer.class, "demand").setInt(o, Integer.parseInt(f[1])); + } + } + } + if (kv.containsKey("gossip")) { + for (String s : kv.get("gossip").split(" ")) { + String[] f = s.split(":"); + v.getGossips().add(PLAYER_UUID, GossipType.valueOf(f[0].toUpperCase(java.util.Locale.ROOT)), Integer.parseInt(f[1])); + } + } + if (kv.containsKey("xp")) v.setVillagerXp(Integer.parseInt(kv.get("xp"))); + if (kv.containsKey("lastrestock")) field(Villager.class, "lastRestockGameTime").setLong(v, Long.parseLong(kv.get("lastrestock"))); + if (kv.containsKey("restocks")) field(Villager.class, "numberOfRestocksToday").setInt(v, Integer.parseInt(kv.get("restocks"))); + } + + void trade(String name, Map kv, ServerLevel level, double[] at) throws Exception { + long vseed = Long.parseLong(kv.getOrDefault("vseed", "0")); + AbstractVillager v = merchant(level, kv.get("v"), at, vseed); + if (v instanceof Villager villager) prepare(villager, kv); + level.addFreshEntity(v); + ServerPlayer p = player(level); + if (kv.containsKey("hero")) p.addEffect(new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE, 1000, Integer.parseInt(kv.get("hero")))); + if (kv.containsKey("inv")) { + for (String s : kv.get("inv").split(",")) { + // SLOT:ITEM*COUNT + String[] f = s.split(":", 2); + String[] ic = f[1].split("\\*"); + p.getInventory().setItem(Integer.parseInt(f[0]), new ItemStack( + BuiltInRegistries.ITEM.getValue(Identifier.parse(ic[0].contains(":") ? ic[0] : "minecraft:" + ic[0])), Integer.parseInt(ic[1]))); + } + } + p.getInventory().setSelectedSlot(Integer.parseInt(kv.getOrDefault("hand", "8"))); + var result = v.interact(p, InteractionHand.MAIN_HAND, p.position()); + out.println(name + " open " + (p.containerMenu instanceof MerchantMenu) + " unhappy " + v.getUnhappyCounter()); + int k = 0; + for (String s : kv.getOrDefault("steps", "").split(",")) { + if (s.isEmpty()) continue; + String[] f = s.split(":"); + switch (f[0]) { + case "select" -> { + if (p.containerMenu instanceof MerchantMenu menu && menu.stillValid(p)) { + menu.setSelectionHint(Integer.parseInt(f[1])); + menu.tryMoveItems(Integer.parseInt(f[1])); + } + } + case "click" -> p.containerMenu.clicked(Integer.parseInt(f[1]), Integer.parseInt(f[2]), + ContainerInput.valueOf(f[3].toUpperCase(java.util.Locale.ROOT)), p); + case "tick" -> { + // Villager.customServerAiStep: the TRADE reputation event of the last trade. + if (v instanceof Villager villager) { + Field last = field(Villager.class, "lastTradedPlayer"); + Object who = last.get(villager); + if (who != null) { + level.onReputationEvent(ReputationEventType.TRADE, (Entity) who, villager); + last.set(villager, null); + } + } + } + case "close" -> p.closeContainer(); + default -> throw new IllegalArgumentException(s); + } + StringBuilder sb = new StringBuilder(name + " " + (k++) + " " + s); + var menu = p.containerMenu; + sb.append(" menu ").append(menu instanceof MerchantMenu); + if (menu instanceof MerchantMenu mm) { + for (int i = 0; i < 3; i++) sb.append(' ').append(stack(level, mm.getSlot(i).getItem())); + sb.append(" fxp ").append(mm.getFutureTraderXp()); + } + sb.append(" carried ").append(stack(level, menu.getCarried())); + sb.append(" inv"); + for (int i = 0; i < 36; i++) { + ItemStack st = p.getInventory().getItem(i); + if (!st.isEmpty()) sb.append(' ').append(i).append('=').append(stack(level, st)); + } + sb.append(" xp ").append(v.getVillagerXp()); + if (v instanceof Villager villager) { + sb.append(" lvl ").append(villager.getVillagerData().level()) + .append(" rep ").append(villager.getPlayerReputation(p)) + .append(" regen ").append(villager.hasEffect(MobEffects.REGENERATION)); + } + sb.append(" offers"); + for (MerchantOffer o : v.getOffers()) { + sb.append(' ').append(o.getUses()).append('/').append(o.getSpecialPriceDiff()).append('/').append(o.getCostA().getCount()); + } + sb.append(" orbs"); + for (ExperienceOrb orb : level.getEntitiesOfClass(ExperienceOrb.class, new AABB(at[0] - 8, at[1] - 8, at[2] - 8, at[0] + 8, at[1] + 8, at[2] + 8))) { + sb.append(' ').append(orb.getValue()); + orb.discard(); + } + out.println(sb); + } + out.println(name + " next " + ((net.minecraft.util.RandomSource) field(Entity.class, "random").get(v)).nextInt()); + if (p.containerMenu != p.inventoryMenu) p.closeContainer(); + v.discard(); + } + + @Override protected SampleLogger getTickTimeLogger() { return sampleLogger; } + @Override public boolean isTickTimeLoggingEnabled() { return false; } + @Override protected void waitUntilNextTick() { this.runAllTasks(); } + @Override public SystemReport fillServerSystemReport(SystemReport report) { report.setDetail("Type", "Trading oracle"); return report; } + @Override protected void onServerExit() { super.onServerExit(); System.exit(0); } + @Override protected void onServerCrash(net.minecraft.CrashReport report) { super.onServerCrash(report); System.exit(1); } + @Override public boolean isHardcore() { return false; } + @Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.ALL; } + @Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.OWNER; } + @Override public boolean shouldRconBroadcast() { return false; } + @Override public boolean isDedicatedServer() { return false; } + @Override public int getRateLimitPacketsPerSecond() { return 0; } + @Override public int getCommandSpamThresholdSeconds() { return 0; } + @Override public int getChatSpamThresholdSeconds() { return 0; } + @Override public boolean useNativeTransport() { return false; } + @Override public boolean isPublished() { return false; } + @Override public boolean shouldInformAdmins() { return false; } + @Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return false; } + @Override public int getMaxPlayers() { return 1; } + } +} diff --git a/tools/test_trading_parity.py b/tools/test_trading_parity.py new file mode 100644 index 000000000..2f66362fc --- /dev/null +++ b/tools/test_trading_parity.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""Compare villager and wandering trader trading with vanilla. + +Java (VanillaTradingOracle) runs vanilla's villagers, wandering traders and +MerchantMenu on a real flat server level; Rust (trading_fixture) runs +horizon_client::merchant and the merchant kind of horizon_client::menu on the +same cases: + +- gen: offers of every profession at every level and villager type, and of + wandering traders, generated from the world's trade set random sequences + (several merchants per world share them), as saved (Offers NBT), then the + next draw of every sequence; +- price: Villager.updateSpecialPrices under gossip (reputation) and Hero of + the Village, with uses and demand; +- restock: Villager.shouldRestock / restock over simulated game times and days + (twice a day, demand catch-up); +- trade: opening the trading screen, selecting offers (tryMoveItems), clicks + on the payment and result slots (pickup, shift-click, swap), the TRADE + reputation event, closing: the menu and inventory, the villager's experience, + level-ups with their new offers and regeneration, offer uses and prices, the + experience orbs and the merchant's random; +- nbt: villagers and wandering traders saved by vanilla, read and written back + (Offers, Xp, VillagerData, LastRestock, RestocksToday). + +Every line of both outputs must match. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +PROFESSIONS = ['armorer', 'butcher', 'cartographer', 'cleric', 'farmer', 'fisherman', 'fletcher', 'leatherworker', + 'librarian', 'mason', 'shepherd', 'toolsmith', 'weaponsmith'] +TYPES = ['desert', 'jungle', 'plains', 'savanna', 'snow', 'swamp', 'taiga'] +GOSSIP = ['major_negative', 'minor_negative', 'minor_positive', 'major_positive', 'trading'] + + +def wanted(resources): + """Items each profession's trades ask for (any level), and the wandering trader's.""" + root = resources / 'data/minecraft/villager_trade' + out = {} + for d in sorted(root.iterdir()): + items = set() + for f in d.rglob('*.json'): + t = json.loads(f.read_text()) + for k in ('wants', 'additional_wants'): + if k in t and 'components' not in t[k]: + items.add(t[k]['id']) + out[d.name] = sorted(items) + return out + + +def spec(rng, level=None): + prof = rng.choice(PROFESSIONS + ['none', 'nitwit'] if rng.random() < 0.05 else PROFESSIONS) + return f'{prof}:{rng.choice(TYPES)}:{level or rng.randint(1, 5)}' + + +def corpus(wants): + rng = random.Random(0x5452414445) + cases = [] + seeds = [0, 1, -1, 12345, -9223372036854775808, 9223372036854775807] + n = 0 + # Every profession, type and level, alone in its world. + for prof in PROFESSIONS: + for t in TYPES: + for seed in seeds[:3] + [rng.randrange(-2**63, 2**63)]: + cases.append(f'gen g{n} seed={seed} v={prof}:{t}:5') + n += 1 + for k in range(int(os.environ.get('TRADING_GEN', '1500'))): + merchants = [('wt' if rng.random() < 0.15 else spec(rng)) for _ in range(rng.randint(1, 6))] + cases.append(f'gen g{n} seed={rng.randrange(-2**63, 2**63)} ' + ' '.join(f'v={m}' for m in merchants)) + n += 1 + for k in range(int(os.environ.get('TRADING_PRICE', '1000'))): + kv = [f'seed={rng.randrange(-2**63, 2**63)}', f'v={spec(rng)}'] + for _ in range(rng.choice([0, 1, 1, 2, 3])): + kv.append(f'gossip={rng.choice(GOSSIP)}:{rng.choice([1, 5, 20, 25, 50, 100, rng.randint(1, 200)])}') + if rng.random() < 0.4: + kv.append(f'hero={rng.choice([0, 0, 1, 2, 4, 9])}') + for _ in range(rng.choice([0, 0, 1, 2])): + kv.append(f'uses={rng.randrange(4)}:{rng.randint(1, 16)}') + for _ in range(rng.choice([0, 0, 1, 2])): + kv.append(f'demand={rng.randrange(4)}:{rng.randint(-20, 40)}') + cases.append(f'price p{k} ' + ' '.join(kv)) + for k in range(int(os.environ.get('TRADING_RESTOCK', '600'))): + steps, time, day = [], rng.choice([0, 100, 24000, 500000]), rng.randint(0, 3) + for _ in range(rng.randint(3, 14)): + if rng.random() < 0.45: + steps.append(f'use:{rng.randrange(2)}:{rng.randint(1, 12)}') + else: + time += rng.choice([1, 100, 2399, 2401, 3000, 6000, 12000, 12001, 24000, 30000]) + if rng.random() < 0.4: + day += rng.choice([1, 1, 2]) + steps.append(f'check:{time}:{day}') + kv = [f'seed={rng.randrange(-2**63, 2**63)}', f'v={spec(rng)}', f'steps={",".join(steps)}'] + if rng.random() < 0.3: + kv.append(f'restocks={rng.randrange(3)}') + if rng.random() < 0.3: + kv.append(f'lastrestock={rng.randrange(0, 40000)}') + cases.append(f'restock r{k} ' + ' '.join(kv)) + for k in range(int(os.environ.get('TRADING_TRADE', '1500'))): + wt = rng.random() < 0.12 + m = 'wt' if wt else spec(rng, rng.choice([1, 1, 2, 3, 4, 5])) + prof = 'wandering_trader' if wt else m.split(':')[0] + pool = wants.get(prof, []) + ['minecraft:emerald'] * 4 + inv, used = [], set() + for _ in range(rng.randint(2, 10)): + slot = rng.randrange(36) + if slot in used or slot == 8: + continue + used.add(slot) + item = rng.choice(pool) + inv.append(f'{slot}:{item}*{rng.choice([1, 5, 16, 32, 64, 64, rng.randint(1, 64)])}') + steps = [] + for _ in range(rng.randint(2, 12)): + r = rng.random() + if r < 0.3: + steps.append(f'select:{rng.randrange(8)}') + elif r < 0.45: + steps.append('click:2:0:quick_move') + elif r < 0.55: + steps.append('click:2:0:pickup') + elif r < 0.65: + steps.append(f'click:{rng.randrange(3, 39)}:0:pickup') + elif r < 0.72: + steps.append(f'click:{rng.choice([0, 1])}:{rng.choice([0, 1])}:pickup') + elif r < 0.78: + steps.append(f'click:{rng.choice([0, 1, 2])}:0:quick_move') + elif r < 0.82: + steps.append(f'click:{rng.choice([0, 1, 2, rng.randrange(3, 39)])}:{rng.randrange(9)}:swap') + elif r < 0.92: + steps.append('tick') + else: + steps.append(f'click:{rng.randrange(3, 39)}:0:quick_move') + if rng.random() < 0.3: + steps.append('close') + if prof in ('none', 'nitwit'): + # No offers: the screen stays shut (the player's own menu is not modelled). + steps = [] + kv = [f'seed={rng.randrange(-2**63, 2**63)}', f'vseed={rng.randrange(-2**47, 2**47)}', f'v={m}', + f'inv={",".join(inv)}' if inv else 'inv=0:minecraft:dirt*1', f'steps={",".join(steps)}'] + if not wt and rng.random() < 0.4: + level = int(m.split(':')[2]) + lo, hi = [0, 10, 70, 150, 250, 250][level - 1], [10, 70, 150, 250, 250, 260][level - 1] + kv.append(f'xp={rng.choice([lo, max(lo, hi - 1), max(lo, hi - 5), rng.randint(lo, hi)])}') + if not wt and rng.random() < 0.3: + kv.append(f'gossip={rng.choice(GOSSIP)}:{rng.randint(1, 100)}') + if rng.random() < 0.15: + kv.append(f'hero={rng.randrange(3)}') + cases.append(f'trade t{k} ' + ' '.join(kv)) + for k in range(int(os.environ.get('TRADING_NBT', '400'))): + m = 'wt' if rng.random() < 0.1 else spec(rng) + kv = [f'seed={rng.randrange(-2**63, 2**63)}', f'v={m}'] + if m != 'wt': + for _ in range(rng.choice([0, 1, 2])): + kv.append(f'uses={rng.randrange(2)}:{rng.randint(1, 16)}') + if rng.random() < 0.5: + kv.append(f'demand=0:{rng.randint(-10, 30)}') + if rng.random() < 0.5: + kv.append(f'xp={rng.randint(0, 260)}') + if rng.random() < 0.5: + kv.append(f'lastrestock={rng.randrange(0, 10**6)}') + kv.append(f'restocks={rng.randrange(3)}') + cases.append(f'nbt n{k} ' + ' '.join(kv)) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + parser.add_argument('--java-only', action='store_true', help='run the oracle and stop') + args = parser.parse_args() + build = lab.LOCAL / 'rust-trading-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/trading_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/merchant.rs', lab.ROOT / 'crates/horizon-client/src/menu.rs'] + tested = base.source_hashes([s for s in sources if s.exists()]) + inputs = build / 'inputs.txt' + cases = corpus(wanted(resources)) + inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + path = build / (name + '.log') + with path.open('w', encoding='utf-8') as log: + try: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError: + log.flush() + raise SystemExit(f'{name} failed:\n' + path.read_text(errors='replace')[-4000:]) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + universe = build / 'universe' + stamp = build / 'server.inputs' + reuse = (os.environ.get('TRADING_REUSE') and stamp.exists() and (build / 'server.txt').exists() + and stamp.read_text() == inputs.read_text()) + if not reuse: + run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaTradingOracle', inputs, build / 'server.txt', universe], 'server') + stamp.write_text(inputs.read_text()) + vanilla = (build / 'server.txt').read_text().splitlines() + errors = [l for l in vanilla if ' error ' in l] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + if args.java_only: + print(f'{len(vanilla)} oracle lines') + return + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'trading_fixture'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/trading_fixture' + run([binary, resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') + rust = (build / 'rust.txt').read_text().splitlines() + bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] + if bad or len(vanilla) != len(rust): + report = '\n'.join(f' vanilla {a[:1500]}\n rust {b[:1500]}' for a, b in bad[:10]) + raise SystemExit(f'{len(bad)} of {len(vanilla)} lines differ (rust {len(rust)} lines):\n{report}') + base.ensure_sources_unchanged([s for s in sources if s.exists()], tested) + kinds = {} + for c in cases: + kinds[c.split()[0]] = kinds.get(c.split()[0], 0) + 1 + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': kinds, + 'lines': len(vanilla), 'sources_sha256': tested, + 'scope': 'AbstractVillager.addOffersFromTradeSet over the trade_set / villager_trade registries and their ' + 'random sequences, VillagerTrade.getOffer with its item modifiers, Villager.updateSpecialPrices, ' + 'shouldRestock / restock / catchUpDemand, MerchantMenu (tryMoveItems, the result slot, quick move), ' + 'notifyTrade / rewardTradeXp with level-ups, and the Offers / Xp / LastRestock / RestocksToday NBT.'}) + print(f'{len(cases):,} trading cases match vanilla ({len(vanilla):,} lines: {kinds})') + + +if __name__ == '__main__': + main()