Trading on the dedicated server, compared with vanilla's

test_dedicated_server_parity summons a librarian beside the spawn and the
vanilla protocol client right-clicks it: the OpenScreen packet (title as
Entity.getDisplayName, UUIDs left out) and the MerchantOffers packet must
match vanilla's server. Villagers keep Xp, LastRestock and RestocksToday
before their offers are made (vanilla's null offers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 23:01:02 +02:00
parent 5cb14ee496
commit 92209ddeee
6 changed files with 119 additions and 10 deletions
+9 -4
View File
@@ -1256,7 +1256,9 @@ 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 Some(t) = m.extra.trade.as_ref().filter(|t| !t.unset) else {
return;
};
map.insert("Offers".into(), offers_to_nbt(&t.offers));
}
/// `ItemCost.CODEC`: id, count (always written) and the exact components.
@@ -1395,11 +1397,14 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
if m.species() == crate::mobs::Species::Villager {
crate::mobs::villager::read_nbt(m, tag);
}
let Some(offers_tag) = tag.get("Offers") else {
let offers_tag = tag.get("Offers");
let xp = number(tag.get("Xp")).unwrap_or(0) as i32;
if offers_tag.is_none() && xp == 0 && tag.get("LastRestock").is_none() {
return;
};
let offers = offers_from_nbt(offers_tag);
}
let offers = offers_tag.map(offers_from_nbt).unwrap_or_default();
m.extra.trade = Some(Box::new(Trader {
unset: offers_tag.is_none(),
xp: number(tag.get("Xp")).unwrap_or(0) as i32,
offers,
last_restock: number(tag.get("LastRestock")).unwrap_or(0),
+55 -1
View File
@@ -54,7 +54,7 @@ impl Game<'_> {
state.session.hero = None;
state.session.update_special_prices();
}
let title = horizon_protocol::text::literal(&self.merchant_title(&state));
let title = self.merchant_display_name(&state);
let Some(window) = host.hub.open_merchant_window(conn, title) else {
self.merchant_closed(&mut state);
return;
@@ -71,8 +71,62 @@ impl Game<'_> {
self.lan_send_merchant_content(host, conn, &mut gm);
host.play.entry(conn).or_default().merchant = Some(gm);
}
/// `Entity.getDisplayName` of the merchant, the screen's title: its name
/// (custom, else the profession's) with the show_entity hover event and
/// its UUID as insertion.
fn merchant_display_name(&mut self, state: &MerchantState) -> horizon_world::nbt::Tag {
use horizon_world::nbt::Tag;
let s = &state.session;
let (kind, key) = if s.villager {
let p = s.profession.trim_start_matches("minecraft:");
(
"minecraft:villager",
format!("entity.minecraft.villager.{p}"),
)
} else {
(
"minecraft:wandering_trader",
"entity.minecraft.wandering_trader".to_owned(),
)
};
let name = match &state.name {
Some(n) => horizon_protocol::text::literal(n),
None => Tag::compound([("translate", Tag::String(key.as_str().into()))]),
};
let uuid = state.mob.map_or([0; 4], |id| self.mob_uuid(id));
let w = uuid.map(|v| v as u32);
let text = format!(
"{:08x}-{:04x}-{:04x}-{:04x}-{:04x}{:08x}",
w[0],
w[1] >> 16,
w[1] & 0xffff,
w[2] >> 16,
w[2] & 0xffff,
w[3]
);
let mut out = match name.clone() {
Tag::Compound(c) => c,
other => {
let mut c = horizon_world::nbt::Compound::new();
c.insert("text".into(), other);
c
}
};
out.insert(
"hover_event".into(),
Tag::compound([
("action", Tag::String("show_entity".into())),
("id", Tag::String(kind.into())),
("uuid", Tag::IntArray(uuid.to_vec())),
("name", name),
]),
);
out.insert("insertion".into(), Tag::String(text.as_str().into()));
Tag::Compound(out)
}
/// The screen title: the custom name, else the profession (the client
/// adds the level itself).
#[allow(dead_code)]
fn merchant_title(&self, state: &MerchantState) -> String {
if let Some(name) = &state.name {
return name.clone();
+9 -5
View File
@@ -179,7 +179,12 @@ impl Game<'_> {
/// `AbstractVillager.getOffers`: generated on first use.
pub(super) fn ensure_offers(&mut self, index: usize) {
let species = self.mobs[index].species();
if self.mobs[index].extra.trade.is_none() {
let unset = self.mobs[index]
.extra
.trade
.as_ref()
.is_none_or(|t| t.unset);
if unset {
let m = &self.mobs[index];
let variant = format!(
"minecraft:{}",
@@ -206,10 +211,9 @@ impl Game<'_> {
Vec::new()
}
};
self.mobs[index].extra.trade = Some(Box::new(merchant::Trader {
offers,
..Default::default()
}));
let trade = self.mobs[index].extra.trade.get_or_insert_default();
trade.offers = offers;
trade.unset = false;
}
}
/// `Villager.mobInteract` / `WanderingTrader.mobInteract`: shake the
+3
View File
@@ -57,6 +57,9 @@ pub struct Trader {
pub last_restock: i64,
pub restocks_today: i32,
pub check_day: i64,
/// The offers are not made yet (vanilla's `offers` is null): they are
/// generated when first asked for, keeping the experience.
pub unset: bool,
}
impl Trader {
fn update_demand(&mut self) {
@@ -430,6 +430,9 @@ public final class VanillaProtocolClient {
long deadline = System.currentTimeMillis() + 90_000;
int step = 0;
long stepAt = 0;
// The villager the server's console summoned beside the spawn.
int villager = -1;
net.minecraft.world.phys.Vec3 villagerAt = null;
while (System.currentTimeMillis() < deadline) {
Received r;
try {
@@ -474,6 +477,28 @@ public final class VanillaProtocolClient {
+ p.chatType().targetName().map(VanillaProtocolClient::json));
} else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0) {
record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName());
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p
&& p.getType() == net.minecraft.world.entity.EntityTypes.VILLAGER) {
villager = p.getId();
villagerAt = new net.minecraft.world.phys.Vec3(p.getX(), p.getY(), p.getZ());
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundOpenScreenPacket p && step > 0) {
record("play-trade", "open " + p.getContainerId() + " "
+ net.minecraft.core.registries.BuiltInRegistries.MENU.getKey(p.getType()) + " "
// The villager's UUID is each server's own.
+ json(p.getTitle()).replaceAll("\"uuid\":\\[[^\\]]*\\]", "\"uuid\":\"<uuid>\"")
.replaceAll("\"insertion\":\"[^\"]*\"", "\"insertion\":\"<uuid>\""));
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundMerchantOffersPacket p && step > 0) {
StringBuilder sb = new StringBuilder("offers " + p.getContainerId() + " " + p.getVillagerLevel() + " "
+ p.getVillagerXp() + " " + p.showProgress() + " " + p.canRestock());
for (var o : p.getOffers()) {
sb.append(" | ").append(o.getItemCostA()).append(' ').append(o.getItemCostB()).append(' ')
.append(net.minecraft.world.item.ItemStack.CODEC.encodeStart(
ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), o.getResult()).getOrThrow())
.append(' ').append(o.isOutOfStock()).append(' ').append(o.getUses()).append(' ').append(o.getMaxUses())
.append(' ').append(o.getXp()).append(' ').append(o.getSpecialPriceDiff()).append(' ')
.append(Float.floatToRawIntBits(o.getPriceMultiplier())).append(' ').append(o.getDemand());
}
record("play-trade", sb.toString());
} else if (packet instanceof ClientboundDisconnectPacket p) {
record("play", r.type + " " + json(p.reason()));
break;
@@ -521,6 +546,20 @@ public final class VanillaProtocolClient {
step++;
stepAt = now;
} else if (step == 2 + REPLIES.length && now - stepAt > 1500) {
// Right-click the villager: the trading screen and its offers.
record("play-trade", "villager " + (villager >= 0));
if (villager >= 0) {
send(new net.minecraft.network.protocol.game.ServerboundInteractPacket(villager,
net.minecraft.world.InteractionHand.MAIN_HAND, new net.minecraft.world.phys.Vec3(0.0, 1.0, 0.0), false));
}
step++;
stepAt = now;
} else if (step == 3 + REPLIES.length && now - stepAt > 1500) {
send(new net.minecraft.network.protocol.game.ServerboundSelectTradePacket(0));
step++;
stepAt = now;
} else if (step == 4 + REPLIES.length && now - stepAt > 1500) {
send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(1));
record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0));
return;
}
+4
View File
@@ -240,6 +240,10 @@ def run_side(label, command, directory, client):
server = Server(command, directory, label)
try:
server.wait_for(r'Done \(')
# A librarian beside the spawn for the client to trade with (no AI:
# it stays put; experience keeps its profession).
server.console('summon minecraft:villager ~1 ~ ~ {NoAI:1b,Xp:1,VillagerData:'
'{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}')
port = int(PROPERTIES_PORTS[label])
legacy = legacy_ping(port)
client(port, directory.parent / f'{label}-client.txt')