Trade over the network: LAN guests and Horizon as a client
The host hands a trading screen a guest's interaction opens to that guest: OpenScreen (minecraft:merchant), MerchantOffers when the offers change, the select trade packet, container clicks run on the merchant menu engine, the TRADE reputation event and prices for the guest's UUID, the payment back on close. As a client, Horizon shows a server's trading window from its MerchantOffers and sends select trade and clicks. Stored enchantments, dyed colours and map ids now travel in item stacks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -46,6 +46,7 @@ mod jukebox;
|
||||
mod lan;
|
||||
mod lan_actions;
|
||||
mod lan_screen;
|
||||
mod lan_trading;
|
||||
mod leads;
|
||||
mod lightning;
|
||||
mod llamas;
|
||||
|
||||
@@ -35,6 +35,8 @@ pub(super) struct GuestPlay {
|
||||
last_progress: i32,
|
||||
/// Hand movements the client announced and the host animated.
|
||||
swung: bool,
|
||||
/// The trading screen the guest has open.
|
||||
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
|
||||
}
|
||||
|
||||
struct ItemRules<'a>(&'a horizon_client::items::Items);
|
||||
@@ -135,6 +137,7 @@ impl Game<'_> {
|
||||
self.left = play.digging.is_some();
|
||||
self.right = play.using.is_some() || self.using.is_some();
|
||||
let riding = self.riding.take();
|
||||
let host_station = self.station.take();
|
||||
self.lan_acting = Some(conn);
|
||||
|
||||
let result = f(self);
|
||||
@@ -142,6 +145,7 @@ impl Game<'_> {
|
||||
|
||||
// What the action opened: handed to the guest instead of the host.
|
||||
let opened = self.container.take();
|
||||
let opened_station = std::mem::replace(&mut self.station, host_station);
|
||||
self.riding = riding;
|
||||
self.left = left;
|
||||
self.right = right;
|
||||
@@ -199,6 +203,9 @@ impl Game<'_> {
|
||||
if let Some(pos) = opened {
|
||||
self.lan_open_container(host, conn, pos);
|
||||
}
|
||||
if let Some(station) = opened_station {
|
||||
self.lan_station_opened(host, conn, station);
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
@@ -384,6 +391,14 @@ impl Game<'_> {
|
||||
let item = self.item_from_network(host, &p.item);
|
||||
host.hub.guests[gi].set_menu_slot(p.slot as usize, item);
|
||||
}
|
||||
S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {}
|
||||
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
|
||||
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if let Some(c) = g.carried.take() {
|
||||
self.drop_guest_items(host, gi, vec![c]);
|
||||
}
|
||||
}
|
||||
S::ContainerClick(p) => {
|
||||
let rules = ItemRules(&self.res.items);
|
||||
let drops = host.hub.container_click(conn, p, &mut self.world, &rules);
|
||||
@@ -445,7 +460,7 @@ impl Game<'_> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn drop_guest_items(&mut self, host: &LanHost, gi: usize, stacks: Vec<ItemStack>) {
|
||||
pub(super) fn drop_guest_items(&mut self, host: &LanHost, gi: usize, stacks: Vec<ItemStack>) {
|
||||
let g = &host.hub.guests[gi];
|
||||
let eye = [
|
||||
g.position[0],
|
||||
@@ -615,6 +630,7 @@ impl Game<'_> {
|
||||
|
||||
/// Per tick, for every guest: dig, use items, pick up drops, die.
|
||||
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
|
||||
self.lan_merchant_tick(host);
|
||||
let conns: Vec<u32> = host
|
||||
.hub
|
||||
.guests
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
//! Trading for LAN guests: the villager screen a guest opens runs the same
|
||||
//! merchant menu as the host's (`horizon_client::menu`, `Kind::Merchant`),
|
||||
//! with vanilla's packets: OpenScreen (`minecraft:merchant`), MerchantOffers,
|
||||
//! the select trade packet, container clicks and the content sync after each.
|
||||
use super::{Game, lan::LanHost, stations::Kind as StationKind, trading::MerchantState};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
menu::{Env, Input, Kind, Menu},
|
||||
merchant,
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
|
||||
/// A guest's open trading screen.
|
||||
pub(super) struct GuestMerchant {
|
||||
pub(super) window: i32,
|
||||
state: i32,
|
||||
/// The payment slots and the result.
|
||||
slots: [Option<ItemStack>; 3],
|
||||
pub(super) merchant: Box<MerchantState>,
|
||||
/// The offers the client was last sent.
|
||||
sent: Vec<merchant::MerchantOffer>,
|
||||
sent_level: i32,
|
||||
}
|
||||
|
||||
/// A guest's UUID as gossip targets it.
|
||||
fn uuid_words(uuid: u128) -> [i32; 4] {
|
||||
[
|
||||
(uuid >> 96) as i32,
|
||||
(uuid >> 64) as i32,
|
||||
(uuid >> 32) as i32,
|
||||
uuid as i32,
|
||||
]
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A trading screen the guest's interaction opened (it opened as a
|
||||
/// station while the guest acted): handed to the guest.
|
||||
pub(super) fn lan_open_merchant(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
mut state: MerchantState,
|
||||
) {
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
let uuid = uuid_words(host.hub.guests[gi].uuid);
|
||||
if let Some(id) = state.mob
|
||||
&& state.session.villager
|
||||
{
|
||||
// startTrading with the guest's reputation (their effects are
|
||||
// not modelled on the host: no Hero of the Village).
|
||||
state.session.reputation = self.villager_reputation_of(id, uuid);
|
||||
state.session.hero = None;
|
||||
state.session.update_special_prices();
|
||||
}
|
||||
let title = horizon_protocol::text::literal(&self.merchant_title(&state));
|
||||
let Some(window) = host.hub.open_merchant_window(conn, title) else {
|
||||
self.merchant_closed(&mut state);
|
||||
return;
|
||||
};
|
||||
let mut gm = GuestMerchant {
|
||||
window,
|
||||
state: 0,
|
||||
slots: [None, None, None],
|
||||
merchant: Box::new(state),
|
||||
sent: Vec::new(),
|
||||
sent_level: 0,
|
||||
};
|
||||
self.lan_send_offers(host, conn, &mut gm, true);
|
||||
self.lan_send_merchant_content(host, conn, &mut gm);
|
||||
host.play.entry(conn).or_default().merchant = Some(gm);
|
||||
}
|
||||
/// The screen title: the custom name, else the profession (the client
|
||||
/// adds the level itself).
|
||||
fn merchant_title(&self, state: &MerchantState) -> String {
|
||||
if let Some(name) = &state.name {
|
||||
return name.clone();
|
||||
}
|
||||
let e = &self.res.stations.enchantments;
|
||||
let profession = state.session.profession.trim_start_matches("minecraft:");
|
||||
if state.session.villager {
|
||||
e.translate(&format!("entity.minecraft.villager.{profession}"))
|
||||
.unwrap_or(profession)
|
||||
.to_owned()
|
||||
} else {
|
||||
e.translate("entity.minecraft.wandering_trader")
|
||||
.unwrap_or("Wandering Trader")
|
||||
.to_owned()
|
||||
}
|
||||
}
|
||||
/// `ServerPlayer.sendMerchantOffers`, when the offers changed.
|
||||
fn lan_send_offers(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
gm: &mut GuestMerchant,
|
||||
force: bool,
|
||||
) {
|
||||
let s = &gm.merchant.session;
|
||||
if !force && s.offers == gm.sent && s.level == gm.sent_level {
|
||||
return;
|
||||
}
|
||||
let offers: Vec<play::NetOffer> = s
|
||||
.offers
|
||||
.iter()
|
||||
.filter_map(|o| {
|
||||
let cost =
|
||||
|st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| play::NetCost {
|
||||
item: hub.item_id(&st.item),
|
||||
count: st.count as i32,
|
||||
};
|
||||
Some(play::NetOffer {
|
||||
cost_a: cost(&o.base_cost_a.stack, &mut host.hub),
|
||||
result: host.hub.stack(&Some(o.result.clone()))?,
|
||||
cost_b: o.cost_b.as_ref().map(|b| cost(&b.stack, &mut host.hub)),
|
||||
out_of_stock: o.out_of_stock(),
|
||||
uses: o.uses,
|
||||
max_uses: o.max_uses,
|
||||
xp: o.xp,
|
||||
special_price: o.special_price_diff,
|
||||
price_multiplier: o.price_multiplier,
|
||||
demand: o.demand,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::MerchantOffers(play::MerchantOffers {
|
||||
container: gm.window,
|
||||
offers,
|
||||
level: s.level,
|
||||
xp: s.xp,
|
||||
show_progress: s.villager,
|
||||
can_restock: s.villager,
|
||||
}),
|
||||
);
|
||||
gm.sent = s.offers.clone();
|
||||
gm.sent_level = s.level;
|
||||
}
|
||||
fn lan_send_merchant_content(&mut self, host: &mut LanHost, conn: u32, gm: &mut GuestMerchant) {
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
let mut items: Vec<Option<ItemStack>> = gm.slots.to_vec();
|
||||
let g = &host.hub.guests[gi];
|
||||
items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
|
||||
let carried = g.carried.clone();
|
||||
let net: Vec<_> = items.iter().map(|s| host.hub.stack(s)).collect();
|
||||
let carried = host.hub.stack(&carried);
|
||||
gm.state = (gm.state + 1) & 0x7FFF;
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::ContainerSetContent(play::ContainerSetContent {
|
||||
container: gm.window,
|
||||
state: gm.state,
|
||||
items: net,
|
||||
carried,
|
||||
}),
|
||||
);
|
||||
}
|
||||
/// Runs `op` on the guest's merchant menu (their inventory copied in and
|
||||
/// back), then syncs the client. False when the guest has no such window.
|
||||
fn lan_merchant_op(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: Option<i32>,
|
||||
op: impl FnOnce(&mut Menu, &Env),
|
||||
) -> bool {
|
||||
let Some(mut gm) = host.play.get_mut(&conn).and_then(|p| p.merchant.take()) else {
|
||||
return false;
|
||||
};
|
||||
if window.is_some_and(|w| w != gm.window) {
|
||||
host.play.entry(conn).or_default().merchant = Some(gm);
|
||||
return false;
|
||||
}
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return false;
|
||||
};
|
||||
let mut session = gm.merchant.session.clone();
|
||||
self.merchant_sync_in(&mut session, gm.merchant.mob);
|
||||
let next_map = self.peek_map_id();
|
||||
let tag = |t: &str| self.structure_tag(t);
|
||||
let maps = super::trading::GameMaps {
|
||||
terrain: self.end.locator(),
|
||||
structure_tag: &tag,
|
||||
made: Default::default(),
|
||||
next_id: std::cell::Cell::new(next_map),
|
||||
};
|
||||
let trade_env = merchant::TradeEnv {
|
||||
trades: &self.res.stations.trades,
|
||||
enchantments: &self.res.stations.enchantments,
|
||||
maps: Some(&maps),
|
||||
};
|
||||
let env = Env {
|
||||
items: &self.res.items,
|
||||
recipes: &self.res.recipes,
|
||||
brewing: &self.res.stations.brewing,
|
||||
banners: &self.res.stations.banners,
|
||||
trade: Some(&trade_env),
|
||||
};
|
||||
let mut menu = Menu::new(Kind::Merchant);
|
||||
{
|
||||
let g = &host.hub.guests[gi];
|
||||
for i in 0..36 {
|
||||
menu.set_player_item(i, g.inventory[i].clone());
|
||||
}
|
||||
menu.set_player_item(40, g.offhand.clone());
|
||||
menu.selected = g.selected;
|
||||
menu.creative = g.creative();
|
||||
menu.carried = g.carried.clone();
|
||||
}
|
||||
for (i, s) in gm.slots.iter().enumerate() {
|
||||
menu.set_slot(&env, i, s.clone());
|
||||
}
|
||||
menu.merchant = Some(session);
|
||||
op(&mut menu, &env);
|
||||
let made = maps.made.take();
|
||||
let session = menu.merchant.take().expect("attached");
|
||||
let dropped = std::mem::take(&mut menu.dropped);
|
||||
gm.slots = [
|
||||
menu.slot(0).cloned(),
|
||||
menu.slot(1).cloned(),
|
||||
menu.slot(2).cloned(),
|
||||
];
|
||||
{
|
||||
let g = &mut host.hub.guests[gi];
|
||||
for i in 0..36 {
|
||||
g.inventory[i] = menu.player_item(i).cloned();
|
||||
}
|
||||
g.offhand = menu.player_item(40).cloned();
|
||||
g.carried = menu.carried.take();
|
||||
}
|
||||
self.register_exploration_maps(made);
|
||||
gm.merchant.session = self.merchant_apply(session, gm.merchant.mob);
|
||||
self.drop_guest_items(host, gi, dropped);
|
||||
self.lan_send_offers(host, conn, &mut gm, false);
|
||||
self.lan_send_merchant_content(host, conn, &mut gm);
|
||||
host.play.entry(conn).or_default().merchant = Some(gm);
|
||||
true
|
||||
}
|
||||
/// A container click on the guest's trading window.
|
||||
pub(super) fn lan_merchant_click(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: &play::ContainerClick,
|
||||
) -> bool {
|
||||
let input = match p.input {
|
||||
0 => Input::Pickup,
|
||||
1 => Input::QuickMove,
|
||||
2 => Input::Swap,
|
||||
3 => Input::Clone,
|
||||
4 => Input::Throw,
|
||||
5 => Input::QuickCraft,
|
||||
_ => Input::PickupAll,
|
||||
};
|
||||
let (slot, button) = (i32::from(p.slot), i32::from(p.button));
|
||||
self.lan_merchant_op(host, conn, Some(p.container), |menu, env| {
|
||||
let _ = menu.click(env, slot, button, input);
|
||||
})
|
||||
}
|
||||
/// ServerboundSelectTradePacket: the selection hint, then tryMoveItems.
|
||||
pub(super) fn lan_select_trade(&mut self, host: &mut LanHost, conn: u32, index: i32) {
|
||||
let Ok(index) = usize::try_from(index) else {
|
||||
return;
|
||||
};
|
||||
self.lan_merchant_op(host, conn, None, |menu, env| {
|
||||
menu.merchant_select(env, index)
|
||||
});
|
||||
}
|
||||
/// The guest closed the trading window (or it is closed for them):
|
||||
/// MerchantMenu.removed, then the villager gets its state back.
|
||||
pub(super) fn lan_merchant_closed(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: Option<i32>,
|
||||
) -> bool {
|
||||
if !self.lan_merchant_op(host, conn, window, |menu, env| menu.merchant_close(env)) {
|
||||
return false;
|
||||
}
|
||||
let Some(mut gm) = host.play.get_mut(&conn).and_then(|p| p.merchant.take()) else {
|
||||
return false;
|
||||
};
|
||||
let uuid = host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| g.conn == conn)
|
||||
.map(|g| uuid_words(g.uuid));
|
||||
if std::mem::take(&mut gm.merchant.session.last_traded)
|
||||
&& let (Some(id), Some(uuid)) = (gm.merchant.mob, uuid)
|
||||
{
|
||||
self.villager_traded_by(id, uuid);
|
||||
}
|
||||
self.merchant_closed(&mut gm.merchant);
|
||||
true
|
||||
}
|
||||
/// `Villager.customServerAiStep` for the guests' trading villagers: the
|
||||
/// TRADE reputation event, then the prices follow.
|
||||
pub(super) fn lan_merchant_tick(&mut self, host: &mut LanHost) {
|
||||
let conns: Vec<u32> = host
|
||||
.play
|
||||
.iter()
|
||||
.filter(|(_, p)| {
|
||||
p.merchant
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.merchant.session.villager && m.merchant.session.last_traded)
|
||||
})
|
||||
.map(|(c, _)| *c)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
let Some(uuid) = host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| g.conn == conn)
|
||||
.map(|g| uuid_words(g.uuid))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(gm) = host.play.get_mut(&conn).and_then(|p| p.merchant.as_mut()) else {
|
||||
continue;
|
||||
};
|
||||
gm.merchant.session.last_traded = false;
|
||||
let Some(id) = gm.merchant.mob else { continue };
|
||||
self.villager_traded_by(id, uuid);
|
||||
let reputation = self.villager_reputation_of(id, uuid);
|
||||
self.lan_merchant_op(host, conn, None, |menu, env| {
|
||||
if let Some(s) = menu.merchant.as_mut() {
|
||||
s.reputation = reputation;
|
||||
s.update_special_prices();
|
||||
}
|
||||
menu.merchant_update(env);
|
||||
});
|
||||
}
|
||||
}
|
||||
/// Takes a station a guest's action opened: a trading screen goes to the
|
||||
/// guest; other stations are not shown to guests yet.
|
||||
pub(super) fn lan_station_opened(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
station: super::stations::Station,
|
||||
) {
|
||||
let mut station = station;
|
||||
if station.kind == StationKind::Merchant
|
||||
&& let Some(m) = station.merchant.take()
|
||||
{
|
||||
self.lan_open_merchant(host, conn, *m);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,7 +287,7 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send(&self, packet: S) {
|
||||
pub(super) fn send(&self, packet: S) {
|
||||
if let Some(r) = &self.remote {
|
||||
r.session.send(packet);
|
||||
}
|
||||
@@ -315,12 +315,20 @@ impl Game<'_> {
|
||||
}
|
||||
fn to_stack(&self, s: &Option<Stack>) -> Option<ItemStack> {
|
||||
let s = s.as_ref()?;
|
||||
Some(ItemStack {
|
||||
let mut out = ItemStack {
|
||||
item: self.item_name(s.item),
|
||||
count: s.count.max(0) as u32,
|
||||
damage: s.damage().max(0) as u32,
|
||||
extra: None,
|
||||
})
|
||||
};
|
||||
use horizon_protocol::item::{Component, component};
|
||||
if let Some(Component::Int(rgb)) = s.component(component::DYED_COLOR) {
|
||||
out.data_mut().dyed_color = Some(*rgb);
|
||||
}
|
||||
if let Some(Component::Int(id)) = s.component(component::MAP_ID) {
|
||||
out.data_mut().map_id = Some(*id);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
fn to_network(&self, s: &Option<ItemStack>) -> Option<Stack> {
|
||||
let s = s.as_ref()?;
|
||||
@@ -659,6 +667,13 @@ impl Game<'_> {
|
||||
37..=45 => Some(s - 37),
|
||||
_ => None,
|
||||
},
|
||||
"minecraft:merchant" => match s {
|
||||
0 | 1 => Some(super::stations::INPUT + s),
|
||||
2 => Some(super::stations::RESULT),
|
||||
3..=29 => Some(9 + s - 3),
|
||||
30..=38 => Some(s - 30),
|
||||
_ => None,
|
||||
},
|
||||
"minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => match s {
|
||||
0..=2 => Some(300 + s),
|
||||
3..=29 => Some(9 + s - 3),
|
||||
@@ -1066,6 +1081,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
C::OpenScreen(p) => self.remote_open_screen(p),
|
||||
C::MerchantOffers(p) => self.remote_merchant_offers(p),
|
||||
C::ContainerClose(_) => {
|
||||
if self.screen == Screen::Inventory {
|
||||
self.remote_close_local();
|
||||
@@ -2293,6 +2309,13 @@ impl Game<'_> {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = None;
|
||||
}
|
||||
if self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == super::stations::Kind::Merchant)
|
||||
{
|
||||
self.station = None;
|
||||
}
|
||||
self.craft_size = 2;
|
||||
if let Some(key) = self.container.take() {
|
||||
// Server containers stay renderable but lose their copied slots.
|
||||
@@ -2303,6 +2326,52 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A server's trading window (MerchantScreen over a ClientSideMerchant).
|
||||
fn remote_open_merchant(&mut self, container: i32, title: String) {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = Some((container, "minecraft:merchant".to_owned()));
|
||||
}
|
||||
let session = horizon_client::merchant::Session::new(Vec::new(), true);
|
||||
self.open_remote_merchant(session, (!title.is_empty()).then_some(title));
|
||||
}
|
||||
/// ClientboundMerchantOffersPacket.
|
||||
fn remote_merchant_offers(&mut self, p: play::MerchantOffers) {
|
||||
if self.open_menu_name(p.container) != "minecraft:merchant" {
|
||||
return;
|
||||
}
|
||||
let cost = |g: &Self, c: &play::NetCost| horizon_client::merchant::ItemCost {
|
||||
stack: ItemStack::new(&g.item_name(c.item), c.count.max(0) as u32),
|
||||
};
|
||||
let offers: Vec<_> = p
|
||||
.offers
|
||||
.iter()
|
||||
.filter_map(|o| {
|
||||
let mut offer = horizon_client::merchant::MerchantOffer {
|
||||
base_cost_a: cost(self, &o.cost_a),
|
||||
cost_b: o.cost_b.as_ref().map(|b| cost(self, b)),
|
||||
result: self.to_stack(&Some(o.result.clone()))?,
|
||||
uses: o.uses,
|
||||
max_uses: o.max_uses,
|
||||
reward_exp: true,
|
||||
special_price_diff: o.special_price,
|
||||
demand: o.demand,
|
||||
price_multiplier: o.price_multiplier,
|
||||
xp: o.xp,
|
||||
};
|
||||
// setToOutOfStock.
|
||||
if o.out_of_stock {
|
||||
offer.uses = offer.max_uses;
|
||||
}
|
||||
Some(offer)
|
||||
})
|
||||
.collect();
|
||||
if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) {
|
||||
m.session.offers = offers;
|
||||
m.session.level = p.level;
|
||||
m.session.xp = p.xp;
|
||||
m.session.villager = p.show_progress;
|
||||
}
|
||||
}
|
||||
/// ClientboundOpenScreenPacket for the menus Horizon draws.
|
||||
fn remote_open_screen(&mut self, p: play::OpenScreen) {
|
||||
let menu = self
|
||||
@@ -2320,6 +2389,19 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.and_then(|r| r.use_target)
|
||||
.map(|t| (t[0], t[1], t[2]));
|
||||
if menu == "minecraft:merchant" {
|
||||
// A trading window: its offers follow in a MerchantOffers packet.
|
||||
let title = plain(
|
||||
&p.title,
|
||||
&self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| r.lang.clone())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
self.remote_open_merchant(p.container, title);
|
||||
return;
|
||||
}
|
||||
let entity = match menu.as_str() {
|
||||
"minecraft:crafting" => None,
|
||||
"minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => {
|
||||
|
||||
@@ -1035,6 +1035,10 @@ impl Game<'_> {
|
||||
if kind == Kind::Merchant && !right && self.merchant_click(local) {
|
||||
return true;
|
||||
}
|
||||
if kind == Kind::Merchant && self.remote.is_some() {
|
||||
// A server's trading window: its slots are the server's.
|
||||
return false;
|
||||
}
|
||||
if kind == Kind::Loom && !right && self.loom_click(local) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -356,6 +356,20 @@ impl Game<'_> {
|
||||
name: None,
|
||||
});
|
||||
}
|
||||
/// A server's trading window (no mob here: the server keeps it).
|
||||
pub(super) fn open_remote_merchant(
|
||||
&mut self,
|
||||
session: merchant::Session,
|
||||
name: Option<String>,
|
||||
) {
|
||||
self.open_merchant_state(MerchantState {
|
||||
session: Box::new(session),
|
||||
scroll: 0,
|
||||
focused: None,
|
||||
mob: None,
|
||||
name,
|
||||
});
|
||||
}
|
||||
fn open_merchant_state(&mut self, state: MerchantState) {
|
||||
let mut s = Station::new_kind(Kind::Merchant, [0, 0, 0]);
|
||||
s.merchant = Some(Box::new(state));
|
||||
@@ -380,6 +394,17 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.and_then(|s| s.merchant.as_ref())
|
||||
.and_then(|m| m.mob);
|
||||
let session = self.merchant_apply(session, mob);
|
||||
if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) {
|
||||
m.session = session;
|
||||
}
|
||||
}
|
||||
/// What a menu click's session did, applied to the world and its mob.
|
||||
pub(super) fn merchant_apply(
|
||||
&mut self,
|
||||
session: Box<merchant::Session>,
|
||||
mob: Option<u32>,
|
||||
) -> Box<merchant::Session> {
|
||||
let mut session = session;
|
||||
let events = std::mem::take(&mut session.events);
|
||||
let (villager, origin) = (session.villager, session.origin);
|
||||
@@ -390,9 +415,6 @@ impl Game<'_> {
|
||||
m.extra.variant3 = session.level.clamp(1, 5) as u8;
|
||||
}
|
||||
}
|
||||
if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) {
|
||||
m.session = session;
|
||||
}
|
||||
for e in events {
|
||||
match e {
|
||||
merchant::Event::Orb(v) => {
|
||||
@@ -416,6 +438,7 @@ impl Game<'_> {
|
||||
merchant::Event::TradeSound => {}
|
||||
}
|
||||
}
|
||||
session
|
||||
}
|
||||
/// `Villager.customServerAiStep`: the TRADE reputation event of the last
|
||||
/// trade, a tick later; the prices follow the new reputation.
|
||||
@@ -440,6 +463,16 @@ impl Game<'_> {
|
||||
}
|
||||
/// `MerchantMenu.tryMoveItems` for the selected offer (the select trade packet).
|
||||
fn try_move_items(&mut self, index: usize) {
|
||||
if self.remote.is_some() {
|
||||
// ServerboundSelectTradePacket; the server moves the items.
|
||||
if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) {
|
||||
m.session.selection_hint = index;
|
||||
}
|
||||
self.send(horizon_protocol::packets::play::Serverbound::SelectTrade(
|
||||
horizon_protocol::packets::play::SelectTrade { item: index as i32 },
|
||||
));
|
||||
return;
|
||||
}
|
||||
self.menu_session(|menu, env, _| {
|
||||
menu.merchant_select(env, index);
|
||||
Some(true)
|
||||
|
||||
@@ -336,9 +336,12 @@ impl Game<'_> {
|
||||
}
|
||||
/// `ReputationEventType.TRADE`: each trade earns a little trust.
|
||||
pub(super) fn villager_traded(&mut self, id: u32) {
|
||||
let Some(uuid) = self.level.player_uuid else {
|
||||
return;
|
||||
};
|
||||
if let Some(uuid) = self.level.player_uuid {
|
||||
self.villager_traded_by(id, uuid);
|
||||
}
|
||||
}
|
||||
/// The TRADE reputation event from the player `uuid` (a guest's too).
|
||||
pub(super) fn villager_traded_by(&mut self, id: u32, uuid: [i32; 4]) {
|
||||
let Some(i) = self.villager_index(id) else {
|
||||
return;
|
||||
};
|
||||
@@ -355,6 +358,10 @@ impl Game<'_> {
|
||||
let Some(uuid) = self.level.player_uuid else {
|
||||
return 0;
|
||||
};
|
||||
self.villager_reputation_of(id, uuid)
|
||||
}
|
||||
/// `Villager.getPlayerReputation` of the player `uuid`.
|
||||
pub(super) fn villager_reputation_of(&self, id: u32, uuid: [i32; 4]) -> i32 {
|
||||
self.villager_index(id)
|
||||
.and_then(|i| villager::ext(&self.mobs[i]))
|
||||
.map_or(0, |e| e.gossips.reputation(uuid))
|
||||
|
||||
@@ -155,6 +155,27 @@ impl Hub {
|
||||
self.send_menu_content(i, items);
|
||||
}
|
||||
|
||||
/// Open a trading window for a guest (`Merchant.openTradingScreen`):
|
||||
/// its id, or None when the menu type is unknown.
|
||||
pub fn open_merchant_window(&mut self, conn: u32, title: Tag) -> Option<i32> {
|
||||
let kind = self
|
||||
.sync
|
||||
.builtin
|
||||
.get("minecraft:menu")
|
||||
.and_then(|m| m.id("minecraft:merchant"))?;
|
||||
let i = self.guests.iter().position(|g| g.conn == conn)?;
|
||||
self.close_container_at(i);
|
||||
let g = &mut self.guests[i];
|
||||
g.next_window = g.next_window % 100 + 1;
|
||||
let window = g.next_window;
|
||||
g.send(&C::OpenScreen(play::OpenScreen {
|
||||
container: window,
|
||||
menu: kind,
|
||||
title,
|
||||
}));
|
||||
Some(window)
|
||||
}
|
||||
|
||||
fn send_menu_content(&mut self, i: usize, mut items: Vec<Option<ItemStack>>) {
|
||||
for j in 0..36 {
|
||||
items.push(self.guests[i].inventory[player_slot(j)].clone());
|
||||
|
||||
@@ -265,6 +265,31 @@ pub fn stack_to_network(
|
||||
horizon_protocol::item::Component::Enchantments(enchantments),
|
||||
));
|
||||
}
|
||||
let stored: Vec<(i32, i32)> = s
|
||||
.stored_enchantments()
|
||||
.iter()
|
||||
.filter_map(|(e, level)| Some((enchantment_id(e)?, *level as i32)))
|
||||
.collect();
|
||||
if !stored.is_empty() {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::STORED_ENCHANTMENTS,
|
||||
horizon_protocol::item::Component::Enchantments(stored),
|
||||
));
|
||||
}
|
||||
if let Some(d) = s.data() {
|
||||
if let Some(rgb) = d.dyed_color {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::DYED_COLOR,
|
||||
horizon_protocol::item::Component::Int(rgb),
|
||||
));
|
||||
}
|
||||
if let Some(id) = d.map_id {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::MAP_ID,
|
||||
horizon_protocol::item::Component::Int(id),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(name) = s.custom_name() {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::CUSTOM_NAME,
|
||||
|
||||
@@ -83,6 +83,94 @@ packet!(ContainerSetContent {
|
||||
items: Vec<Option<Stack>> => List<Slot>,
|
||||
carried: Option<Stack> => Slot,
|
||||
});
|
||||
/// ItemCost.STREAM_CODEC: item, count, then the exact component predicate
|
||||
/// (Horizon sends and reads it as a component patch without removals).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NetCost {
|
||||
pub item: i32,
|
||||
pub count: i32,
|
||||
}
|
||||
/// MerchantOffer.STREAM_CODEC.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NetOffer {
|
||||
pub cost_a: NetCost,
|
||||
pub result: Stack,
|
||||
pub cost_b: Option<NetCost>,
|
||||
pub out_of_stock: bool,
|
||||
pub uses: i32,
|
||||
pub max_uses: i32,
|
||||
pub xp: i32,
|
||||
pub special_price: i32,
|
||||
pub price_multiplier: f32,
|
||||
pub demand: i32,
|
||||
}
|
||||
pub struct Offers;
|
||||
impl Codec<Vec<NetOffer>> for Offers {
|
||||
fn read(r: &mut Reader) -> Result<Vec<NetOffer>> {
|
||||
fn cost(r: &mut Reader) -> Result<NetCost> {
|
||||
let item = r.varint()?;
|
||||
let count = r.varint()?;
|
||||
if r.varint()? != 0 {
|
||||
return Err(Error::new("item cost components are not supported"));
|
||||
}
|
||||
Ok(NetCost { item, count })
|
||||
}
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut out = Vec::with_capacity(n.min(64));
|
||||
for _ in 0..n {
|
||||
let cost_a = cost(r)?;
|
||||
let result = Slot::read(r)?.ok_or_else(|| Error::new("empty merchant result"))?;
|
||||
let cost_b = if r.bool()? { Some(cost(r)?) } else { None };
|
||||
out.push(NetOffer {
|
||||
cost_a,
|
||||
result,
|
||||
cost_b,
|
||||
out_of_stock: r.bool()?,
|
||||
uses: r.i32()?,
|
||||
max_uses: r.i32()?,
|
||||
xp: r.i32()?,
|
||||
special_price: r.i32()?,
|
||||
price_multiplier: r.f32()?,
|
||||
demand: r.i32()?,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn write(v: &Vec<NetOffer>, w: &mut Writer) {
|
||||
fn cost(c: &NetCost, w: &mut Writer) {
|
||||
w.varint(c.item);
|
||||
w.varint(c.count);
|
||||
w.varint(0);
|
||||
}
|
||||
w.varint(v.len() as i32);
|
||||
for o in v {
|
||||
cost(&o.cost_a, w);
|
||||
Slot::write(&Some(o.result.clone()), w);
|
||||
w.bool(o.cost_b.is_some());
|
||||
if let Some(b) = &o.cost_b {
|
||||
cost(b, w);
|
||||
}
|
||||
w.bool(o.out_of_stock);
|
||||
w.i32(o.uses);
|
||||
w.i32(o.max_uses);
|
||||
w.i32(o.xp);
|
||||
w.i32(o.special_price);
|
||||
w.f32(o.price_multiplier);
|
||||
w.i32(o.demand);
|
||||
}
|
||||
}
|
||||
}
|
||||
packet!(
|
||||
/// ClientboundMerchantOffersPacket.
|
||||
MerchantOffers {
|
||||
container: i32 => VarInt,
|
||||
offers: Vec<NetOffer> => Offers,
|
||||
level: i32 => VarInt,
|
||||
xp: i32 => VarInt,
|
||||
show_progress: bool => Bool,
|
||||
can_restock: bool => Bool,
|
||||
}
|
||||
);
|
||||
packet!(ContainerSetData { container: i32 => VarInt, id: i16 => Short, value: i16 => Short });
|
||||
packet!(ContainerSetSlot { container: i32 => VarInt, state: i32 => VarInt, slot: i16 => Short, item: Option<Stack> => Slot });
|
||||
/// A holder reference: registry id + 1, or 0 for an inline value (unsupported).
|
||||
@@ -921,6 +1009,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
MoveEntityPos(MoveEntityPos) = MOVE_ENTITY_POS,
|
||||
MoveEntityPosRot(MoveEntityPosRot) = MOVE_ENTITY_POS_ROT,
|
||||
MoveEntityRot(MoveEntityRot) = MOVE_ENTITY_ROT,
|
||||
MerchantOffers(MerchantOffers) = MERCHANT_OFFERS,
|
||||
OpenScreen(OpenScreen) = OPEN_SCREEN,
|
||||
Ping(Ping) = PING,
|
||||
PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES,
|
||||
@@ -1037,6 +1126,7 @@ packet!(
|
||||
carried: Option<Hashed> => HashedSlot,
|
||||
}
|
||||
);
|
||||
packet!(SelectTrade { item: i32 => VarInt });
|
||||
packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool });
|
||||
packet!(
|
||||
/// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision.
|
||||
@@ -1111,6 +1201,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
Pong(Ping) = PONG,
|
||||
Punch(Empty) = PUNCH,
|
||||
ResourcePack(ResourcePackResponse) = RESOURCE_PACK,
|
||||
SelectTrade(SelectTrade) = SELECT_TRADE,
|
||||
SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM,
|
||||
SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT,
|
||||
UseItem(UseItem) = USE_ITEM,
|
||||
@@ -1302,6 +1393,25 @@ mod tests {
|
||||
menu: 2,
|
||||
title: literal("Chest"),
|
||||
}),
|
||||
Clientbound::MerchantOffers(MerchantOffers {
|
||||
container: 3,
|
||||
offers: vec![NetOffer {
|
||||
cost_a: NetCost { item: 5, count: 24 },
|
||||
result: Stack::new(7, 1),
|
||||
cost_b: Some(NetCost { item: 9, count: 1 }),
|
||||
out_of_stock: false,
|
||||
uses: 2,
|
||||
max_uses: 16,
|
||||
xp: 2,
|
||||
special_price: -3,
|
||||
price_multiplier: 0.05,
|
||||
demand: 4,
|
||||
}],
|
||||
level: 2,
|
||||
xp: 12,
|
||||
show_progress: true,
|
||||
can_restock: true,
|
||||
}),
|
||||
Clientbound::PlayerChat(PlayerChat {
|
||||
global_index: 0,
|
||||
sender: 5,
|
||||
@@ -1499,6 +1609,11 @@ mod tests {
|
||||
}
|
||||
round_trip(p, Serverbound::encode, Serverbound::decode);
|
||||
}
|
||||
round_trip(
|
||||
Serverbound::SelectTrade(SelectTrade { item: 3 }),
|
||||
Serverbound::encode,
|
||||
Serverbound::decode,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user