Add villager trading: data-driven offers, merchant pricing and the trading menu

Offers come from the trade_set/villager_trade registries through each
set's RandomSequence (world seed + sequence id), with merchant predicates,
enchant_with_levels/enchant_randomly/filtered/set_potion modifiers and the
additional trade cost. MerchantOffer pricing (demand, price multiplier,
special price), payment matching and stock follow vanilla; the trading menu
matches MerchantScreen and levels the merchant up with new offers.
horizon-ctl 'trade PROFESSION [LEVEL]' opens it until villagers exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:39:08 +02:00
parent 61c803095e
commit 708451f28d
9 changed files with 830 additions and 6 deletions
+4 -4
View File
@@ -279,7 +279,7 @@ impl Enchantments {
// ---- Enchanting table (EnchantmentHelper) ----
/// `EnchantmentHelper.getEnchantmentCost`.
pub fn enchantment_cost(&self, random: &mut LegacyRandom, slot: usize, bookcases: i32, item: &str) -> i32 {
pub fn enchantment_cost<R: RandomSource>(&self, random: &mut R, slot: usize, bookcases: i32, item: &str) -> i32 {
if self.enchantable(item) == 0 {
return 0;
}
@@ -309,7 +309,7 @@ impl Enchantments {
}
out
}
fn weighted(&self, random: &mut LegacyRandom, list: &[(Arc<str>, u32)]) -> Option<(Arc<str>, u32)> {
fn weighted<R: RandomSource>(&self, random: &mut R, list: &[(Arc<str>, u32)]) -> Option<(Arc<str>, u32)> {
let total: i32 = list.iter().map(|(id, _)| self.get(id).map_or(0, |e| e.weight as i32)).sum();
if total <= 0 {
return None;
@@ -324,7 +324,7 @@ impl Enchantments {
None
}
/// `EnchantmentHelper.selectEnchantment`.
pub fn select(&self, items: &Items, random: &mut LegacyRandom, item: &str, cost: i32, pool: &[Arc<str>]) -> Vec<(Arc<str>, u32)> {
pub fn select<R: RandomSource>(&self, items: &Items, random: &mut R, item: &str, cost: i32, pool: &[Arc<str>]) -> Vec<(Arc<str>, u32)> {
let mut results = Vec::new();
let value = self.enchantable(item) as i32;
if value == 0 {
@@ -482,7 +482,7 @@ pub struct EffectContext<'a> {
pub attacker: Option<&'a str>,
pub direct_attacker: Option<&'a str>,
}
fn next_int(random: &mut LegacyRandom, bound: i32) -> i32 {
fn next_int<R: RandomSource>(random: &mut R, bound: i32) -> i32 {
random.next_int_bound(bound.max(1)).unwrap_or(0)
}
/// `LevelBasedValue.calculate`.
+1
View File
@@ -5,6 +5,7 @@ mod enchant_effects;
mod potions;
mod station_control;
mod stations;
mod trading;
use horizon_client::{
Result,
assets::Assets,
@@ -31,6 +31,8 @@ pub(super) struct PotionState {
pub(super) burning: Vec<(u32, i32)>,
/// Enchantment attribute modifiers on the player: (attribute, id, amount, operation).
pub(super) enchant_modifiers: Vec<(String, String, f64, String)>,
/// The level's trade-set `RandomSequence`s, by sequence id.
pub(super) trade_randoms: std::collections::HashMap<String, horizon_core::random::XoroshiroRandom>,
}
impl Game<'_> {
@@ -16,6 +16,7 @@ pub(super) const HELP: &[&str] = &[
"menu JSON dump of the open menu, carried stack and inventory",
"effect ID SECONDS [AMPLIFIER] give a status effect (effect clear removes all)",
"effects list active status effects",
"trade PROFESSION [LEVEL] [TYPE] open a villager trading menu (offers from the world's trade sequences)",
"close close the open menu",
];
fn id(name: &str) -> String {
@@ -151,6 +152,16 @@ impl Game<'_> {
self.potions.effects.add(horizon_client::effects::EffectInstance::new(def.id, seconds * 20, amp));
ok()
}
"trade" => {
let profession = arg(1)?.trim_start_matches("minecraft:").to_owned();
if !horizon_client::merchant::PROFESSIONS.contains(&profession.as_str()) {
return Err(format!("unknown profession {profession}").into());
}
let level: i32 = words.get(2).map_or(Ok(1), |l| l.parse())?;
let variant = id(words.get(3).copied().unwrap_or("plains"));
self.open_merchant(&profession, &variant, level);
ok()
}
"effects" => Ok(Some(json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }))),
"close" => {
self.close_container();
+27 -1
View File
@@ -26,6 +26,8 @@ pub(super) enum Kind {
Grindstone,
Smithing,
Stonecutter,
/// Villager trading (game/trading.rs).
Merchant,
}
impl Kind {
fn from_block(name: &str) -> Option<Self> {
@@ -52,6 +54,7 @@ impl Kind {
Self::Grindstone => "gui/container/grindstone",
Self::Smithing => "gui/container/smithing",
Self::Stonecutter => "gui/container/stonecutter",
Self::Merchant => "gui/container/villager",
}
}
fn title_key(self) -> &'static str {
@@ -61,6 +64,7 @@ impl Kind {
Self::Grindstone => "container.grindstone_title",
Self::Smithing => "container.upgrade",
Self::Stonecutter => "container.stonecutter",
Self::Merchant => "merchant.trades",
}
}
/// (titleLabelX, titleLabelY).
@@ -79,6 +83,7 @@ impl Kind {
Self::Grindstone => &[(49.0, 19.0), (49.0, 40.0)],
Self::Smithing => &[(8.0, 48.0), (26.0, 48.0), (44.0, 48.0)],
Self::Stonecutter => &[(20.0, 33.0)],
Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)],
};
table[i.min(table.len() - 1)]
}
@@ -89,6 +94,7 @@ impl Kind {
Self::Grindstone => Some((129.0, 34.0)),
Self::Smithing => Some((98.0, 48.0)),
Self::Stonecutter => Some((143.0, 33.0)),
Self::Merchant => Some((170.0, 37.0)),
}
}
}
@@ -97,7 +103,7 @@ pub(super) struct Station {
pub(super) kind: Kind,
pub(super) pos: [i32; 3],
pub(super) inputs: Vec<Option<ItemStack>>,
result: Option<ItemStack>,
pub(super) result: Option<ItemStack>,
offers: EnchantOffers,
bookcases: i32,
anvil: AnvilResult,
@@ -111,6 +117,8 @@ pub(super) struct Station {
/// Anvil: the input the rename box was last filled from.
anvil_last: Option<ItemStack>,
last_sound: u64,
/// Villager trading state.
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
}
impl Station {
fn new(kind: Kind, pos: [i32; 3]) -> Self {
@@ -129,8 +137,12 @@ impl Station {
input_item: None,
anvil_last: None,
last_sound: 0,
merchant: None,
}
}
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
Self::new(kind, pos)
}
}
/// The 108x19 enchantment button `i` (relative to the GUI origin).
@@ -195,6 +207,9 @@ impl Game<'_> {
return Some([(56.0, 51.0), (79.0, 58.0), (102.0, 51.0), (79.0, 17.0), (17.0, 17.0)][i - 300]);
}
let s = self.station.as_ref()?;
if s.kind == Kind::Merchant && i < 36 {
return Some(super::trading::inventory_slot(i));
}
match i {
RESULT => s.kind.result_pos(),
_ if i >= INPUT && i < INPUT + s.inputs.len() => Some(s.kind.input_pos(i - INPUT)),
@@ -253,6 +268,7 @@ impl Game<'_> {
Kind::Smithing => {
s.result = data.recipes.smithing_result(&data.enchantments, s.inputs[0].as_ref(), s.inputs[1].as_ref(), s.inputs[2].as_ref());
}
Kind::Merchant => super::trading::update(&mut s, items),
Kind::Stonecutter => {
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
if item != s.input_item {
@@ -430,6 +446,7 @@ impl Game<'_> {
moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false);
}
}
Some(Kind::Merchant) => {}
Some(Kind::Smithing) | Some(Kind::Anvil) | Some(Kind::Stonecutter) => {
let n = self.station.as_ref().map_or(0, |s| s.inputs.len());
let inputs: Vec<usize> = (0..n).map(|i| INPUT + i).collect();
@@ -565,6 +582,7 @@ impl Game<'_> {
self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0);
}
}
Kind::Merchant => self.merchant_take(&mut s),
Kind::Enchanting => {}
}
self.station = Some(s);
@@ -647,6 +665,9 @@ impl Game<'_> {
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
let shift = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) || self.keys.contains(&winit::keyboard::KeyCode::ShiftRight);
if let Some(kind) = self.station.as_ref().map(|s| s.kind) {
if kind == Kind::Merchant && !right && self.merchant_click(local) {
return true;
}
if kind == Kind::Enchanting && !right {
for i in 0..3 {
let (x, y, w, h) = enchant_button(i);
@@ -705,6 +726,7 @@ impl Game<'_> {
self.station_changed();
}
pub(super) fn station_scroll(&mut self, d: f32) {
self.merchant_scroll(d);
let Some(s) = self.station.as_mut() else { return };
if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 {
return;
@@ -793,6 +815,9 @@ impl Game<'_> {
}
/// Draws the open station or brewing stand screen; false when none is open.
pub(super) fn draw_station(&mut self, batch: &mut HudBatch) -> bool {
if self.station.as_ref().is_some_and(|s| s.kind == Kind::Merchant) {
return self.draw_merchant(batch);
}
let brewing = self.brewing_open();
if self.station.is_none() && !brewing {
return false;
@@ -963,6 +988,7 @@ impl Game<'_> {
}
}
}
Kind::Merchant => {}
Kind::Stonecutter => {
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
let active = display && s.recipes.len() > 12;
+311
View File
@@ -0,0 +1,311 @@
//! The merchant (villager trading) menu: `MerchantMenu` / `MerchantScreen`
//! layout (276x166, drawn 50 px left of the usual 176-wide origin), offer
//! buttons, payment slots, the result slot's `onTake`, villager experience and
//! level-ups with new offers from the next trade set.
use super::{
Game,
stations::{INPUT, Kind, RESULT, Station},
};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
merchant::{self, MerchantOffer, TradeContext},
};
use horizon_core::random::RandomSource;
/// The merchant screen is 100 px wider than the 176-px menus it shares an origin with.
const SHIFT: f32 = -50.0;
const GREY: u32 = 0xFF40_4040;
pub(super) struct MerchantState {
pub(super) profession: String,
pub(super) variant: String,
pub(super) level: i32,
pub(super) xp: i32,
pub(super) offers: Vec<MerchantOffer>,
/// `shopItem` / selection hint, scroll offset, and the active offer.
pub(super) shop_item: usize,
pub(super) scroll: usize,
pub(super) active: Option<usize>,
pub(super) future_xp: i32,
/// The offer button that keeps focus after a click (drawn highlighted).
pub(super) focused: Option<usize>,
}
/// Player inventory slot positions in `MerchantMenu` (x from 108).
pub(super) fn inventory_slot(i: usize) -> (f32, f32) {
match i {
0..9 => (108.0 + SHIFT + i as f32 * 18.0, 142.0),
_ => (108.0 + SHIFT + ((i - 9) % 9) as f32 * 18.0, 84.0 + ((i - 9) / 9) as f32 * 18.0),
}
}
/// `MerchantContainer.updateSellItem`.
pub(super) fn update(s: &mut Station, items: &horizon_client::items::Items) {
let Some(m) = s.merchant.as_mut() else { return };
let (active, result) = merchant::sell_item(&m.offers, items, s.inputs[0].as_ref(), s.inputs[1].as_ref(), Some(m.shop_item));
m.active = active;
m.future_xp = if result.is_some() { active.map_or(0, |i| m.offers[i].xp) } else { 0 };
s.result = result;
}
impl Game<'_> {
/// Offers a villager of `profession` gets on reaching `level`.
fn new_offers(&mut self, profession: &str, variant: &str, level: i32) -> Vec<MerchantOffer> {
let set = merchant::Trades::set_for(profession, level);
let sequence = format!("minecraft:trade_set/{}", set.trim_start_matches("minecraft:"));
let random = self.potions.trade_randoms.entry(sequence.clone()).or_insert_with(|| merchant::sequence_random(self.level.seed, &sequence));
let ctx = TradeContext { items: &self.res.items, enchantments: &self.res.stations.enchantments, variant };
self.res.stations.trades.offers_from_set(&ctx, &set, random)
}
/// Opens a merchant menu for a villager (or a generated one for tests).
pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) {
let mut offers = Vec::new();
for l in 1..=level.clamp(1, 5) {
offers.extend(self.new_offers(profession, variant, l));
}
let mut s = Station::new_kind(Kind::Merchant, [0, 0, 0]);
s.merchant = Some(Box::new(MerchantState {
profession: profession.trim_start_matches("minecraft:").to_owned(),
variant: variant.to_owned(),
level: level.clamp(1, 5),
xp: merchant::min_xp(level.clamp(1, 5)),
offers,
shop_item: 0,
scroll: 0,
active: None,
future_xp: 0,
focused: None,
}));
self.station = Some(s);
self.screen = super::Screen::Inventory;
self.capture(false);
self.right = false;
}
/// `MerchantResultSlot.onTake` and `Villager.notifyTrade` / `rewardTradeXp`.
pub(super) fn merchant_take(&mut self, s: &mut Station) {
let items = &self.res.items;
let Some(m) = s.merchant.as_mut() else { return };
let Some(i) = m.active else { return };
let offer = m.offers[i].clone();
let (mut a, mut b) = (s.inputs[0].take(), s.inputs[1].take());
let took = offer.take(items, &mut a, &mut b) || offer.take(items, &mut b, &mut a);
s.inputs[0] = a;
s.inputs[1] = b;
if !took {
return;
}
m.offers[i].uses += 1;
let mut pop = 3 + self.world.random.next_int_bound(4).unwrap_or(0);
m.xp += offer.xp;
let level_up = merchant::can_level_up(m.level) && m.xp >= merchant::max_xp(m.level);
let at = self.player.as_ref().map(|p| [p.position.x, p.position.y + 0.5, p.position.z]);
self.audio.play("minecraft:entity.villager.yes", at, 1.0, 1.0);
if level_up {
let (profession, variant, level) = (m.profession.clone(), m.variant.clone(), m.level + 1);
m.level = level;
let more = self.new_offers(&profession, &variant, level);
if let Some(m) = s.merchant.as_mut() {
m.offers.extend(more);
}
pop += 5;
}
if offer.reward_exp
&& let Some(at) = at
{
self.spawn_orbs(at, pop as u32);
}
}
/// `MerchantMenu.tryMoveItems`: return payment, then fill it for the selected offer.
fn try_move_items(&mut self, index: usize) {
let Some(s) = self.station.as_mut() else { return };
let returned: Vec<ItemStack> = s.inputs.iter_mut().filter_map(Option::take).collect();
for stack in returned {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
}
}
let Some(offer) = self.station.as_ref().and_then(|s| s.merchant.as_ref()).and_then(|m| m.offers.get(index)).cloned() else { return };
let wants = [Some(offer.cost_a(&self.res.items)), offer.cost_b()];
for (slot, want) in wants.into_iter().enumerate() {
let Some(want) = want else { continue };
let max = self.res.items.get(&want.item).map_or(64, |i| i.max_stack);
let mut gathered: Option<ItemStack> = None;
for i in (9..36).chain(0..9) {
let Some(s) = self.inventory[i].as_mut() else { continue };
if !s.same_item_same_components(&ItemStack { count: s.count, ..want.clone() }) {
continue;
}
let have = gathered.as_ref().map_or(0, |g| g.count);
let n = s.count.min(max - have);
if n == 0 {
break;
}
s.count -= n;
let taken = ItemStack { count: n, ..s.clone() };
if s.count == 0 {
self.inventory[i] = None;
}
match gathered.as_mut() {
Some(g) => g.count += n,
None => gathered = Some(taken),
}
}
if let Some(st) = self.station.as_mut() {
st.inputs[slot] = gathered;
}
}
}
/// Clicks on the offer list; true when one was hit.
pub(super) fn merchant_click(&mut self, local: (f32, f32)) -> bool {
let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { return false };
for i in 0..7 {
let (x, y) = (5.0 + SHIFT, 18.0 + 20.0 * i as f32);
if local.0 >= x && local.0 < x + 88.0 && local.1 >= y && local.1 < y + 20.0 && i + m.scroll < m.offers.len() {
let index = i + m.scroll;
if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) {
m.shop_item = index;
m.focused = Some(i);
}
self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.try_move_items(index);
self.station_changed();
return true;
}
}
false
}
pub(super) fn merchant_scroll(&mut self, d: f32) {
let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) else { return };
if m.offers.len() > 7 {
let max = m.offers.len() - 7;
m.scroll = (m.scroll as i32 - d.signum() as i32).clamp(0, max as i32) as usize;
}
}
/// `MerchantScreen` rendering.
pub(super) fn draw_merchant(&mut self, batch: &mut HudBatch) -> bool {
let (ox, oy) = self.inventory_origin(batch);
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { return false };
let (profession, level, xp, scroll, shop, future, focused) = (m.profession.clone(), m.level, m.xp, m.scroll, m.shop_item, m.future_xp, m.focused);
let offers = m.offers.clone();
let costs: Vec<ItemStack> = offers.iter().map(|o| o.cost_a(&self.res.items)).collect();
let atlas = &self.res.atlas;
batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160));
if let Some(mut r) = atlas.sprites.get("gui/container/villager").copied() {
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
r.u1 = r.u0 + 276.0 * du;
r.v1 = r.v0 + 166.0 * dv;
batch.rect_uv(ox + SHIFT, oy, 276.0, 166.0, r, u32::MAX);
}
let e = &self.res.stations.enchantments;
let tr = |k: &str, f: &str| e.translate(k).unwrap_or(f).to_owned();
let name = tr(&format!("entity.minecraft.villager.{profession}"), &profession);
let title = tr("merchant.title", "%s - %s").replacen("%s", &name, 1).replacen("%s", &tr(&format!("merchant.level.{level}"), ""), 1);
let tw = HudBatch::text_width(atlas, &title);
batch.text(atlas, &title, ox + SHIFT + (49.0 + 138.0 - (tw / 2.0).floor()), oy + 6.0, GREY, false);
let trades = tr("merchant.trades", "Trades");
let tw = HudBatch::text_width(atlas, &trades);
batch.text(atlas, &trades, ox + SHIFT + 5.0 - (tw / 2.0).floor() + 48.0, oy + 6.0, GREY, false);
batch.text(atlas, &tr("container.inventory", "Inventory"), ox + SHIFT + 107.0, oy + 72.0, GREY, false);
if offers.get(shop).is_some_and(MerchantOffer::out_of_stock) {
batch.sprite(atlas, "gui/sprites/container/villager/out_of_stock", ox + SHIFT + 182.0, oy + 35.0);
}
// Experience bar (levels 1-4).
if level < 5 {
batch.sprite(atlas, "gui/sprites/container/villager/experience_bar_background", ox + SHIFT + 136.0, oy + 16.0);
let min = merchant::min_xp(level);
if xp >= min && merchant::can_level_up(level) {
let mult = 102.0 / (merchant::max_xp(level) - min) as f32;
let w = ((mult * (xp - min) as f32).floor()).min(102.0);
batch.sprite_part(atlas, "gui/sprites/container/villager/experience_bar_current", ox + SHIFT + 136.0, oy + 16.0, w / 102.0);
if future > 0 {
let fw = (future as f32 * mult).floor().min(102.0 - w);
if let Some(mut r) = atlas.sprites.get("gui/sprites/container/villager/experience_bar_result").copied() {
let du = (r.u1 - r.u0) / r.w as f32;
r.u0 += w * du;
r.u1 = r.u0 + fw * du;
batch.rect_uv(ox + SHIFT + 136.0 + w, oy + 16.0, fw, 5.0, r, u32::MAX);
}
}
}
}
// Scroller.
let steps = offers.len() as i32 + 1 - 7;
if steps > 1 {
let left = 139 - (27 + (steps - 1) * 139 / steps);
let step = 1 + left / steps + 139 / steps;
let mut y = (scroll as i32 * step).min(113);
if scroll as i32 == steps - 1 {
y = 113;
}
batch.sprite(atlas, "gui/sprites/container/villager/scroller", ox + SHIFT + 94.0, oy + 18.0 + y as f32);
} else {
batch.sprite(atlas, "gui/sprites/container/villager/scroller_disabled", ox + SHIFT + 94.0, oy + 18.0);
}
// Offer buttons.
let mut tooltip: Option<ItemStack> = None;
for (row, (index, offer)) in offers.iter().enumerate().skip(scroll).take(7).enumerate() {
let (bx, by) = (ox + SHIFT + 5.0, oy + 18.0 + 20.0 * row as f32);
let hover = local.0 >= 5.0 + SHIFT && local.0 < 93.0 + SHIFT && local.1 >= 18.0 + 20.0 * row as f32 && local.1 < 38.0 + 20.0 * row as f32;
let sprite = if hover || focused == Some(row) { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" };
batch.sprite_scaled(&self.res.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX);
let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0;
let base = offer.base_cost_a.stack.clone();
let cost_a = costs[index].clone();
let x = ox + SHIFT + 10.0;
if base.count == cost_a.count {
self.draw_item(batch, &cost_a, x, y);
} else {
// Discounted: the base price struck through, then the new price.
self.draw_item(batch, &ItemStack { count: 1, ..cost_a.clone() }, x, y);
let atlas = &self.res.atlas;
let t = base.count.to_string();
batch.text(atlas, &t, x + 17.0 - HudBatch::text_width(atlas, &t), y + 9.0, u32::MAX, true);
let t = cost_a.count.to_string();
batch.text(atlas, &t, x + 14.0 + 17.0 - HudBatch::text_width(atlas, &t), y + 9.0, u32::MAX, true);
batch.sprite(atlas, "gui/sprites/container/villager/discount_strikethrough", x + 7.0, y + 12.0);
}
if let Some(b) = offer.cost_b() {
self.draw_item(batch, &b, ox + SHIFT + 40.0, y);
}
let arrow = if offer.out_of_stock() { "trade_arrow_out_of_stock" } else { "trade_arrow" };
batch.sprite(&self.res.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0);
self.draw_item(batch, &offer.result, ox + SHIFT + 73.0, y);
if hover && self.carried.is_none() {
let rel = local.0 - (5.0 + SHIFT);
tooltip = if rel < 20.0 {
Some(cost_a)
} else if rel > 30.0 && rel < 50.0 {
offer.cost_b()
} else if rel > 65.0 {
Some(offer.result.clone())
} else {
None
};
}
}
// Slots, hover highlight, carried stack, tooltip.
let slots: Vec<usize> = (0..36).chain([INPUT, INPUT + 1, RESULT]).collect();
for i in slots {
let (sx, sy) = self.slot_position(i);
if let Some(stack) = self.slot_mut(i).clone() {
self.draw_item(batch, &stack, ox + sx, oy + sy);
}
}
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
batch.fill(&self.res.atlas, ox + sx, oy + sy, 16.0, 16.0, rgba(255, 255, 255, 128));
if self.carried.is_none() && tooltip.is_none() {
tooltip = self.slot_mut(slot).clone();
}
}
if let Some(stack) = self.carried.clone() {
self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0);
} else if let Some(stack) = tooltip {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
}
true
}
}
+1
View File
@@ -27,6 +27,7 @@ pub mod item_data;
pub mod items;
pub mod landing;
pub mod light;
pub mod merchant;
pub mod mesher;
pub mod mobs;
pub mod models;
+466
View File
@@ -0,0 +1,466 @@
//! Villager trading: the data-driven `trade_set` / `villager_trade` registries,
//! offer generation (`AbstractVillager.addOffersFromTradeSet` with each
//! set's `RandomSequence`), `MerchantOffer` pricing, demand and stock, and the
//! `VillagerData` level thresholds. The villager entity itself is not part of
//! this module; anything that can trade calls [`Merchant`].
use crate::{
enchant::Enchantments,
items::{ItemStack, Items},
};
use horizon_core::random::{RandomSource, XoroshiroRandom, mix_stafford13, seed_from_hash};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path, sync::Arc};
/// `VillagerData.NEXT_LEVEL_XP_THRESHOLDS`.
pub const LEVEL_XP: [i32; 5] = [0, 10, 70, 150, 250];
pub fn can_level_up(level: i32) -> bool {
(1..5).contains(&level)
}
pub fn min_xp(level: i32) -> i32 {
if can_level_up(level) { LEVEL_XP[level as usize - 1] } else { 0 }
}
pub fn max_xp(level: i32) -> i32 {
if can_level_up(level) { LEVEL_XP[level as usize] } else { 0 }
}
/// The professions with trades, as in `VillagerProfession`.
pub const PROFESSIONS: &[&str] = &[
"armorer", "butcher", "cartographer", "cleric", "farmer", "fisherman", "fletcher", "leatherworker", "librarian", "mason", "shepherd", "toolsmith", "weaponsmith",
];
/// An `ItemCost`: item and count (component predicates are not used by the
/// 26.3 trade data except for one exact match, kept as the stack's data).
#[derive(Clone, Debug, PartialEq)]
pub struct ItemCost {
pub stack: ItemStack,
}
impl ItemCost {
pub fn test(&self, s: &ItemStack) -> bool {
s.item == self.stack.item && (self.stack.extra.is_none() || s.data() == self.stack.data())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MerchantOffer {
pub base_cost_a: ItemCost,
pub cost_b: Option<ItemCost>,
pub result: ItemStack,
pub uses: i32,
pub max_uses: i32,
pub reward_exp: bool,
pub special_price_diff: i32,
pub demand: i32,
pub price_multiplier: f32,
pub xp: i32,
}
impl MerchantOffer {
fn max_stack(items: &Items, s: &ItemStack) -> u32 {
items.get(&s.item).map_or(64, |i| i.max_stack)
}
/// `getModifiedCostCount` for cost A.
pub fn cost_a_count(&self, items: &Items) -> u32 {
let base = self.base_cost_a.stack.count as i32;
let demand_diff = ((base as f32 * 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
}
pub fn cost_a(&self, items: &Items) -> ItemStack {
ItemStack { count: self.cost_a_count(items), ..self.base_cost_a.stack.clone() }
}
pub fn cost_b(&self) -> Option<ItemStack> {
self.cost_b.as_ref().map(|c| c.stack.clone())
}
pub fn out_of_stock(&self) -> bool {
self.uses >= self.max_uses
}
/// `MerchantOffer.updateDemand` (on restock).
pub fn update_demand(&mut self) {
self.demand = self.demand + self.uses - (self.max_uses - self.uses);
}
/// `satisfiedBy(buyA, buyB)`.
pub fn satisfied_by(&self, items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>) -> bool {
let Some(a) = a else { return false };
if !self.base_cost_a.test(a) || a.count < self.cost_a_count(items) {
return false;
}
match (&self.cost_b, b) {
(None, b) => b.is_none(),
(Some(c), Some(b)) => c.test(b) && b.count >= c.stack.count,
(Some(_), None) => false,
}
}
/// `MerchantOffer.take`: consume the payment; false when not satisfied.
pub fn take(&self, items: &Items, a: &mut Option<ItemStack>, b: &mut Option<ItemStack>) -> bool {
if !self.satisfied_by(items, a.as_ref(), b.as_ref()) {
return false;
}
let n = self.cost_a_count(items);
if let Some(s) = a.as_mut() {
s.count -= n;
if s.count == 0 {
*a = None;
}
}
if let (Some(c), Some(s)) = (&self.cost_b, b.as_mut()) {
s.count -= c.stack.count;
if s.count == 0 {
*b = None;
}
}
true
}
}
/// `MerchantOffers.getRecipeFor`: the hinted offer if it fits, else the first that does.
pub fn recipe_for(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>, hint: Option<usize>) -> Option<usize> {
if let Some(h) = hint
&& offers.get(h).is_some_and(|o| o.satisfied_by(items, a, b))
{
return Some(h);
}
offers.iter().position(|o| o.satisfied_by(items, a, b))
}
/// `MerchantContainer.updateSellItem`: (active offer, result).
pub fn sell_item(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>, hint: Option<usize>) -> (Option<usize>, Option<ItemStack>) {
let (a, b) = if a.is_none() { (b, None) } else { (a, b) };
if a.is_none() {
return (None, None);
}
let mut found = recipe_for(offers, items, a, b, hint);
let mut active = found;
if found.is_none_or(|i| offers[i].out_of_stock()) {
active = found;
found = recipe_for(offers, items, b, a, hint);
}
match found {
Some(i) if !offers[i].out_of_stock() => (Some(i), Some(offers[i].result.clone())),
_ => (active, None),
}
}
/// `RandomSequence(worldSeed ^ salt, id)` with the default salt 0.
pub fn sequence_random(world_seed: i64, id: &str) -> XoroshiroRandom {
const SILVER: u64 = 0x6a09_e667_f3bc_c909;
const GOLDEN: u64 = 0x9e37_79b9_7f4a_7c15;
let lo = world_seed as u64 ^ SILVER;
let hi = lo.wrapping_add(GOLDEN);
let key = seed_from_hash(id);
XoroshiroRandom::from_state(mix_stafford13(lo ^ key[0]), mix_stafford13(hi ^ key[1]))
}
/// The trade registries.
pub struct Trades {
pub trades: HashMap<String, Value>,
/// villager_trade tags, ordered.
pub tags: HashMap<String, Vec<String>>,
pub sets: HashMap<String, Value>,
}
fn walk(dir: &Path, base: &Path, out: &mut HashMap<String, Value>) {
let Ok(entries) = fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
walk(&p, base, out);
} else if p.extension().is_some_and(|x| x == "json")
&& let Ok(rel) = p.strip_prefix(base)
&& let Ok(bytes) = fs::read(&p)
&& let Ok(v) = serde_json::from_slice(&bytes)
{
out.insert(format!("minecraft:{}", rel.with_extension("").to_string_lossy().replace('\\', "/")), v);
}
}
}
impl Trades {
pub fn load(root: &Path) -> Self {
let data = root.join("data/minecraft");
let (mut trades, mut raw_tags, mut sets) = (HashMap::new(), HashMap::new(), HashMap::new());
walk(&data.join("villager_trade"), &data.join("villager_trade"), &mut trades);
walk(&data.join("tags/villager_trade"), &data.join("tags/villager_trade"), &mut raw_tags);
walk(&data.join("trade_set"), &data.join("trade_set"), &mut sets);
let raw: HashMap<String, Vec<String>> = raw_tags
.into_iter()
.map(|(k, v)| (k, v["values"].as_array().into_iter().flatten().filter_map(|e| e.as_str().map(str::to_owned)).collect()))
.collect();
fn expand(name: &str, raw: &HashMap<String, Vec<String>>, out: &mut Vec<String>, depth: u32) {
for v in raw.get(name).into_iter().flatten() {
match v.strip_prefix('#') {
Some(t) if depth < 16 => expand(t, raw, out, depth + 1),
Some(_) => {}
None if !out.contains(v) => out.push(v.clone()),
None => {}
}
}
}
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 }
}
/// `VillagerProfession.getTrades(level)`.
pub fn set_for(profession: &str, level: i32) -> String {
format!("minecraft:{}/level_{level}", profession.trim_start_matches("minecraft:"))
}
fn trade_list(&self, spec: &Value) -> Vec<String> {
match spec {
Value::String(s) => match s.strip_prefix('#') {
Some(tag) => self.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![],
}
}
/// `AbstractVillager.addOffersFromTradeSet`.
pub fn offers_from_set<R: RandomSource>(&self, ctx: &TradeContext<'_>, set_id: &str, random: &mut R) -> Vec<MerchantOffer> {
let Some(set) = self.sets.get(set_id) else { return vec![] };
let mut potential = self.trade_list(&set["trades"]);
let amount = int_provider(&set["amount"], random);
let duplicates = set["allow_duplicates"].as_bool().unwrap_or(false);
let mut out = Vec::new();
while (out.len() as i32) < amount && !potential.is_empty() {
let roll = random.next_int_bound(potential.len() as i32).unwrap_or(0) as usize;
let id = if duplicates { potential[roll].clone() } else { potential.remove(roll) };
match self.trades.get(&id).and_then(|t| offer_from(ctx, t, random)) {
Some(o) => out.push(o),
None if duplicates => {
potential.remove(roll);
}
None => {}
}
}
out
}
}
/// What a villager trade's loot context provides.
pub struct TradeContext<'a> {
pub items: &'a Items,
pub enchantments: &'a Enchantments,
/// Villager type (`minecraft:plains`, ...), for `merchant_predicate`.
pub variant: &'a str,
}
fn int_provider<R: RandomSource>(v: &Value, random: &mut R) -> i32 {
match v {
Value::Number(n) => n.as_i64().unwrap_or(0) as i32,
Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("") {
"minecraft:uniform" => {
let (min, max) = (o["min"].as_i64().unwrap_or(0) as i32, o["max"].as_i64().unwrap_or(0) as i32);
if min >= max { min } else { min + random.next_int_bound(max - min + 1).unwrap_or(0) }
}
"minecraft:constant" => o["value"].as_i64().unwrap_or(0) as i32,
_ => o.get("value").and_then(Value::as_i64).unwrap_or(0) as i32,
},
_ => 0,
}
}
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) }
}
fn variant_ok(pred: &Value, variant: &str) -> bool {
match &pred["predicate"]["minecraft:predicates"]["minecraft:villager/variant"] {
Value::String(s) => s == variant,
Value::Array(a) => a.iter().any(|x| x.as_str() == Some(variant)),
_ => true,
}
}
/// `VillagerTrade.getOffer`.
pub fn offer_from<R: RandomSource>(ctx: &TradeContext<'_>, t: &Value, random: &mut R) -> Option<MerchantOffer> {
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") {
if 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<R: RandomSource>(ctx: &TradeContext<'_>, m: &Value, stack: ItemStack, random: &mut R) -> Option<(ItemStack, i32)> {
let e = ctx.enchantments;
let pool = |options: &Value| -> Vec<Arc<str>> {
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(),
}
};
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))
}
"minecraft:enchant_randomly" => {
let book = &*stack.item == "minecraft:book";
let only_compatible = m["only_compatible"].as_bool().unwrap_or(true);
let options: Vec<Arc<str>> = 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"][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: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)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn items() -> Items {
Items::for_tests(HashMap::new())
}
fn offer(cost: u32, b: Option<u32>) -> MerchantOffer {
MerchantOffer {
base_cost_a: ItemCost { stack: ItemStack::new("minecraft:emerald", cost) },
cost_b: b.map(|n| ItemCost { stack: ItemStack::new("minecraft:book", n) }),
result: ItemStack::new("minecraft:iron_boots", 1),
uses: 0,
max_uses: 12,
reward_exp: true,
special_price_diff: 0,
demand: 0,
price_multiplier: 0.2,
xp: 1,
}
}
#[test]
fn demand_raises_prices() {
let items = items();
let mut o = offer(4, None);
assert_eq!(o.cost_a_count(&items), 4);
o.uses = 12;
o.update_demand();
assert_eq!(o.demand, 12);
// 4 + floor(4 * 12 * 0.2) = 13.
assert_eq!(o.cost_a_count(&items), 13);
o.special_price_diff = -20;
assert_eq!(o.cost_a_count(&items), 1);
}
#[test]
fn payment_and_selection() {
let items = items();
let offers = vec![offer(5, None), offer(1, Some(1))];
let mut a = Some(ItemStack::new("minecraft:emerald", 6));
let mut b = None;
assert_eq!(sell_item(&offers, &items, a.as_ref(), b.as_ref(), None).0, Some(0));
assert!(offers[0].take(&items, &mut a, &mut b));
assert_eq!(a.as_ref().unwrap().count, 1);
// Payment in the second slot only still matches (A and B swap).
let book = Some(ItemStack::new("minecraft:book", 1));
let (i, r) = sell_item(&offers, &items, None, Some(&ItemStack::new("minecraft:emerald", 5)), None);
assert_eq!((i, r.map(|r| r.item)), (Some(0), Some(Arc::from("minecraft:iron_boots"))));
assert_eq!(sell_item(&offers, &items, a.as_ref(), book.as_ref(), Some(1)).0, Some(1));
let mut out = offers[0].clone();
out.uses = 12;
assert_eq!(sell_item(&[out], &items, Some(&ItemStack::new("minecraft:emerald", 5)), None, None).1, None);
}
#[test]
fn sequence_random_is_stable() {
let mut a = sequence_random(12345, "minecraft:trade_set/armorer/level_1");
let mut b = sequence_random(12345, "minecraft:trade_set/armorer/level_1");
let mut c = sequence_random(12345, "minecraft:trade_set/butcher/level_1");
let (x, y, z) = (a.next_long(), b.next_long(), c.next_long());
assert_eq!(x, y);
assert_ne!(x, z);
assert_eq!(min_xp(2), 10);
assert_eq!(max_xp(2), 70);
assert!(!can_level_up(5));
}
#[test]
fn offers_follow_the_trade_data() {
let items = items();
let e = crate::enchant::tests::sample();
let mut trades = HashMap::new();
trades.insert("minecraft:t/boots".into(), json!({"gives":{"id":"minecraft:iron_boots"},"max_uses":12,"reputation_discount":0.2,"wants":{"count":4,"id":"minecraft:emerald"}}));
trades.insert("minecraft:t/helmet".into(), json!({"gives":{"id":"minecraft:iron_helmet"},"max_uses":12,"reputation_discount":0.2,"wants":{"count":5,"id":"minecraft:emerald"}}));
trades.insert("minecraft:t/desert".into(), json!({"gives":{"id":"minecraft:sand"},"wants":{"id":"minecraft:emerald"},"merchant_predicate":{"entity":"this","predicate":{"minecraft:predicates":{"minecraft:villager/variant":"minecraft:desert"}},"type":"minecraft:entity_properties"}}));
let mut tags = HashMap::new();
tags.insert("minecraft:t/level_1".into(), vec!["minecraft:t/boots".into(), "minecraft:t/helmet".into(), "minecraft:t/desert".into()]);
let mut sets = HashMap::new();
sets.insert("minecraft:t/level_1".into(), json!({"amount": 5, "trades": "#minecraft:t/level_1"}));
let t = Trades { trades, tags, sets };
let ctx = TradeContext { items: &items, enchantments: &e, variant: "minecraft:plains" };
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.
assert_eq!(offers.len(), 2);
assert_ne!(offers[0].result.item, offers[1].result.item);
assert!(offers.iter().all(|o| o.max_uses == 12 && (o.price_multiplier - 0.2).abs() < 1e-6));
}
}
+7 -1
View File
@@ -17,10 +17,16 @@ pub struct StationData {
pub enchantments: Enchantments,
pub recipes: StationRecipes,
pub brewing: crate::brewing::Brewing,
pub trades: crate::merchant::Trades,
}
impl StationData {
pub fn load(root: &Path, items: &Items) -> Self {
Self { enchantments: Enchantments::load(root), recipes: StationRecipes::load(root, items), brewing: crate::brewing::Brewing::load(root, items) }
Self {
enchantments: Enchantments::load(root),
recipes: StationRecipes::load(root, items),
brewing: crate::brewing::Brewing::load(root, items),
trades: crate::merchant::Trades::load(root),
}
}
}