Stonecutter on the menu engine; LAN guests use stonecutters

StonecutterMenu joins horizon_client::menu (Kind::Stonecutter): the input's
recipe list (slotsChanged / setupRecipeList), selectedRecipeIndex as its data
slot, clickMenuButton (an invalid index is taken too), the result's onTake
(one input used up, awardUsedRecipes, the take sound) and quickMoveStack with
the leftover of a result move dropped. test_menu_click_parity compares it
with vanilla's StonecutterMenu, recipe buttons included.

Single player's stonecutter screen now clicks through the engine (drags and
double clicks included), and its recipe grid calls clickMenuButton as
StonecutterScreen does. A LAN guest's stonecutter opens minecraft:stonecutter
on the host's engine, as the loom does (#868).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-22 04:40:04 +02:00
parent cd37ea98a0
commit c8f02d91b7
18 changed files with 335 additions and 109 deletions
@@ -82,11 +82,13 @@ fn main() -> horizon_client::Result<()> {
let brewing = horizon_client::brewing::Brewing::load(root, &items);
// The inventory menu never reads banner patterns.
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
trade: None,
};
let mut out = String::new();
@@ -44,11 +44,13 @@ fn main() -> horizon_client::Result<()> {
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::load(root);
let station_recipes = horizon_client::stations::StationRecipes::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
trade: None,
};
let mut out = String::new();
@@ -38,11 +38,13 @@ fn main() -> horizon_client::Result<()> {
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
trade: None,
};
let mut out = String::new();
@@ -243,6 +243,7 @@ fn main() -> horizon_client::Result<()> {
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 station_recipes = horizon_client::stations::StationRecipes::default();
let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)?
.types
.into_iter()
@@ -378,6 +379,7 @@ fn main() -> horizon_client::Result<()> {
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
trade: Some(&env_trade),
};
trade(&mut out, name, &kv, &mut world, &env, origin)?;
+32 -1
View File
@@ -5425,6 +5425,10 @@ impl Game<'_> {
.station
.as_ref()
.is_some_and(|s| s.kind == stations::Kind::Merchant);
let stonecutter_open = self
.station
.as_ref()
.is_some_and(|s| s.kind == stations::Kind::Stonecutter);
let (kind, game_of): (Kind, Vec<Option<usize>>) = if self.creative_tab_open() {
// ItemPickerMenu: the display slots (clicked by the screen), then the hotbar.
let mut v = vec![None; 45];
@@ -5451,6 +5455,11 @@ impl Game<'_> {
v.push(Some(stations::RESULT));
v.extend((9..36).chain(0..9).map(Some));
(Kind::Loom, v)
} else if stonecutter_open {
// StonecutterMenu: the input, the result, then the inventory.
let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Stonecutter, v)
} else {
let (kind, map) = if self.container.is_some() {
let size = self.container_size();
@@ -5533,6 +5542,10 @@ impl Game<'_> {
s.loom.patterns.clone(),
)
});
let stone = self
.station
.as_ref()
.map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone()));
let crafter_data = match self.container_kind() {
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
_ => None,
@@ -5564,6 +5577,7 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
trade: Some(&trade_env),
};
menu.creative = creative;
@@ -5585,6 +5599,14 @@ impl Game<'_> {
menu.loom_patterns = patterns;
menu.set_slot(&env, 3, before[3].clone());
}
if kind == Kind::Stonecutter
&& let Some((selected, state)) = stone
{
// The same: the list and selection between clicks, then the result.
menu.data[0] = selected;
menu.stone = state;
menu.set_slot(&env, 1, before[1].clone());
}
if let Some((disabled, triggered)) = crafter_data {
for (i, d) in disabled.iter().enumerate() {
menu.data[i] = i32::from(*d);
@@ -5641,9 +5663,18 @@ impl Game<'_> {
}
// A server's loom plays its own sounds (the client's menu has no level).
for sound in sounds.into_iter().filter(|_| !predicting) {
self.loom_sound(sound);
self.station_sound(sound);
}
self.loom_screen_changed();
} else if kind == Kind::Stonecutter {
if let Some(s) = self.station.as_mut() {
s.selected = usize::try_from(menu.data[0]).ok();
s.stone = std::mem::take(&mut menu.stone);
s.stonecutter_changed();
}
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
}
if kind == Kind::CrafterBlock
&& let Some(BlockEntity::Crafter(c)) = self
@@ -89,6 +89,7 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
trade: None,
}
}
@@ -34,6 +34,7 @@ pub(super) struct GuestStation {
fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range<usize>)> {
Some(match kind {
StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3),
StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1),
_ => return None,
})
}
@@ -255,6 +255,7 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
trade: Some(&trade_env),
};
let mut menu = Menu::new(Kind::Merchant);
+3 -2
View File
@@ -68,8 +68,9 @@ impl Game<'_> {
}
l.last_inputs = inputs;
}
/// A sound the loom menu played: the result's once per tick.
pub(super) fn loom_sound(&mut self, sound: &str) {
/// A sound the loom or stonecutter menu played: the result's once per
/// tick (`lastSoundTime`).
pub(super) fn station_sound(&mut self, sound: &str) {
let ticks = self.ticks;
let Some(s) = self.station.as_mut() else {
return;
@@ -279,6 +279,7 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
trade: None,
};
for i in 0..36 {
+1
View File
@@ -1236,6 +1236,7 @@ impl Game<'_> {
use super::stations::Kind;
Some(match menu {
"minecraft:loom" => Kind::Loom,
"minecraft:stonecutter" => Kind::Stonecutter,
_ => return None,
})
}
@@ -46,9 +46,13 @@ impl Game<'_> {
/// The server set station slot `internal`: the client menu's
/// `Slot.set` runs its container's `setChanged`, so the loom lists the
/// patterns its inputs allow.
/// patterns its inputs allow and the stonecutter the recipes of its input.
pub(super) fn remote_station_slot_changed(&mut self, internal: usize) {
if !self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom) {
if !self
.station
.as_ref()
.is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter))
{
return;
}
self.menu_session(|menu, env, to_menu| {
@@ -64,9 +68,12 @@ impl Game<'_> {
let Some(s) = self.station.as_mut() else {
return;
};
// LoomMenu.selectedBannerPatternIndex.
if (s.kind, id) == (Kind::Loom, 0) {
s.loom.selected = usize::try_from(value).ok();
match (s.kind, id) {
// LoomMenu.selectedBannerPatternIndex.
(Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(),
// StonecutterMenu.selectedRecipeIndex.
(Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(),
_ => {}
}
}
+64 -89
View File
@@ -13,7 +13,6 @@ use horizon_client::{
stations::{self, AnvilResult, EnchantOffers},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::sync::Arc;
/// Slot ids of the open station: inputs from 600, the result at 650.
pub(super) const INPUT: usize = 600;
@@ -137,11 +136,11 @@ pub(super) struct Station {
anvil: AnvilResult,
/// Anvil rename box text.
pub(super) name: String,
/// Stonecutter: recipe indices for the input, selection and first shown index.
recipes: Vec<usize>,
selected: Option<usize>,
/// Stonecutter: the menu's recipe list (horizon_client::menu), its
/// `selectedRecipeIndex` and the screen's first shown index.
pub(super) stone: horizon_client::menu::Stonecutter,
pub(super) selected: Option<usize>,
start: usize,
input_item: Option<Arc<str>>,
/// Anvil: the input the rename box was last filled from.
anvil_last: Option<ItemStack>,
/// When the screen opened: the rename box has the focus from then.
@@ -165,10 +164,9 @@ impl Station {
bookcases: 0,
anvil: AnvilResult::default(),
name: String::new(),
recipes: Vec::new(),
stone: Default::default(),
selected: None,
start: 0,
input_item: None,
anvil_last: None,
opened: std::time::Instant::now(),
last_sound: 0,
@@ -180,6 +178,13 @@ impl Station {
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
Self::new(kind, pos)
}
/// `StonecutterScreen.containerChanged`: without recipes to show, the
/// list scrolls back to the top.
pub(super) fn stonecutter_changed(&mut self) {
if self.inputs[0].is_none() || self.stone.recipes.is_empty() {
self.start = 0;
}
}
}
/// The 108x19 enchantment button `i` (relative to the GUI origin).
@@ -476,32 +481,8 @@ impl Game<'_> {
Kind::Cartography => s.result = self.cartography_result(&s),
// The menu engine keeps the loom's state (Game::menu_session).
Kind::Loom => {}
Kind::Stonecutter => {
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
if item != s.input_item {
s.input_item = item;
s.selected = None;
s.start = 0;
s.recipes = match &s.inputs[0] {
Some(input) => data
.recipes
.stonecutting
.iter()
.enumerate()
.filter(|(_, r)| r.input.test(input))
.map(|(i, _)| i)
.collect(),
None => Vec::new(),
};
}
s.result = match (s.selected, &s.inputs[0]) {
(Some(i), Some(_)) => s
.recipes
.get(i)
.map(|&r| data.recipes.stonecutting[r].result.clone()),
_ => None,
};
}
// The menu engine keeps the stonecutter's state (Game::menu_session).
Kind::Stonecutter => {}
}
self.station = Some(s);
}
@@ -718,13 +699,6 @@ impl Game<'_> {
self.move_to(&mut stack, &halves, false);
}
}
Kind::Stonecutter => {
if self.data().recipes.stonecutter(&stack).is_empty() {
self.move_to(&mut stack, &halves, false);
} else {
self.move_to(&mut stack, &[INPUT], false);
}
}
Kind::Cartography => {
if super::maps::map_id(&stack).is_some() {
self.move_to(&mut stack, &[INPUT], false);
@@ -750,7 +724,7 @@ impl Game<'_> {
self.move_to(&mut stack, targets, false);
}
// Their clicks run on the menu engine.
Kind::Merchant | Kind::Loom => {}
Kind::Merchant | Kind::Loom | Kind::Stonecutter => {}
}
}
let moved = stack.count != start;
@@ -886,19 +860,7 @@ impl Game<'_> {
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch);
}
Kind::Stonecutter => {
if let Some(x) = s.inputs[0].as_mut() {
x.count -= 1;
if x.count == 0 {
s.inputs[0] = None;
}
}
if s.last_sound != self.ticks {
s.last_sound = self.ticks;
self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0);
}
}
Kind::Merchant => {}
Kind::Merchant | Kind::Stonecutter => {}
Kind::Beacon => {}
Kind::Cartography => {
for slot in &mut s.inputs {
@@ -1044,7 +1006,7 @@ impl Game<'_> {
})
.collect(),
Kind::Stonecutter if s.inputs[0].is_some() => (s.start
..(s.start + 12).min(s.recipes.len()))
..(s.start + 12).min(s.stone.recipes.len()))
.map(|index| {
let p = index - s.start;
[
@@ -1097,29 +1059,8 @@ impl Game<'_> {
}
}
}
if kind == Kind::Stonecutter
&& let Some(s) = self.station.as_ref()
&& s.inputs[0].is_some()
{
for index in s.start..(s.start + 12).min(s.recipes.len()) {
let p = index - s.start;
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
if inside(local, x, y, 16.0, 18.0) {
if s.selected != Some(index) {
if let Some(st) = self.station.as_mut() {
st.selected = Some(index);
}
self.audio.play(
"minecraft:ui.stonecutter.select_recipe",
None,
1.0,
1.0,
);
self.station_changed();
}
return true;
}
}
if kind == Kind::Stonecutter && self.stonecutter_click(local) {
return true;
}
}
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
@@ -1128,10 +1069,10 @@ impl Game<'_> {
if self
.station
.as_ref()
.is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant))
.is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter))
{
// LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu
// clicks run on the verified menu engine.
// LoomMenu, MerchantMenu, StonecutterMenu and the brewing stand's
// BrewingStandMenu clicks run on the verified menu engine.
let input = if shift {
horizon_client::menu::Input::QuickMove
} else {
@@ -1172,16 +1113,49 @@ impl Game<'_> {
}
self.station_changed();
}
/// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton`
/// with the cell's index (an empty cell's too), and the select sound when
/// the menu took it.
fn stonecutter_click(&mut self, local: (f32, f32)) -> bool {
let Some(start) = self
.station
.as_ref()
.filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty())
.map(|s| s.start)
else {
return false;
};
for index in start..start + 12 {
let p = index - start;
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
if !inside(local, x, y, 16.0, 18.0) {
continue;
}
let mut taken = false;
let flag = &mut taken;
self.menu_session(|menu, env, _| {
*flag = menu.button(env, index as i32);
Some(*flag)
});
if taken {
self.audio
.play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0);
self.remote_station_button(index as i32);
return true;
}
}
false
}
pub(super) fn station_scroll(&mut self, d: f32) {
self.merchant_scroll(d);
self.loom_scroll(d);
let Some(s) = self.station.as_mut() else {
return;
};
if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 {
if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 {
return;
}
let rows = s.recipes.len().div_ceil(4) - 3;
let rows = s.stone.recipes.len().div_ceil(4) - 3;
let first_row = (s.start / 4) as i32 - d.signum() as i32;
s.start = first_row.clamp(0, rows as i32) as usize * 4;
}
@@ -1748,9 +1722,9 @@ impl Game<'_> {
}
Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {}
Kind::Stonecutter => {
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
let active = display && s.recipes.len() > 12;
let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1);
let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty();
let active = display && s.stone.recipes.len() > 12;
let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1);
let offs = if active {
(s.start / 4) as f32 / rows as f32
} else {
@@ -1771,13 +1745,14 @@ impl Game<'_> {
let (start, selected) = (s.start, s.selected);
// graphics.item: the icon only, without the count.
let shown: Vec<(usize, ItemStack)> = (start
..(start + 12).min(s.recipes.len()))
..(start + 12).min(s.stone.recipes.len()))
.map(|i| {
(
i,
ItemStack {
count: 1,
..self.res.stations().recipes.stonecutting[s.recipes[i]]
..self.res.stations().recipes.stonecutting
[s.stone.recipes[i]]
.result
.clone()
},
@@ -2090,7 +2065,7 @@ impl Game<'_> {
"bookcases": s.bookcases,
"anvil_cost": s.anvil.cost,
"result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)),
"recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
"recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
"selected": s.selected,
})
}
+133 -7
View File
@@ -3,8 +3,8 @@
//! 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`), the loom (`clickMenuButton`, `slotsChanged`) and the
//! merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the
//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`), the
//! stonecutter (its recipe buttons and result) 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.
@@ -24,6 +24,8 @@ pub struct Env<'a> {
pub recipes: &'a Recipes,
pub brewing: &'a Brewing,
pub banners: &'a Banners,
/// The stonecutter's recipes.
pub station_recipes: &'a crate::stations::StationRecipes,
/// What a merchant menu needs for offers made while it is open (level-ups).
pub trade: Option<&'a crate::merchant::TradeEnv<'a>>,
}
@@ -71,6 +73,8 @@ pub enum Kind {
/// result follows the grid, and filling a disabled slot enables it.
CrafterBlock,
Loom,
/// `StonecutterMenu`: the input, the result, then the inventory.
Stonecutter,
/// `MerchantMenu`: two payment slots, the result, then the inventory.
Merchant,
/// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45
@@ -96,6 +100,7 @@ impl Kind {
"crafter" => Self::Crafter,
"crafter_be" => Self::CrafterBlock,
"loom" => Self::Loom,
"stonecutter" => Self::Stonecutter,
"merchant" => Self::Merchant,
"item_picker" => Self::ItemPicker,
_ => return None,
@@ -133,6 +138,8 @@ enum Role {
LoomResult,
/// `MerchantResultSlot`.
MerchantResult,
/// The stonecutter's result slot (`onTake` uses up one input).
StoneResult,
/// `CustomCreativeSlot`: a creative tab's display slot, which the
/// screen clicks itself; drags and PICKUP_ALL pass it by.
CreativeDisplay,
@@ -182,6 +189,19 @@ pub struct Menu {
pub equipped: Vec<(&'static str, Option<ItemStack>)>,
/// The merchant a merchant menu trades with.
pub merchant: Option<Box<crate::merchant::Session>>,
/// The stonecutter's recipe list (`recipesForInput`).
pub stone: Stonecutter,
}
/// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`.
#[derive(Clone, Default, Debug, PartialEq)]
pub struct Stonecutter {
/// `recipesForInput`: indices into `StationRecipes.stonecutting`.
pub recipes: Vec<usize>,
/// The item the list was made for (`input`; None for nothing).
pub input: Option<Arc<str>>,
/// `ResultContainer.recipeUsed`.
pub used: Option<usize>,
}
fn same_item(a: &ItemStack, b: &ItemStack) -> bool {
@@ -318,6 +338,18 @@ impl Menu {
player(&mut slots);
data = 1;
}
Kind::Stonecutter => {
containers[MAIN] = vec![None; 1];
slots.extend(main(1, Role::Plain));
slots.push(Slot {
container: RESULT,
index: 0,
role: Role::StoneResult,
});
player(&mut slots);
// selectedRecipeIndex: DataSlot.standalone() starts at 0.
data = 1;
}
Kind::ItemPicker => {
containers[MAIN] = vec![None; 45];
slots.extend(main(45, Role::CreativeDisplay));
@@ -403,6 +435,7 @@ impl Menu {
crafted: Vec::new(),
equipped: Vec::new(),
merchant: None,
stone: Stonecutter::default(),
}
}
@@ -410,8 +443,20 @@ impl Menu {
self.kind
}
/// `clickMenuButton`: the loom's pattern buttons. False when refused.
/// `clickMenuButton`: the loom's pattern buttons and the stonecutter's
/// recipes. False when refused.
pub fn button(&mut self, env: &Env, id: i32) -> bool {
if self.kind == Kind::Stonecutter {
// StonecutterMenu.clickMenuButton: an invalid index is taken too.
if self.data[0] == id {
return false;
}
if id >= 0 && (id as usize) < self.stone.recipes.len() {
self.data[0] = id;
self.stone_setup_result(env, id);
}
return true;
}
if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() {
return false;
}
@@ -510,8 +555,42 @@ impl Menu {
}
}
/// `StonecutterMenu.slotsChanged`: a new input item lists its recipes
/// (`setupRecipeList`), with none selected and no result.
fn stone_changed(&mut self, env: &Env) {
let input = self.containers[MAIN][0].as_ref().map(|s| s.item.clone());
if input == self.stone.input {
return;
}
self.stone.input = input;
self.data[0] = -1;
self.containers[RESULT][0] = None;
self.stone.recipes = match &self.containers[MAIN][0] {
Some(stack) => env
.station_recipes
.stonecutting
.iter()
.enumerate()
.filter(|(_, r)| r.input.test(stack))
.map(|(i, _)| i)
.collect(),
None => Vec::new(),
};
}
/// `StonecutterMenu.setupResultSlot`.
fn stone_setup_result(&mut self, env: &Env, index: i32) {
let recipe = usize::try_from(index)
.ok()
.and_then(|i| self.stone.recipes.get(i).copied());
self.stone.used = recipe;
self.containers[RESULT][0] =
recipe.map(|r| env.station_recipes.stonecutting[r].result.clone());
}
/// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs,
/// the block crafter refreshes its result.
/// the stonecutter lists its recipes, 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 {
@@ -523,6 +602,7 @@ impl Menu {
}
match self.kind {
Kind::Loom => self.loom_changed(env),
Kind::Stonecutter => self.stone_changed(env),
Kind::CrafterBlock => self.crafter_result(env),
_ => {}
}
@@ -634,7 +714,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 | Role::MerchantResult => false,
Role::LoomResult | Role::MerchantResult | Role::StoneResult => false,
}
}
@@ -763,7 +843,7 @@ impl Menu {
}
// 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) {
if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter) {
self.slot_changed(env, s);
}
out
@@ -787,6 +867,19 @@ impl Menu {
self.merchant_take(env);
return;
}
if self.slots[s].role == Role::StoneResult {
// StonecutterMenu's result onTake: awardUsedRecipes, one input
// used up, the result again for the selected recipe.
if let Some(r) = self.stone.used {
self.crafted
.push(env.station_recipes.stonecutting[r].id.clone());
}
if self.remove(env, 0, 1).is_some() {
self.stone_setup_result(env, self.data[0]);
}
self.sounds.push("minecraft:ui.stonecutter.take_result");
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);
@@ -1231,6 +1324,34 @@ impl Menu {
return None;
}
}
Kind::Stonecutter => {
after_take = true;
if index == 1 {
if !self.move_to(env, &mut stack, 2, 38, true) {
return None;
}
} else if index == 0 {
if !self.move_to(env, &mut stack, 2, 38, false) {
return None;
}
} else if env
.station_recipes
.stonecutting
.iter()
.any(|r| r.input.test(&stack))
{
if !self.move_to(env, &mut stack, 0, 1, false) {
return None;
}
} else if (2..29).contains(&index) {
if !self.move_to(env, &mut stack, 29, 38, false) {
return None;
}
} else if (29..38).contains(&index) && !self.move_to(env, &mut stack, 2, 29, false)
{
return None;
}
}
Kind::Merchant => {
after_take = true;
if index == 2 {
@@ -1369,7 +1490,10 @@ impl Menu {
if after_take || matches!(self.kind, Kind::Inventory | Kind::Crafting) {
self.on_take(env, index);
}
if index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting) {
// What the result slot's move left over is dropped.
if (index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting))
|| (index == 1 && self.kind == Kind::Stonecutter)
{
self.drop_stack(&stack);
}
Some(clicked)
@@ -2023,11 +2147,13 @@ pub(crate) mod tests {
let recipes = Recipes::load(&root, &items).unwrap();
let brewing = Brewing::load(&root, &items);
let banners = Banners::load(&root);
let station_recipes = crate::stations::StationRecipes::load(&root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
trade: None,
};
let mut menu = Menu::new(kind);
+1
View File
@@ -450,6 +450,7 @@ pub struct Stonecutting {
pub input: Ingredient,
pub result: ItemStack,
}
#[derive(Default)]
pub struct StationRecipes {
pub smithing: Vec<Smithing>,
/// Sorted by recipe id, the registry order vanilla lists them in.
@@ -178,6 +178,7 @@ public final class VanillaMenuOracle {
}
}
case "loom" -> new LoomMenu(0, inv);
case "stonecutter" -> new StonecutterMenu(0, inv);
default -> throw new IllegalArgumentException(kind);
};
}
+47 -1
View File
@@ -39,6 +39,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- loom: a loom opens on the guest's screen; the banner and dye the guest shift-clicks go to their
slots, a pattern button the guest clicks makes the server's result, and the guest takes the
patterned banner (#868);
- stonecutter: a stonecutter opens on the guest's screen with the recipes of the stone the guest puts
in; the guest picks the slab and shift-clicks the result, and the server has cut every
stone into slabs (#868);
- feedback: the guest's command feedback names the guest and shows the numbers;
- chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the
server thread the host window's too;
@@ -133,7 +136,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
class Game:
@@ -948,6 +951,48 @@ def check_loom(host, guest, out):
return seen
def server_count(guest, item):
"""How many of `item` the server says the guest has (`clear` with a count of 0 only counts)."""
since = guest.raw('events')['last']
guest('command', command=f'clear @s minecraft:{item} 0')
for n in range(0, 65):
reply = guest.raw('events', '--since', since)
lines = [e.get('text', '') for e in reply['events'] if e.get('event') == 'chat']
for line in lines:
if 'matching item' in line or 'No items were found' in line:
return 0 if 'No items' in line else int(line.split('Found ')[1].split(' ')[0])
guest.wait(2)
raise Failed(f'no answer to clear for {item}')
def check_stonecutter(host, guest, out):
guest('command', command='gamemode survival')
guest('command', command='clear @s')
guest('command', command='give @s minecraft:stone 3')
at = open_station(guest, 'stonecutter', out, 'stonecutter')
# StonecutterMenu.quickMoveStack: stone has recipes, so it goes to the input.
guest.raw('click-slot', hotbar_slot(guest, 'minecraft:stone'), 'shift')
guest.wait(10)
recipes = guest.raw('menu')['info']['recipes']
index = recipes.index('minecraft:stone_slab_from_stone_stonecutting')
# StonecutterScreen's recipe grid: four columns of 16x18 cells from (52, 14).
guest.raw('click-gui', 52 + index % 4 * 16 + 8, 14 + index // 4 * 18 + 9)
guest.wait(10)
picked = (guest.raw('menu')['info']['selected'], station_slots(guest).get(650))
guest.shot(out, 'stonecutter-recipe')
# A shift-click on the result cuts while there is stone (doClick repeats quickMoveStack).
guest.raw('click-slot', 650, 'shift')
guest.wait(10)
left = station_slots(guest)
close_station(guest, at)
seen = {'picked': picked, 'left': left,
'server': {item: server_count(guest, item) for item in ('stone_slab', 'stone')}}
want = {'picked': (index, ('minecraft:stone_slab', 2)), 'left': {},
'server': {'stone_slab': 6, 'stone': 0}}
assert seen == want, f'the stonecutter on the guest: {seen}'
return seen
def slot_point(game, slot):
"""The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N)."""
for w in game.raw('ui')['widgets']:
@@ -2140,6 +2185,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'machines': check_machines,
'brewing': check_brewing,
'loom': check_loom,
'stonecutter': check_stonecutter,
'hurt': check_hurt,
'commands': check_commands,
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
+29 -4
View File
@@ -10,7 +10,8 @@ click: QUICK_MOVE on every slot of the clicked slot's container holding the
item the first click moved) over the player inventory,
crafting table, chests, hopper, dispenser, shulker box, the furnaces, the
brewing stand, the crafter (the client's menu, and the server's over the block
entity with slot state packets), the loom (with its pattern buttons) and the
entity with slot state packets), the loom (with its pattern buttons), the
stonecutter (with its recipe buttons) and the
server's furnace menus over their block entities (`*_be`: a new input restarts
cooking, other clicks keep its progress). After
every click the slots, carried stack, data slots and drops are compared.
@@ -26,8 +27,9 @@ except ImportError:
MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81,
'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46,
'crafter_be': 46, 'loom': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39}
'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39}
DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1,
'stonecutter': 1,
'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4}
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
@@ -40,6 +42,9 @@ COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_i
'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling',
'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder',
'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath']
# Stonecutter inputs (several recipes each), and a block it doesn't cut.
CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sandstone', 'quartz_block', 'deepslate',
'stone_bricks', 'oak_planks']
def quote(text):
@@ -97,6 +102,13 @@ class Gen:
return snbt(rng.choice(pool), 1)
return self.stack()
def cut_stack(self):
"""Mostly something the stonecutter cuts, sometimes anything."""
rng = self.rng
if rng.random() < 0.75:
return snbt('minecraft:' + rng.choice(CUTTABLE), rng.choice([1, 1, 2, 3, 10, 63, 64]))
return self.stack()
def recipe(self, slots, width, start=1):
"""Fills the crafting grid (slots `start`..) with a small known recipe."""
rng = self.rng
@@ -123,6 +135,13 @@ class Gen:
# The result: take it, shift it out, throw it.
out.append([3, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'THROW', 'SWAP'])])
continue
if menu == 'stonecutter' and rng.random() < 0.25:
# A recipe button (clickMenuButton), sometimes out of range or the selected one.
out.append([rng.choice([0, 0, 1, 2, 3, 5, 10, 30, -1]), 0, 'BUTTON'])
continue
if menu == 'stonecutter' and rng.random() < 0.2:
out.append([1, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])])
continue
if menu == 'crafter_be' and rng.random() < 0.2:
out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE'])
continue
@@ -183,6 +202,12 @@ def main():
slots[2] = g.loom_stack(0.6) if rng.random() < 0.4 else rng.choice(['-', '-', g.loom_stack()])
# The result slot follows the inputs; a fixture stack there is rare.
slots[3] = '-' if rng.random() < 0.9 else g.loom_stack()
if menu == 'stonecutter':
for i in rng.sample(range(2, size), 8):
slots[i] = g.cut_stack()
slots[0] = g.cut_stack() if rng.random() < 0.8 else '-'
# The result follows the input and the selected recipe; a fixture stack there is rare.
slots[1] = '-' if rng.random() < 0.9 else g.cut_stack()
if menu == 'crafter_be':
slots[45] = '-'
if rng.random() < 0.6:
@@ -208,10 +233,10 @@ def main():
return [rng.choice([0, 37, 1600]), 1600, rng.choice([0, 1, 57, 199]), rng.choice([200, 100])][i]
if menu in ('crafter', 'crafter_be'):
return rng.choice([0, 0, 1])
if menu == 'loom':
if menu in ('loom', 'stonecutter'):
return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30])
return 0
carried = (g.loom_stack() if menu == 'loom' else g.stack()) if rng.random() < 0.5 else '-'
carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-'
if carried_food is not None:
carried = carried_food
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,