From 69c7fd925eb22cd41f0105222e75822bdf03480a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:04:56 +0200 Subject: [PATCH 01/16] Port every crafting recipe type and test recipes against vanilla The crafting module now matches shapeless recipes with a full bipartite assignment, shrinks shaped patterns like ShapedRecipePattern, keeps result components (suspicious stew effects), and implements the transmute, dye, imbue (tipped arrow), book cloning, firework rocket/star/fade, decorated pot, repair item, map extending, banner duplicate and shield decoration recipes with vanilla's matching and assembly. Crafting remainders now follow Item.craftRemainder only and are placed on the grid by recipe, so cloned books and duplicated banners stay. Stacks gain dyed colour, firework explosion, pot decorations, bundle contents, stew effects and map post-processing components, and their NBT now matches the codecs (defaults omitted, templates without count 1). A banner whose first layer was a rhombus was mistaken for the raid banner; that is fixed. tools/test_recipe_parity.py drives vanilla's RecipeManager (new VanillaRecipeOracle) and the Rust recipe_fixture over 50k generated crafting, cooking, stonecutting and smithing cases and compares matches, results and remainders as canonical NBT; all match. Co-Authored-By: Claude Sonnet 5.5 --- .../horizon-client/examples/recipe_fixture.rs | 91 ++ crates/horizon-client/src/crafting.rs | 1365 ++++++++++++++--- crates/horizon-client/src/game.rs | 16 +- .../src/game/machines/crafter.rs | 2 +- crates/horizon-client/src/item_data.rs | 346 ++++- crates/horizon-client/src/items.rs | 30 +- crates/horizon-client/src/recipe_book.rs | 2 +- .../dev/horizonlab/parity/ParityData.java | 132 ++ .../parity/VanillaRecipeOracle.java | 140 ++ tools/interaction_lab.py | 71 + tools/test_recipe_parity.py | 303 ++++ 11 files changed, 2233 insertions(+), 265 deletions(-) create mode 100644 crates/horizon-client/examples/recipe_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java create mode 100644 tools/interaction_lab.py create mode 100644 tools/test_recipe_parity.py diff --git a/crates/horizon-client/examples/recipe_fixture.rs b/crates/horizon-client/examples/recipe_fixture.rs new file mode 100644 index 000000000..e68258e4d --- /dev/null +++ b/crates/horizon-client/examples/recipe_fixture.rs @@ -0,0 +1,91 @@ +//! Recipe lookups for tools/test_recipe_parity.py: reads the oracle's +//! tab-separated commands (craft, cook, stonecut, smith) and prints one line +//! per command in the oracle's format. +//! +//! usage: recipe_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + crafting::Recipes, + enchant::Enchantments, + item_data::{canon_stack, parse_stack}, + items::Items, + stations::StationRecipes, +}; +use std::{fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let stations = StationRecipes::load(root, &items); + let enchantments = Enchantments::load(root); + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split('\t').collect(); + let stack = |i: usize| parse_stack(f[i]); + let text = match f[0] { + "craft" => { + let n: usize = f[1].parse()?; + let mut grid = Vec::new(); + for i in 0..n * n { + grid.push(stack(2 + i)?); + } + match recipes.find(&grid, n) { + None => "none".to_owned(), + Some((id, result)) => { + let rest = recipes.remainders(id, &grid, n); + let rest: Vec = rest + .iter() + .enumerate() + .filter_map(|(i, s)| { + Some(format!("{i}={}", canon_stack(Some(s.as_ref()?)))) + }) + .collect(); + format!("{id}\t{}\t{}", canon_stack(Some(&result)), rest.join(";")) + } + } + } + "cook" => match stack(2)?.and_then(|s| { + recipes + .cook(&format!("minecraft:{}", f[1]), &s) + .map(|c| (c.id.clone(), c.result.clone(), c.experience, c.time)) + }) { + None => "none".to_owned(), + Some((id, result, xp, time)) => { + format!("{id}\t{}\t{xp:?}\t{time}", canon_stack(Some(&result))) + } + }, + "stonecut" => match stack(1)? { + None => String::new(), + Some(s) => stations + .stonecutter(&s) + .iter() + .map(|r| { + format!( + "{}={}", + r.id.trim_start_matches("minecraft:"), + canon_stack(Some(&r.result)) + ) + }) + .collect::>() + .join(";"), + }, + "smith" => { + let (t, b, a) = (stack(1)?, stack(2)?, stack(3)?); + match stations.smithing_result(&enchantments, t.as_ref(), b.as_ref(), a.as_ref()) { + None => "none".to_owned(), + Some(r) => canon_stack(Some(&r)), + } + } + other => return Err(format!("unknown command {other}").into()), + }; + out.push_str(&text); + out.push('\n'); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index aa434a556..cf2e43f03 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1,13 +1,28 @@ //! Crafting and cooking recipes from the pinned data pack: shaped patterns -//! (placed anywhere in the grid, optionally mirrored as in -//! `ShapedRecipePattern.matches`), shapeless ingredient sets, and furnace-type -//! cooking lookups. +//! (`ShapedRecipePattern.matches`), shapeless recipes (a bipartite match of +//! ingredients to stacks, as `StackedContents.canCraft`), the special and +//! transmuting crafting recipes (`CustomRecipe` and friends), and +//! furnace-type cooking lookups. use crate::{ Result, + item_data::StackData, items::{ItemStack, Items}, + particles::{FireworkExplosion, FireworkShape}, }; +use horizon_world::nbt::Tag; use serde_json::Value; -use std::{collections::HashSet, fs, path::Path, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + fs, + path::Path, + sync::Arc, +}; + +/// `DyeColor.getFireworkColor` in dye order (white to black). +const FIREWORK_COLORS: [u32; 16] = [ + 15_790_320, 15_435_844, 12_801_229, 6_719_955, 14_602_026, 4_312_372, 14_188_952, 4_408_131, + 11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019, +]; /// A set of accepted items (expanded from an item, list or tag). #[derive(Clone, Debug)] @@ -41,22 +56,124 @@ impl Ingredient { self.0.contains(&*stack.item) } } +/// A recipe result: `ItemStackTemplate` (`id`, `count`, `components`), with the +/// id optional for the transmuting recipes that keep the input's item. +#[derive(Clone, Debug)] +pub struct Template { + pub item: Option>, + pub count: u32, + pub damage: u32, + pub extra: Option>, +} +impl Template { + fn parse(v: &Value) -> Option { + let (damage, extra) = match v.get("components") { + Some(c) => crate::item_data::decode_components(Some(&json_tag(c))), + None => (0, None), + }; + Some(Self { + item: v["id"].as_str().map(Arc::from), + count: v["count"].as_u64().unwrap_or(1) as u32, + damage, + extra, + }) + } + /// `ItemStackTemplate.create`. + pub fn create(&self) -> ItemStack { + ItemStack { + item: self + .item + .clone() + .unwrap_or_else(|| Arc::from("minecraft:air")), + count: self.count, + damage: self.damage, + extra: self.extra.clone(), + } + } + /// `TransmuteRecipe.createWithOriginalComponents`: the input's component + /// patch on the result item, then the template's own components over it. + fn over(&self, input: &ItemStack, extra_count: u32) -> ItemStack { + let mut out = ItemStack { + item: self.item.clone().unwrap_or_else(|| input.item.clone()), + count: self.count + extra_count, + damage: input.damage, + extra: input.extra.clone(), + }; + if self.damage > 0 { + out.damage = self.damage; + } + if let Some(over) = &self.extra { + overlay(out.data_mut(), over); + } + out.tidy(); + out + } +} +/// `DataComponentPatch` application: every component the overlay sets wins. +fn overlay(dst: &mut StackData, src: &StackData) { + let none = StackData::default(); + macro_rules! field { + ($($f:ident),*) => {$( + if src.$f != none.$f { + dst.$f = src.$f.clone(); + } + )*}; + } + field!( + enchantments, + stored_enchantments, + repair_cost, + custom_name, + potion, + trim, + container, + charged, + fireworks, + map_id, + writable_pages, + written, + banner_patterns, + base_color, + ominous_banner, + ominous_amplifier, + dyed_color, + firework_explosion, + pot_decorations, + bundle_contents, + stew_effects, + map_post_processing + ); +} +/// A JSON recipe value as the NBT a component codec reads. +fn json_tag(v: &Value) -> Tag { + match v { + Value::Null => Tag::End, + Value::Bool(b) => Tag::Byte(i8::from(*b)), + Value::Number(n) => match n.as_i64() { + Some(i) => i32::try_from(i).map_or(Tag::Long(i), Tag::Int), + None => Tag::Double(n.as_f64().unwrap_or(0.0).to_bits()), + }, + Value::String(s) => Tag::String(s.as_str().into()), + Value::Array(a) => Tag::List(a.iter().map(json_tag).collect()), + Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), json_tag(v)))), + } +} #[derive(Clone, Debug)] pub enum Recipe { Shaped { width: usize, height: usize, cells: Vec>, - result: ItemStack, + result: Template, }, Shapeless { ingredients: Vec, - result: ItemStack, + result: Template, }, - /// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`. + /// The recipes with code of their own. Special(Special), } -/// The banner-copying custom recipes. +/// The custom and transmuting crafting recipes. #[derive(Clone, Debug)] pub enum Special { /// A patterned banner and a blank one of the same colour copy the patterns. @@ -67,70 +184,481 @@ pub enum Special { target: Ingredient, result: String, }, + /// `TransmuteRecipe`: one input, 1..8 materials; shulker box and bundle + /// dyeing, map cloning. + Transmute { + input: Ingredient, + material: Ingredient, + min: usize, + max: usize, + add_count: bool, + result: Template, + }, + /// `DyeRecipe`: dyed armour. + Dye { + target: Ingredient, + dye: Ingredient, + result: Template, + }, + /// `ImbueRecipe`: tipped arrows. + Imbue { + source: Ingredient, + material: Ingredient, + result: Template, + }, + /// `BookCloningRecipe`. + BookCloning { + source: Ingredient, + material: Ingredient, + min: i32, + max: i32, + result: Template, + }, + /// `FireworkRocketRecipe`. + FireworkRocket { + shell: Ingredient, + fuel: Ingredient, + star: Ingredient, + result: Template, + }, + /// `FireworkStarRecipe`. + FireworkStar { + dye: Ingredient, + fuel: Ingredient, + trail: Ingredient, + twinkle: Ingredient, + shapes: Vec<(FireworkShape, Ingredient)>, + result: Template, + }, + /// `FireworkStarFadeRecipe`. + FireworkStarFade { + dye: Ingredient, + target: Ingredient, + result: Template, + }, + /// `MapExtendingRecipe`: a map ringed by paper, when its scale is under 4. + MapExtending { + map: Ingredient, + material: Ingredient, + result: Template, + }, + /// `DecoratedPotRecipe`: four sherds or bricks. + DecoratedPot { + back: Ingredient, + left: Ingredient, + right: Ingredient, + front: Ingredient, + result: Template, + }, + /// `RepairItemRecipe`: two damaged items of one kind. + RepairItem, +} +/// `CraftingInput`: the occupied bounding box of the grid. +pub struct Input<'a> { + pub width: usize, + pub height: usize, + /// Position of the box in the grid. + pub left: usize, + pub top: usize, + cells: Vec>, +} +impl<'a> Input<'a> { + /// `CraftingInput.ofPositioned`; None for an empty grid. + pub fn of(grid: &'a [Option], size: usize) -> Option { + let occupied: Vec<(usize, usize)> = (0..size * size) + .filter(|&i| grid.get(i).is_some_and(|c| c.is_some())) + .map(|i| (i % size, i / size)) + .collect(); + let (x0, x1) = ( + occupied.iter().map(|p| p.0).min()?, + occupied.iter().map(|p| p.0).max()?, + ); + let (y0, y1) = ( + occupied.iter().map(|p| p.1).min()?, + occupied.iter().map(|p| p.1).max()?, + ); + let (width, height) = (x1 - x0 + 1, y1 - y0 + 1); + let cells = (0..width * height) + .map(|i| grid[(y0 + i / width) * size + x0 + i % width].as_ref()) + .collect(); + Some(Self { + width, + height, + left: x0, + top: y0, + cells, + }) + } + pub fn get(&self, x: usize, y: usize) -> Option<&'a ItemStack> { + self.cells.get(y * self.width + x).copied().flatten() + } + /// The non-empty stacks in slot order. + pub fn stacks(&self) -> Vec<&'a ItemStack> { + self.cells.iter().flatten().copied().collect() + } + pub fn count(&self) -> usize { + self.cells.iter().flatten().count() + } +} +/// What recipes need to know about an item. +#[derive(Clone, Debug, Default)] +struct Facts { + /// Index into the dye colours when the item has the `dye` component. + dye: Option, + max_damage: u32, + max_stack: u32, + remainder: Option>, +} +/// The tables recipes consult. +pub struct Context<'a> { + recipes: &'a Recipes, + /// A filled map's scale, when its data is known. + pub map_scale: &'a dyn Fn(i32) -> Option, +} +impl Context<'_> { + fn facts(&self, stack: &ItemStack) -> Option<&Facts> { + self.recipes.facts.get(&stack.item) + } + /// `itemStack.has(DataComponents.DYE)`. + fn dye(&self, stack: &ItemStack) -> Option { + self.facts(stack).and_then(|f| f.dye) + } + fn max_stack(&self, item: &str) -> u32 { + self.recipes.facts.get(item).map_or(64, |f| f.max_stack) + } } impl Special { - /// `matches` + `assemble` over the non-empty stacks of the grid. - fn assemble(&self, stacks: &[&ItemStack]) -> Option { + /// `Recipe.matches`. + fn matches(&self, ctx: &Context, input: &Input) -> bool { use crate::banner; - if stacks.len() != 2 { - return None; - } + let stacks = input.stacks(); match self { - Self::BannerDuplicate { - banner: ing, - result, - } => { - let color = banner::banner_color(&stacks[0].item)?; - let mut source = None; - let mut target = false; - for s in stacks { - if !ing.test(s) || banner::banner_color(&s.item)? != color { - return None; + Self::BannerDuplicate { banner: ing, .. } => { + if stacks.len() != 2 { + return false; + } + let mut color = None; + let (mut target, mut source) = (false, false); + for s in &stacks { + let Some(this) = banner::banner_color(&s.item).filter(|_| ing.test(s)) else { + return false; + }; + match color { + None => color = Some(this), + Some(c) if c != this => return false, + _ => {} } let layers = banner::layers(s).len(); if layers > banner::MAX_LAYERS { - return None; + return false; } - if layers > 0 { - if source.is_some() { - return None; - } - source = Some(*s); - } else { - if target { - return None; - } - target = true; + let seen = if layers > 0 { &mut source } else { &mut target }; + if *seen { + return false; } + *seen = true; } - let source = source.filter(|_| target)?; - // TransmuteRecipe.createWithOriginalComponents: the source's components. - Some(ItemStack { - item: Arc::from(result.as_str()), - count: 1, - ..(*source).clone() - }) + source && target } Self::ShieldDecoration { banner: ing, target: tgt, - result, + .. } => { - let (mut patterned, mut clear) = (None, None); - for s in stacks { + if stacks.len() != 2 { + return false; + } + let (mut patterned, mut clear) = (false, false); + for s in &stacks { if ing.test(s) && banner::banner_color(&s.item).is_some() { - if patterned.is_some() { - return None; + if patterned { + return false; } - patterned = Some(*s); + patterned = true; } else { - if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() { - return None; + if !tgt.test(s) || clear || !banner::layers(s).is_empty() { + return false; } - clear = Some(*s); + clear = true; } } - let (banner_stack, shield) = (patterned?, clear?); + patterned && clear + } + Self::Transmute { + input: base, + material, + min, + max, + add_count, + result, + } => { + let n = stacks.len(); + if n < min + 1 || n > max + 1 { + return false; + } + let mut found: Option<&ItemStack> = None; + let mut materials = 0; + for s in &stacks { + if base.test(s) { + if found.is_some() { + return false; + } + found = Some(s); + } else { + if !material.test(s) { + return false; + } + materials += 1; + if materials > *max { + return false; + } + } + } + let Some(found) = found else { + return false; + }; + if materials < *min || materials > *max { + return false; + } + let count = if *add_count { + materials as u32 + result.count + } else { + result.count + }; + if count != 1 { + return true; + } + let made = result.over(found, 0); + made.count <= ctx.max_stack(&made.item) && !made.same_item_same_components(found) + } + Self::Dye { target, dye, .. } => { + if stacks.len() < 2 { + return false; + } + let (mut has_target, mut has_dyes) = (false, false); + for s in &stacks { + if target.test(s) { + if has_target { + return false; + } + has_target = true; + } else { + if !dye.test(s) || ctx.dye(s).is_none() { + return false; + } + has_dyes = true; + } + } + has_dyes && has_target + } + Self::Imbue { + source, material, .. + } => { + if input.width != 3 || input.height != 3 || stacks.len() != 9 { + return false; + } + (0..3).all(|y| { + (0..3).all(|x| { + let ing = if x == 1 && y == 1 { source } else { material }; + input.get(x, y).is_some_and(|s| ing.test(s)) + }) + }) + } + Self::BookCloning { + source, + material, + min, + max, + .. + } => { + if stacks.len() < 2 { + return false; + } + let (mut has_material, mut has_source) = (false, false); + for s in &stacks { + if source.test(s) { + let Some(book) = s.data().and_then(|d| d.written.as_ref()) else { + return false; + }; + let generation = i32::from(book.generation); + if generation < *min || generation > *max || has_source { + return false; + } + has_source = true; + } else { + if !material.test(s) { + return false; + } + has_material = true; + } + } + has_source && has_material + } + Self::FireworkRocket { + shell, fuel, star, .. + } => { + if stacks.len() < 2 { + return false; + } + let mut has_shell = false; + let mut fuels = 0; + for s in &stacks { + if shell.test(s) { + if has_shell { + return false; + } + has_shell = true; + } else if fuel.test(s) { + fuels += 1; + if fuels > 3 { + return false; + } + } else if !star.test(s) { + return false; + } + } + has_shell && fuels >= 1 + } + Self::FireworkStar { + dye, + fuel, + trail, + twinkle, + shapes, + .. + } => { + if stacks.len() < 2 { + return false; + } + let (mut has_fuel, mut has_dye, mut has_shape) = (false, false, false); + let (mut has_trail, mut has_twinkle) = (false, false); + for s in &stacks { + if twinkle.test(s) { + if has_twinkle { + return false; + } + has_twinkle = true; + } else if trail.test(s) { + if has_trail { + return false; + } + has_trail = true; + } else if fuel.test(s) { + if has_fuel { + return false; + } + has_fuel = true; + } else if dye.test(s) && ctx.dye(s).is_some() { + has_dye = true; + } else { + if !shapes.iter().any(|(_, ing)| ing.test(s)) || has_shape { + return false; + } + has_shape = true; + } + } + has_fuel && has_dye + } + Self::FireworkStarFade { dye, target, .. } => { + if stacks.len() < 2 { + return false; + } + let (mut has_dye, mut has_target) = (false, false); + for s in &stacks { + if dye.test(s) && ctx.dye(s).is_some() { + has_dye = true; + } else { + if !target.test(s) || has_target { + return false; + } + has_target = true; + } + } + has_target && has_dye + } + Self::MapExtending { map, material, .. } => { + if input.width != 3 || input.height != 3 || stacks.len() != 9 { + return false; + } + let ring = (0..3).all(|y| { + (0..3).all(|x| { + let ing = if x == 1 && y == 1 { map } else { material }; + input.get(x, y).is_some_and(|s| ing.test(s)) + }) + }); + if !ring { + return false; + } + stacks + .iter() + .find_map(|s| s.data().and_then(|d| d.map_id)) + .and_then(|id| (ctx.map_scale)(id)) + .is_some_and(|scale| scale < 4) + } + Self::DecoratedPot { + back, + left, + right, + front, + .. + } => { + input.width == 3 + && input.height == 3 + && stacks.len() == 4 + && input.get(1, 0).is_some_and(|s| back.test(s)) + && input.get(0, 1).is_some_and(|s| left.test(s)) + && input.get(2, 1).is_some_and(|s| right.test(s)) + && input.get(1, 2).is_some_and(|s| front.test(s)) + } + Self::RepairItem => Self::repair_pair(ctx, &stacks).is_some(), + } + } + /// `RepairItemRecipe.getItemsToCombine`. + fn repair_pair<'a>( + ctx: &Context, + stacks: &[&'a ItemStack], + ) -> Option<(&'a ItemStack, &'a ItemStack)> { + let [first, second] = stacks else { + return None; + }; + let durable = |s: &ItemStack| ctx.facts(s).is_some_and(|f| f.max_damage > 0); + (second.item == first.item + && first.count == 1 + && second.count == 1 + && durable(first) + && durable(second)) + .then_some((*first, *second)) + } + /// `Recipe.assemble`; None is the empty stack. + fn assemble(&self, ctx: &Context, input: &Input) -> Option { + use crate::banner; + let stacks = input.stacks(); + let made = match self { + Self::BannerDuplicate { result, .. } => { + let source = stacks + .iter() + .find(|s| (1..=banner::MAX_LAYERS).contains(&banner::layers(s).len()))?; + // TransmuteRecipe.createWithOriginalComponents: the source's components. + ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..(**source).clone() + } + } + Self::ShieldDecoration { + banner: ing, + target, + result, + } => { + let (mut banner_stack, mut shield) = (None, None); + for s in &stacks { + if ing.test(s) && banner::banner_color(&s.item).is_some() { + banner_stack = Some(*s); + } else if target.test(s) { + shield = Some(*s); + } + } + let (banner_stack, shield) = (banner_stack?, shield?); let mut out = ItemStack { item: Arc::from(result.as_str()), count: 1, @@ -139,11 +667,258 @@ impl Special { let data = out.data_mut(); data.banner_patterns = banner::layers(banner_stack).to_vec(); data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from); - Some(out) + out } - } + Self::Transmute { + input: base, + material, + add_count, + result, + .. + } => { + if *add_count { + let mut materials = 0; + let mut found = None; + for s in &stacks { + if base.test(s) { + found = Some(*s); + } else if material.test(s) { + materials += 1; + } + } + result.over(found?, materials) + } else { + let s = stacks.iter().find(|s| base.test(s))?; + result.over(s, 0) + } + } + Self::Dye { + target, + dye, + result, + } => { + let mut dyes = Vec::new(); + let mut target_stack: Option<&ItemStack> = None; + for s in &stacks { + if target.test(s) { + if target_stack.is_some() { + return None; + } + target_stack = Some(s); + } else { + if !dye.test(s) { + return None; + } + // getOrDefault(DYE, WHITE) + dyes.push(ctx.dye(s).unwrap_or(0)); + } + } + let target_stack = target_stack?; + if dyes.is_empty() { + return None; + } + let current = target_stack.data().and_then(|d| d.dyed_color); + let mut out = result.over(target_stack, 0); + out.data_mut().dyed_color = Some(apply_dyes(current, &dyes)); + out + } + Self::Imbue { result, .. } => { + let source = input.get(1, 1)?; + let mut out = result.create(); + out.data_mut().potion = source.data().and_then(|d| d.potion.clone()); + out + } + Self::BookCloning { + source, + material, + result, + .. + } => { + let mut copies = 0u32; + let mut book: Option<&ItemStack> = None; + for s in &stacks { + if source.test(s) && s.data().is_some_and(|d| d.written.is_some()) { + if book.is_some() { + return None; + } + book = Some(s); + } else { + if !material.test(s) { + return None; + } + copies += 1; + } + } + let book = book?; + // count - 1 can be -1 when no material was seen; matches() ensures one. + let mut out = result.over(book, copies.saturating_sub(1)); + if let Some(w) = out.data_mut().written.as_mut() { + w.generation += 1; + } + out + } + Self::FireworkRocket { + fuel, star, result, .. + } => { + let mut explosions = Vec::new(); + let mut fuels = 0u8; + for s in &stacks { + if fuel.test(s) { + fuels += 1; + } else if star.test(s) + && let Some(e) = s.data().and_then(|d| d.firework_explosion.clone()) + { + explosions.push(e); + } + } + let mut out = result.create(); + // A rocket's prototype is one flight and no explosions. + if fuels != 1 || !explosions.is_empty() { + out.data_mut().fireworks = Some((fuels, explosions)); + } + out + } + Self::FireworkStar { + dye, + trail, + twinkle, + shapes, + result, + .. + } => { + let mut shape = FireworkShape::SmallBall; + let (mut has_twinkle, mut has_trail) = (false, false); + let mut colors = Vec::new(); + for s in &stacks { + if let Some((found, _)) = shapes.iter().find(|(_, ing)| ing.test(s)) { + shape = *found; + } else if twinkle.test(s) { + has_twinkle = true; + } else if trail.test(s) { + has_trail = true; + } else if dye.test(s) { + colors.push(FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)]); + } + } + let mut out = result.create(); + out.data_mut().firework_explosion = Some(FireworkExplosion { + shape, + colors, + fade: Vec::new(), + trail: has_trail, + twinkle: has_twinkle, + }); + out + } + Self::FireworkStarFade { + dye, + target, + result, + } => { + let mut colors = Vec::new(); + let mut target_stack = None; + for s in &stacks { + if dye.test(s) { + colors.push(FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)]); + } else if target.test(s) { + target_stack = Some(*s); + } + } + let target_stack = target_stack?; + if colors.is_empty() { + return None; + } + let mut out = result.over(target_stack, 0); + let explosion = out + .data_mut() + .firework_explosion + .get_or_insert_with(FireworkExplosion::default); + explosion.fade = colors; + out + } + Self::MapExtending { result, .. } => { + let map = stacks + .iter() + .find(|s| s.data().is_some_and(|d| d.map_id.is_some()))?; + let mut out = result.over(map, 0); + out.data_mut().map_post_processing = Some(1); + out + } + Self::DecoratedPot { result, .. } => { + let side = |x, y| { + input.get(x, y).map(|s| ItemStack { + count: 1, + ..s.clone() + }) + }; + let mut out = result.create(); + let sides = [side(1, 0), side(0, 1), side(2, 1), side(1, 2)]; + if !crate::item_data::all_bricks(&sides) { + out.data_mut().pot_decorations = Some(Box::new(sides)); + } + out + } + Self::RepairItem => { + let (first, second) = Self::repair_pair(ctx, &stacks)?; + let max = |s: &ItemStack| ctx.facts(s).map_or(0, |f| f.max_damage) as i64; + let durability = max(first).max(max(second)); + let remaining = (max(first) - i64::from(first.damage)) + + (max(second) - i64::from(second.damage)) + + durability * 5 / 100; + let mut out = ItemStack::new(&first.item, 1); + out.damage = (durability - remaining).max(0) as u32; + // Only the curses of both survive, at the higher level. + let (a, b) = ( + first.crafting_enchantments(), + second.crafting_enchantments(), + ); + let mut curses: Vec<(Arc, u32)> = Vec::new(); + for (id, level) in a.iter().chain(b.iter()) { + if !ctx.recipes.curses.contains(&**id) { + continue; + } + match curses.iter_mut().find(|(c, _)| c == id) { + Some((_, l)) => *l = (*l).max(*level), + None => curses.push((id.clone(), *level)), + } + } + out.set_crafting_enchantments(curses); + out + } + }; + let mut made = made; + made.tidy(); + // ItemStackTemplate.validate: oversized stacks become empty. + (made.count > 0 && made.count <= ctx.max_stack(&made.item)).then_some(made) } } +/// `DyedItemColor.applyDyes` over dye indexes. +fn apply_dyes(current: Option, dyes: &[usize]) -> i32 { + let (mut r, mut g, mut b, mut intensity, mut n) = (0i32, 0i32, 0i32, 0i32, 0i32); + let mut add = |rgb: u32| { + let (red, green, blue) = ( + (rgb >> 16 & 255) as i32, + (rgb >> 8 & 255) as i32, + (rgb & 255) as i32, + ); + intensity += red.max(green.max(blue)); + r += red; + g += green; + b += blue; + n += 1; + }; + if let Some(c) = current { + add(c as u32); + } + for d in dyes { + add(crate::block_entity_render::DYES[*d].1); + } + let (red, green, blue) = (r / n, g / n, b / n); + let average = intensity as f32 / n as f32; + let result = red.max(green.max(blue)) as f32; + let scale = |c: i32| (c as f32 * average / result) as i32; + scale(red) << 16 | scale(green) << 8 | scale(blue) +} #[derive(Clone, Debug)] pub struct Cooking { /// The recipe's file name (its id without namespace). @@ -161,21 +936,84 @@ pub struct Recipes { pub crafting: Vec<(String, Recipe)>, pub cooking: Vec, /// `category` and `group` of each crafting recipe, by file name. - pub meta: std::collections::HashMap, + pub meta: HashMap, + facts: HashMap, Facts>, + /// The `#minecraft:curse` enchantments. + curses: HashSet, } -fn result(v: &Value) -> Option { - Some(ItemStack { - item: Arc::from(v["id"].as_str()?), - count: v["count"].as_u64().unwrap_or(1) as u32, - damage: 0, - extra: None, +/// `MinMaxBounds.Ints` as (min, max) with the given defaults. +fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) { + match v { + Some(Value::Number(n)) => { + let n = n.as_i64().unwrap_or(default.0); + (n, n) + } + Some(o @ Value::Object(_)) => ( + o["min"].as_i64().unwrap_or(open.0), + o["max"].as_i64().unwrap_or(open.1), + ), + _ => default, + } +} +/// `Util.isSymmetrical` is not needed: both orientations are tried. +/// `ShapedRecipePattern.shrink`: the pattern without empty border rows and columns. +fn shrink(pattern: &[Vec]) -> Vec> { + let rows: Vec<&Vec> = pattern + .iter() + .skip_while(|r| r.iter().all(|c| *c == ' ')) + .collect(); + let mut rows: Vec> = rows.into_iter().cloned().collect(); + while rows.last().is_some_and(|r| r.iter().all(|c| *c == ' ')) { + rows.pop(); + } + let left = rows + .iter() + .filter_map(|r| r.iter().position(|c| *c != ' ')) + .min(); + let right = rows + .iter() + .filter_map(|r| r.iter().rposition(|c| *c != ' ')) + .max(); + match (left, right) { + (Some(l), Some(r)) => rows.iter().map(|row| row[l..=r].to_vec()).collect(), + _ => Vec::new(), + } +} +/// A perfect matching of the ingredients to distinct stacks (`StackedContents.canCraft`). +fn matches_all(ingredients: &[Ingredient], stacks: &[&ItemStack]) -> bool { + fn augment( + i: usize, + ingredients: &[Ingredient], + stacks: &[&ItemStack], + owner: &mut [Option], + seen: &mut [bool], + ) -> bool { + for s in 0..stacks.len() { + if seen[s] || !ingredients[i].test(stacks[s]) { + continue; + } + seen[s] = true; + if owner[s].is_none_or(|o| augment(o, ingredients, stacks, owner, seen)) { + owner[s] = Some(i); + return true; + } + } + false + } + if ingredients.len() != stacks.len() { + return false; + } + let mut owner = vec![None; stacks.len()]; + (0..ingredients.len()).all(|i| { + let mut seen = vec![false; stacks.len()]; + augment(i, ingredients, stacks, &mut owner, &mut seen) }) } impl Recipes { pub fn load(root: &Path, items: &Items) -> Result { let mut crafting = Vec::new(); let mut cooking = Vec::new(); - let mut meta = std::collections::HashMap::new(); + let mut meta = HashMap::new(); let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? .flatten() .map(|e| e.path()) @@ -191,7 +1029,10 @@ impl Recipes { let v: Value = serde_json::from_slice(&fs::read(&path)?)?; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); - match v["type"].as_str().unwrap_or("") { + let ing = |k: &str| Ingredient::parse(&v[k], items); + let result = || Template::parse(&v["result"]); + let special = |recipe: Option| recipe.map(Recipe::Special); + let parsed: Option = match v["type"].as_str().unwrap_or("") { "minecraft:crafting_shaped" => { let pattern: Vec> = v["pattern"] .as_array() @@ -199,14 +1040,14 @@ impl Recipes { .flatten() .filter_map(|r| r.as_str().map(|s| s.chars().collect())) .collect(); + let pattern = shrink(&pattern); let height = pattern.len(); - let width = pattern.iter().map(Vec::len).max().unwrap_or(0); + let width = pattern.first().map_or(0, Vec::len); let mut cells = Vec::with_capacity(width * height); - let mut ok = true; + let mut ok = height > 0; for row in &pattern { - for x in 0..width { - let c = row.get(x).copied().unwrap_or(' '); - if c == ' ' { + for c in row { + if *c == ' ' { cells.push(None); } else { match Ingredient::parse(&v["key"][c.to_string()], items) { @@ -216,16 +1057,14 @@ impl Recipes { } } } - if let (true, Some(result)) = (ok, result(&v["result"])) { - crafting.push(( - name, - Recipe::Shaped { - width, - height, - cells, - result, - }, - )); + match (ok, result()) { + (true, Some(result)) => Some(Recipe::Shaped { + width, + height, + cells, + result, + }), + _ => None, } } "minecraft:crafting_shapeless" => { @@ -235,73 +1074,168 @@ impl Recipes { .flatten() .map(|i| Ingredient::parse(i, items)) .collect(); - if let (Some(ingredients), Some(result)) = (ingredients, result(&v["result"])) { - crafting.push(( - name, - Recipe::Shapeless { - ingredients, - result, - }, - )); + match (ingredients, result()) { + (Some(ingredients), Some(result)) => Some(Recipe::Shapeless { + ingredients, + result, + }), + _ => None, } } - "minecraft:crafting_special_bannerduplicate" => { - if let (Some(banner), Some(id)) = ( - Ingredient::parse(&v["banner"], items), - v["result"]["id"].as_str(), - ) { - crafting.push(( - name, - Recipe::Special(Special::BannerDuplicate { - banner, - result: id.to_owned(), - }), + "minecraft:crafting_special_bannerduplicate" => special( + ing("banner") + .zip(v["result"]["id"].as_str()) + .map(|(banner, id)| Special::BannerDuplicate { + banner, + result: id.to_owned(), + }), + ), + "minecraft:crafting_special_shielddecoration" => special( + ing("banner") + .zip(ing("target")) + .zip(v["result"]["id"].as_str()) + .map(|((banner, target), id)| Special::ShieldDecoration { + banner, + target, + result: id.to_owned(), + }), + ), + "minecraft:crafting_transmute" => special((|| { + let (min, max) = bounds(v.get("material_count"), (1, 1), (1, 8)); + Some(Special::Transmute { + input: ing("input")?, + material: ing("material")?, + min: min.clamp(1, 8) as usize, + max: max.clamp(1, 8) as usize, + add_count: v["add_material_count_to_result"].as_bool().unwrap_or(false), + result: result()?, + }) + })()), + "minecraft:crafting_dye" => special((|| { + Some(Special::Dye { + target: ing("target")?, + dye: ing("dye")?, + result: result()?, + }) + })()), + "minecraft:crafting_imbue" => special((|| { + Some(Special::Imbue { + source: ing("source")?, + material: ing("material")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_bookcloning" => special((|| { + let (min, max) = bounds(v.get("allowed_generations"), (0, 1), (0, 2)); + Some(Special::BookCloning { + source: ing("source")?, + material: ing("material")?, + min: min as i32, + max: max as i32, + result: result()?, + }) + })()), + "minecraft:crafting_special_firework_rocket" => special((|| { + Some(Special::FireworkRocket { + shell: ing("shell")?, + fuel: ing("fuel")?, + star: ing("star")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_firework_star" => special((|| { + let mut shapes = Vec::new(); + for (shape, value) in v["shapes"].as_object()? { + shapes.push(( + FireworkShape::from_name(shape), + Ingredient::parse(value, items)?, )); } - } - "minecraft:crafting_special_shielddecoration" => { - if let (Some(banner), Some(target), Some(id)) = ( - Ingredient::parse(&v["banner"], items), - Ingredient::parse(&v["target"], items), - v["result"]["id"].as_str(), - ) { - crafting.push(( - name, - Recipe::Special(Special::ShieldDecoration { - banner, - target, - result: id.to_owned(), - }), - )); - } - } + Some(Special::FireworkStar { + dye: ing("dye")?, + fuel: ing("fuel")?, + trail: ing("trail")?, + twinkle: ing("twinkle")?, + shapes, + result: result()?, + }) + })()), + "minecraft:crafting_special_firework_star_fade" => special((|| { + Some(Special::FireworkStarFade { + dye: ing("dye")?, + target: ing("target")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_mapextending" => special((|| { + Some(Special::MapExtending { + map: ing("map")?, + material: ing("material")?, + result: result()?, + }) + })()), + "minecraft:crafting_decorated_pot" => special((|| { + Some(Special::DecoratedPot { + back: ing("back")?, + left: ing("left")?, + right: ing("right")?, + front: ing("front")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_repairitem" => special(Some(Special::RepairItem)), kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" | "minecraft:campfire_cooking") => { - if let (Some(ingredient), Some(result)) = ( - Ingredient::parse(&v["ingredient"], items), - result(&v["result"]), - ) { + if let (Some(ingredient), Some(result)) = (ing("ingredient"), result()) { cooking.push(Cooking { - id: name, + id: name.clone(), category: text("category"), group: text("group"), kind: kind.to_owned(), ingredient, - result, + result: result.create(), experience: v["experience"].as_f64().unwrap_or(0.0) as f32, time: v["cookingtime"].as_u64().unwrap_or(200) as u32, }); } + None } - _ => {} + _ => None, + }; + if let Some(recipe) = parsed { + crafting.push((name, recipe)); } } + let facts = items + .items + .iter() + .map(|(id, info)| { + ( + id.clone(), + Facts { + dye: info.dye.as_deref().and_then(|d| { + crate::block_entity_render::DYES + .iter() + .position(|(name, _)| *name == d) + }), + max_damage: info.max_damage, + max_stack: info.max_stack, + remainder: info.crafting_remainder.as_deref().map(Arc::from), + }, + ) + }) + .collect(); + let curses = crate::items::load_tags(root, "enchantment")? + .remove("minecraft:curse") + .unwrap_or_default(); Ok(Self { crafting, cooking, meta, + facts, + curses, }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. @@ -310,31 +1244,28 @@ impl Recipes { } /// `craft` with the matched recipe's id (the file name without namespace). pub fn find(&self, grid: &[Option], size: usize) -> Option<(&str, ItemStack)> { - // Trim to the occupied bounding box. - let occupied: Vec<(usize, usize)> = (0..size * size) - .filter(|&i| grid[i].is_some()) - .map(|i| (i % size, i / size)) - .collect(); - if occupied.is_empty() { - return None; - } - let (x0, x1) = ( - occupied.iter().map(|p| p.0).min()?, - occupied.iter().map(|p| p.0).max()?, - ); - let (y0, y1) = ( - occupied.iter().map(|p| p.1).min()?, - occupied.iter().map(|p| p.1).max()?, - ); - let (w, h) = (x1 - x0 + 1, y1 - y0 + 1); - let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); + self.find_with(grid, size, &|_| None) + } + /// `RecipeManager.getRecipeFor(CRAFTING, ...)` with a lookup for the scale + /// of a filled map (map extending reads the map's saved data). + pub fn find_with( + &self, + grid: &[Option], + size: usize, + map_scale: &dyn Fn(i32) -> Option, + ) -> Option<(&str, ItemStack)> { + let input = Input::of(grid, size)?; + let ctx = Context { + recipes: self, + map_scale, + }; for (name, recipe) in &self.crafting { - match recipe { + let result = match recipe { Recipe::Special(special) => { - let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); - if let Some(result) = special.assemble(&stacks) { - return Some((name, result)); + if !special.matches(&ctx, &input) { + continue; } + special.assemble(&ctx, &input) } Recipe::Shaped { width, @@ -342,14 +1273,17 @@ impl Recipes { cells, result, } => { - if *width != w || *height != h { + if *width != input.width + || *height != input.height + || cells.iter().flatten().count() != input.count() + { continue; } let matches = |mirror: bool| { - (0..h).all(|y| { - (0..w).all(|x| { - let rx = if mirror { w - 1 - x } else { x }; - match (&cells[y * w + rx], cell(x, y)) { + (0..*height).all(|y| { + (0..*width).all(|x| { + let rx = if mirror { width - 1 - x } else { x }; + match (&cells[y * width + rx], input.get(x, y)) { (None, None) => true, (Some(i), Some(s)) => i.test(s), _ => false, @@ -357,60 +1291,76 @@ impl Recipes { }) }) }; - if matches(false) || matches(true) { - return Some((name, result.clone())); + if !(matches(false) || matches(true)) { + continue; } + Some(result.create()) } Recipe::Shapeless { ingredients, result, } => { - let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); - if stacks.len() != ingredients.len() { + if !matches_all(ingredients, &input.stacks()) { continue; } - // Greedy bipartite matching is sufficient for vanilla's ingredient sets. - let mut used = vec![false; stacks.len()]; - let ok = ingredients.iter().all(|ingredient| { - if let Some(i) = - (0..stacks.len()).find(|&i| !used[i] && ingredient.test(stacks[i])) - { - used[i] = true; - true - } else { - false - } - }); - if ok { - return Some((name, result.clone())); - } + Some(result.create()) } - } + }; + return result.map(|r| (name.as_str(), r)); } None } - /// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder - /// (buckets, bottles), and the patterned banner a duplicate keeps. + /// `Recipe.getRemainingItems` placed on the `size`x`size` grid: an item's + /// crafting remainder (buckets, bottles), the patterned banner a duplicate + /// keeps and the written book a clone keeps. pub fn remainders( &self, - items: &Items, + recipe: &str, grid: &[Option], - result: &ItemStack, + size: usize, ) -> Vec> { - grid.iter() - .map(|cell| { - let s = cell.as_ref()?; - if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) { - return Some(ItemStack::new(rem, 1)); + let mut out = vec![None; size * size]; + let Some(input) = Input::of(grid, size) else { + return out; + }; + let kind = self + .crafting + .iter() + .find(|(n, _)| n == recipe) + .map(|(_, r)| r); + for (i, cell) in input.cells.iter().enumerate() { + let Some(s) = cell else { continue }; + let at = (input.top + i / input.width) * size + input.left + i % input.width; + let rest = self + .facts + .get(&s.item) + .and_then(|f| f.remainder.as_deref()) + .map(|r| ItemStack::new(r, 1)); + if rest.is_some() { + out[at] = rest; + continue; + } + let copy = ItemStack { + count: 1, + ..(*s).clone() + }; + match kind { + Some(Recipe::Special(Special::BannerDuplicate { .. })) + if !crate::banner::layers(s).is_empty() => + { + out[at] = Some(copy); } - (result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then( - || ItemStack { - count: 1, - ..s.clone() - }, - ) - }) - .collect() + // BookCloningRecipe stops at the first copied book. + Some(Recipe::Special(Special::BookCloning { .. })) + if s.data().is_some_and(|d| d.written.is_some()) => + { + out[at] = Some(copy); + break; + } + _ => {} + } + } + out } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking @@ -432,6 +1382,26 @@ mod tests { s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; s } + fn run(special: &Special, cells: &[ItemStack]) -> Option { + let recipes = Recipes { + crafting: Vec::new(), + cooking: Vec::new(), + meta: HashMap::new(), + facts: HashMap::new(), + curses: HashSet::new(), + }; + let ctx = Context { + recipes: &recipes, + map_scale: &|_| None, + }; + let mut grid: Vec> = cells.iter().cloned().map(Some).collect(); + grid.resize(9, None); + let input = Input::of(&grid, 3)?; + special + .matches(&ctx, &input) + .then(|| special.assemble(&ctx, &input)) + .flatten() + } #[test] fn banner_duplicate_copies_the_patterns_of_the_same_colour() { let recipe = Special::BannerDuplicate { @@ -440,14 +1410,14 @@ mod tests { }; let source = patterned("minecraft:white_banner"); let blank = ItemStack::new("minecraft:white_banner", 1); - let out = recipe.assemble(&[&source, &blank]).expect("copy"); + let out = run(&recipe, &[source.clone(), blank.clone()]).expect("copy"); assert_eq!(out.data().unwrap().banner_patterns.len(), 1); // Two blanks, or two patterned banners, do not match. - assert!(recipe.assemble(&[&blank, &blank]).is_none()); - assert!(recipe.assemble(&[&source, &source]).is_none()); + assert!(run(&recipe, &[blank.clone(), blank.clone()]).is_none()); + assert!(run(&recipe, &[source.clone(), source.clone()]).is_none()); // Another colour is not in the recipe's ingredient. let other = ItemStack::new("minecraft:red_banner", 1); - assert!(recipe.assemble(&[&source, &other]).is_none()); + assert!(run(&recipe, &[source, other]).is_none()); } #[test] fn shield_decoration_needs_a_bare_shield() { @@ -458,11 +1428,26 @@ mod tests { }; let banner = patterned("minecraft:red_banner"); let shield = ItemStack::new("minecraft:shield", 1); - let out = recipe.assemble(&[&banner, &shield]).expect("decorated"); + let out = run(&recipe, &[banner.clone(), shield]).expect("decorated"); let data = out.data().unwrap(); assert_eq!(data.base_color.as_deref(), Some("red")); assert_eq!(data.banner_patterns.len(), 1); // A shield that already has patterns cannot be decorated again. - assert!(recipe.assemble(&[&banner, &out]).is_none()); + assert!(run(&recipe, &[banner, out]).is_none()); + } + #[test] + fn shapeless_matching_assigns_each_stack_one_ingredient() { + let any = ingredient(&["a", "b"]); + let only_a = ingredient(&["a"]); + let (a, b) = (ItemStack::new("a", 1), ItemStack::new("b", 1)); + // Greedy matching would give `a` to the first ingredient and fail. + assert!(matches_all(&[any.clone(), only_a.clone()], &[&a, &b])); + assert!(!matches_all(&[only_a.clone(), only_a], &[&a, &b])); + assert!(!matches_all(&[any], &[&a, &b])); + } + #[test] + fn dyes_blend_like_dyed_item_color() { + // One red dye on an undyed item gives the dye's own colour. + assert_eq!(apply_dyes(None, &[14]), 0xB02E26); } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b66937e3b..e8d7eb2e4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3185,9 +3185,17 @@ impl Game<'_> { } } fn craft_result(&self) -> Option { + self.craft_recipe().map(|(_, result)| result) + } + /// The recipe id and result of the crafting grid. + fn craft_recipe(&self) -> Option<(String, ItemStack)> { let n = self.craft_size; let grid: Vec> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); - self.res.recipes.craft(&grid, n) + let scale = |id: i32| self.maps.data.get(&id).map(|m| m.scale); + self.res + .recipes + .find_with(&grid, n, &scale) + .map(|(name, result)| (name.to_owned(), result)) } fn draw_inventory(&mut self, batch: &mut HudBatch) { if self.draw_station(batch) { @@ -3484,13 +3492,13 @@ impl Game<'_> { if slot == 200 { // ResultSlot: take the crafted stack and consume one of each ingredient. let mut crafted = 0; - while let Some(result) = self.craft_result() { + while let Some((recipe, result)) = self.craft_recipe() { let made = (result.item.clone(), result.count); let cells = self.craft_size * self.craft_size; let remainders = self.res.recipes.remainders( - &self.res.items, + &recipe, &self.craft_grid[..cells], - &result, + self.craft_size, ); if shift { if self.give(result).is_some() { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 0d1432526..470424c44 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -125,7 +125,7 @@ impl Game<'_> { true, horizon_world::level::flags::UPDATE_CLIENTS, ); - let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result); + let remainders = self.res.recipes.remainders(&recipe, &grid, 3); self.crafter_eject(key, facing, result, &recipe); for rest in remainders.into_iter().flatten() { self.crafter_eject(key, facing, rest, &recipe); diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 21273d804..e4329a140 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -44,6 +44,18 @@ pub struct StackData { pub ominous_banner: bool, /// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0). pub ominous_amplifier: Option, + /// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB). + pub dyed_color: Option, + /// `minecraft:firework_explosion` (a firework star). + pub firework_explosion: Option, + /// `minecraft:pot_decorations`: back, left, right, front sherds. + pub pot_decorations: Option; 4]>>, + /// `minecraft:bundle_contents`. + pub bundle_contents: Vec, + /// `minecraft:suspicious_stew_effects`: (effect id, duration). + pub stew_effects: Vec<(Arc, i32)>, + /// `minecraft:map_post_processing`: 0 lock, 1 scale. + pub map_post_processing: Option, } /// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers. pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ @@ -243,6 +255,151 @@ fn read_text(t: &Tag) -> Option { } } +/// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted). +fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag { + let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect()); + let mut fields = vec![("shape", Tag::String(e.shape.name().into()))]; + if !e.colors.is_empty() { + fields.push(("colors", colors(&e.colors))); + } + if !e.fade.is_empty() { + fields.push(("fade_colors", colors(&e.fade))); + } + if e.trail { + fields.push(("has_trail", Tag::Byte(1))); + } + if e.twinkle { + fields.push(("has_twinkle", Tag::Byte(1))); + } + Tag::compound(fields) +} +fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion { + let ints = |t: Option<&Tag>| match t { + Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(), + Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(), + _ => Vec::new(), + }; + crate::particles::FireworkExplosion { + shape: crate::particles::FireworkShape::from_name( + e.get("shape") + .and_then(string) + .as_deref() + .map_or("small_ball", |s| s.strip_prefix("minecraft:").unwrap_or(s)), + ), + colors: ints(e.get("colors")), + fade: ints(e.get("fade_colors")), + trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0, + twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0, + } +} +/// An `ItemStackTemplate`: `{id, count?, components?}`. +fn template_tag(stack: &ItemStack) -> Tag { + let mut entries = vec![("id", Tag::String((&*stack.item).into()))]; + if stack.count != 1 { + entries.push(("count", Tag::Int(stack.count as i32))); + } + if let Some(components) = encode_components(stack) { + entries.push(("components", components)); + } + Tag::compound(entries) +} +/// The pot prototype's decorations: a brick on every side. +pub fn all_bricks(sides: &[Option; 4]) -> bool { + sides.iter().all(|s| { + s.as_ref() + .is_some_and(|s| &*s.item == "minecraft:brick" && s.count == 1 && s.extra.is_none()) + }) +} +fn template_from(tag: &Tag) -> Option { + match tag { + Tag::String(id) => Some(ItemStack::new(&id.to_string_lossy(), 1)), + _ => { + let id = tag.get("id").and_then(string)?; + let (damage, extra) = decode_components(tag.get("components")); + Some(ItemStack { + item: Arc::from(id.as_str()), + count: tag.get("count").and_then(int).unwrap_or(1).max(1) as u32, + damage, + extra, + }) + } + } +} +/// Sorted-key, type-annotated text of a tag (the differential harnesses +/// print the same form from the vanilla side). +pub fn canon_tag(tag: &Tag) -> String { + fn list(out: &mut String, prefix: &str, items: impl Iterator) { + out.push_str(prefix); + out.push_str(&items.collect::>().join(",")); + out.push(']'); + } + fn go(tag: &Tag, out: &mut String) { + use std::fmt::Write as _; + match tag { + Tag::End => {} + Tag::Byte(v) => write!(out, "{v}b").unwrap(), + Tag::Short(v) => write!(out, "{v}s").unwrap(), + Tag::Int(v) => write!(out, "{v}").unwrap(), + Tag::Long(v) => write!(out, "{v}L").unwrap(), + Tag::Float(v) => write!(out, "{}f", f32::from_bits(*v)).unwrap(), + Tag::Double(v) => write!(out, "{}d", f64::from_bits(*v)).unwrap(), + Tag::String(s) => write!( + out, + "\"{}\"", + s.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ) + .unwrap(), + Tag::ByteArray(v) => list(out, "[B;", v.iter().map(|b| (*b as i8).to_string())), + Tag::IntArray(v) => list(out, "[I;", v.iter().map(i32::to_string)), + Tag::LongArray(v) => list(out, "[L;", v.iter().map(i64::to_string)), + Tag::List(items) => { + out.push('['); + for (i, t) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + go(t, out); + } + out.push(']'); + } + Tag::Compound(map) => { + let mut keys: Vec<(String, &Tag)> = + map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect(); + keys.sort_by(|a, b| a.0.cmp(&b.0)); + out.push('{'); + for (i, (k, v)) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&k); + out.push(':'); + go(v, out); + } + out.push('}'); + } + } + } + let mut out = String::new(); + go(tag, &mut out); + out +} +/// `canon_tag` of a stack as `ItemStack.CODEC` writes it; "-" for none. +pub fn canon_stack(stack: Option<&ItemStack>) -> String { + stack.map_or_else( + || "-".to_owned(), + |s| canon_tag(&crate::save::item_to_nbt(s)), + ) +} +/// The stack of an SNBT `ItemStack.CODEC` compound; None for "-". +pub fn parse_stack(snbt: &str) -> Result, String> { + if snbt == "-" { + return Ok(None); + } + let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?; + Ok(crate::save::item_from_nbt(&tag)) +} /// The `components` compound for a stack, or None when every component is default. pub fn encode_components(stack: &ItemStack) -> Option { components_tag(stack.damage, stack.data()) @@ -317,40 +474,73 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { .collect(); entries.push(( "minecraft:written_book_content", - Tag::compound([ - ("title", raw(Tag::String(w.title.as_str().into()))), - ("author", Tag::String(w.author.as_str().into())), - ("generation", Tag::Int(i32::from(w.generation))), - ("pages", Tag::List(pages)), - ("resolved", Tag::Byte(1)), - ]), + Tag::compound({ + let mut fields = vec![ + ("title", raw(Tag::String(w.title.as_str().into()))), + ("author", Tag::String(w.author.as_str().into())), + ("pages", Tag::List(pages)), + ]; + if w.generation != 0 { + fields.push(("generation", Tag::Int(i32::from(w.generation)))); + } + fields + }), )); } if let Some((flight, explosions)) = &d.fireworks { - let list = explosions - .iter() - .map(|e| { - Tag::compound([ - ("shape", Tag::String(e.shape.name().into())), - ( - "colors", - Tag::IntArray(e.colors.iter().map(|c| *c as i32).collect()), - ), - ( - "fade_colors", - Tag::IntArray(e.fade.iter().map(|c| *c as i32).collect()), - ), - ("has_trail", Tag::Byte(i8::from(e.trail))), - ("has_twinkle", Tag::Byte(i8::from(e.twinkle))), - ]) - }) - .collect(); + let mut fields = Vec::new(); + if *flight != 0 { + fields.push(("flight_duration", Tag::Byte(*flight as i8))); + } + if !explosions.is_empty() { + fields.push(( + "explosions", + Tag::List(explosions.iter().map(explosion_tag).collect()), + )); + } + entries.push(("minecraft:fireworks", Tag::compound(fields))); + } + if let Some(e) = &d.firework_explosion { + entries.push(("minecraft:firework_explosion", explosion_tag(e))); + } + if let Some(color) = d.dyed_color { + entries.push(("minecraft:dyed_color", Tag::Int(color))); + } + if let Some(sides) = &d.pot_decorations { + let mut sherds = Vec::new(); + for (name, side) in ["back", "left", "right", "front"].iter().zip(sides.iter()) { + if let Some(stack) = side { + sherds.push((*name, template_tag(stack))); + } + } + entries.push(("minecraft:pot_decorations", Tag::compound(sherds))); + } + if !d.bundle_contents.is_empty() { entries.push(( - "minecraft:fireworks", - Tag::compound([ - ("flight_duration", Tag::Byte(*flight as i8)), - ("explosions", Tag::List(list)), - ]), + "minecraft:bundle_contents", + Tag::List(d.bundle_contents.iter().map(template_tag).collect()), + )); + } + if !d.stew_effects.is_empty() { + entries.push(( + "minecraft:suspicious_stew_effects", + Tag::List( + d.stew_effects + .iter() + .map(|(id, duration)| { + Tag::compound([ + ("id", Tag::String((&**id).into())), + ("duration", Tag::Int(*duration)), + ]) + }) + .collect(), + ), + )); + } + if let Some(mode) = d.map_post_processing { + entries.push(( + "minecraft:map_post_processing", + Tag::String(if mode == 0 { "lock" } else { "scale" }.into()), )); } if !d.charged.is_empty() { @@ -399,7 +589,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { .map(|(slot, stack)| { Tag::compound([ ("slot", Tag::Int(i32::from(*slot))), - ("item", crate::save::item_to_nbt(stack)), + ("item", template_tag(stack)), ]) }) .collect(); @@ -456,36 +646,54 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Vec::new(), }, }), - fireworks: c.get("minecraft:fireworks").map(|f| { - let flight = f - .get("flight_duration") - .and_then(int) - .unwrap_or(0) - .clamp(0, 255) as u8; - let ints = |t: Option<&Tag>| match t { - Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(), - _ => Vec::new(), - }; - let explosions = match f.get("explosions") { - Some(Tag::List(list)) => list - .iter() - .map(|e| crate::particles::FireworkExplosion { - shape: crate::particles::FireworkShape::from_name( - e.get("shape") - .and_then(string) - .as_deref() - .unwrap_or("small_ball"), - ), - colors: ints(e.get("colors")), - fade: ints(e.get("fade_colors")), - trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0, - twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0, - }) - .collect(), - _ => Vec::new(), - }; - (flight, explosions) - }), + fireworks: c + .get("minecraft:fireworks") + .map(|f| { + let flight = f + .get("flight_duration") + .and_then(int) + .unwrap_or(0) + .clamp(0, 255) as u8; + let explosions = match f.get("explosions") { + Some(Tag::List(list)) => list.iter().map(explosion_from).collect(), + _ => Vec::new(), + }; + (flight, explosions) + }) + .filter(|(flight, explosions)| !(*flight == 1 && explosions.is_empty())), + firework_explosion: c.get("minecraft:firework_explosion").map(explosion_from), + dyed_color: c + .get("minecraft:dyed_color") + .and_then(int) + .map(|v| v as i32), + pot_decorations: c + .get("minecraft:pot_decorations") + .map(|p| { + let side = |name: &str| p.get(name).and_then(template_from); + Box::new([side("back"), side("left"), side("right"), side("front")]) + }) + .filter(|sides| !all_bricks(sides)), + bundle_contents: match c.get("minecraft:bundle_contents") { + Some(Tag::List(list)) => list.iter().filter_map(template_from).collect(), + _ => Vec::new(), + }, + stew_effects: match c.get("minecraft:suspicious_stew_effects") { + Some(Tag::List(list)) => list + .iter() + .filter_map(|e| { + Some(( + Arc::from(e.get("id").and_then(string)?.as_str()), + e.get("duration").and_then(int).unwrap_or(160) as i32, + )) + }) + .collect(), + _ => Vec::new(), + }, + map_post_processing: match c.get("minecraft:map_post_processing") { + Some(Tag::String(s)) => Some(u8::from(s.to_string_lossy() != "lock")), + Some(t) => int(t).map(|v| v.clamp(0, 1) as u8), + None => None, + }, charged: match c.get("minecraft:charged_projectiles") { Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(), _ => Vec::new(), @@ -496,17 +704,21 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Vec::new(), }, - ominous_banner: matches!( - c.get("minecraft:banner_patterns"), - Some(Tag::List(layers)) if layers.first().is_some_and(|l| - l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus")) - ), + ominous_banner: c + .get("minecraft:item_name") + .and_then(|n| n.get("translate")) + .and_then(string) + .as_deref() + == Some("block.minecraft.ominous_banner") + && matches!( + c.get("minecraft:banner_patterns"), + Some(Tag::List(layers)) if layers.len() == OMINOUS_LAYERS.len()), ominous_amplifier: c .get("minecraft:ominous_bottle_amplifier") .and_then(int) diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index c7eb83aae..bd0d44f92 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -60,7 +60,20 @@ pub struct ItemInfo { pub equip_sound: Option, /// `jukebox_playable`: the jukebox song it plays. pub jukebox_song: Option, + /// `crafting_remainder`: what stays in the grid when the item is used in a recipe. + pub crafting_remainder: Option, + /// `dye`: the dye colour name (dyes, and anything else with the component). + pub dye: Option, } +/// `Item.Properties.craftRemainder` (not a data component, so not in the +/// default-component report): what an item leaves in the grid when crafted with. +pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [ + ("minecraft:water_bucket", "minecraft:bucket"), + ("minecraft:lava_bucket", "minecraft:bucket"), + ("minecraft:milk_bucket", "minecraft:bucket"), + ("minecraft:dragon_breath", "minecraft:glass_bottle"), + ("minecraft:honey_bottle", "minecraft:glass_bottle"), +]; /// A reduction of `blocks_attacks.damage_reductions`. #[derive(Clone, Debug)] pub struct BlockReduction { @@ -264,8 +277,6 @@ fn entity_spec(tags: &HashMap>, spec: &str) -> HashSet Result { - let raw: BTreeMap = - serde_json::from_slice(&fs::read(root.join("items.json"))?)?; let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); for (i, s) in facts.states.iter().enumerate() { let default = registry.default_state(&s.name); @@ -275,6 +286,16 @@ impl Items { .or_insert(BlockStateId(i as u32)); } } + Self::load_with(root, &block_for_item) + } + /// Every item's default components and the tags, without the block <-> + /// item mapping (for headless tools that never place blocks). + pub fn catalog(root: &Path) -> Result { + Self::load_with(root, &HashMap::new()) + } + fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result { + let raw: BTreeMap = + serde_json::from_slice(&fs::read(root.join("items.json"))?)?; let entity_tags = load_tags(root, "entity_type")?; let mut items = HashMap::new(); let mut order = Vec::new(); @@ -352,6 +373,11 @@ impl Items { .as_str() .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), + dye: c["minecraft:dye"].as_str().map(str::to_owned), + crafting_remainder: CRAFT_REMAINDERS + .iter() + .find(|(item, _)| *item == name) + .map(|(_, rest)| (*rest).to_owned()), use_speed: c["minecraft:use_effects"]["speed_multiplier"] .as_f64() .unwrap_or(0.2) as f32, diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 50edd8329..4aeb50f7c 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -287,7 +287,7 @@ impl Book { category: crafting_category(&category), group: group(&grp), display, - result: result.clone(), + result: result.create(), }); } for c in &recipes.cooking { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java new file mode 100644 index 000000000..09d75a7d8 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java @@ -0,0 +1,132 @@ +package dev.horizonlab.parity; + +import java.lang.reflect.Field; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.*; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.RegistryOps; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +/** + * Shared set-up for the interaction/inventory parity oracles: the vanilla data + * pack loaded into registries (as the server does), an NBT registry ops, a + * stand-in ServerLevel that only answers registryAccess, and canonical text + * for item stacks and NBT so both sides print comparable lines. + */ +public final class ParityData { + public static HolderLookup.Provider lookup; + public static RegistryAccess access; + public static RegistryOps ops; + public static ServerLevel level; + + public static void init() throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + access = loaded.layers().compositeAccess(); + ops = RegistryOps.create(NbtOps.INSTANCE, lookup); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + Object unsafe = unsafeField.get(null); + level = (ServerLevel) unsafe.getClass().getMethod("allocateInstance", Class.class).invoke(unsafe, ServerLevel.class); + Field registryAccess = Level.class.getDeclaredField("registryAccess"); + registryAccess.setAccessible(true); + long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, registryAccess); + unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, level, offset, access); + } + + /** "-" is the empty stack; otherwise ItemStack.CODEC over SNBT. */ + public static ItemStack stack(String snbt) throws Exception { + if (snbt.equals("-")) return ItemStack.EMPTY; + Tag tag = TagParser.parseCompoundFully(snbt); + return ItemStack.CODEC.parse(ops, tag).getOrThrow(); + } + + public static String canon(ItemStack stack) { + if (stack == null || stack.isEmpty()) return "-"; + Tag tag = ItemStack.CODEC.encodeStart(ops, stack).getOrThrow(); + return canon(tag); + } + + /** Sorted-key, type-annotated text of an NBT tag. */ + public static String canon(Tag tag) { + StringBuilder out = new StringBuilder(); + canon(tag, out); + return out.toString(); + } + + private static void canon(Tag tag, StringBuilder out) { + switch (tag) { + case ByteTag t -> out.append(t.value()).append('b'); + case ShortTag t -> out.append(t.value()).append('s'); + case IntTag t -> out.append(t.value()); + case LongTag t -> out.append(t.value()).append('L'); + case FloatTag t -> out.append(t.value()).append('f'); + case DoubleTag t -> out.append(t.value()).append('d'); + case StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"'); + case ByteArrayTag t -> { + out.append("[B;"); + byte[] a = t.getAsByteArray(); + for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]); + out.append(']'); + } + case IntArrayTag t -> { + out.append("[I;"); + int[] a = t.getAsIntArray(); + for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]); + out.append(']'); + } + case LongArrayTag t -> { + out.append("[L;"); + long[] a = t.getAsLongArray(); + for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]); + out.append(']'); + } + case ListTag t -> { + out.append('['); + for (int i = 0; i < t.size(); i++) { + if (i > 0) out.append(','); + canon(t.get(i), out); + } + out.append(']'); + } + case CompoundTag t -> { + out.append('{'); + boolean first = true; + for (String key : new TreeSet<>(t.keySet())) { + if (!first) out.append(','); + first = false; + out.append(key).append(':'); + canon(t.get(key), out); + } + out.append('}'); + } + default -> throw new IllegalStateException(tag.toString()); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java new file mode 100644 index 000000000..f35cd5337 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java @@ -0,0 +1,140 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.*; + +/** + * Original oracle: vanilla's RecipeManager over the data pack's recipes. + * Tab-separated commands (stacks are SNBT of ItemStack.CODEC, "-" is empty): + * craft N cells..., cook TYPE stack, stonecut stack, smith template base addition. + * "dump" prints every crafting recipe's ingredient item lists for the generator. + */ +public final class VanillaRecipeOracle { + static RecipeManager recipes; + + public static void main(String[] args) throws Exception { + ParityData.init(); + recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + if (args[0].equals("dump")) { + dump(Path.of(args[1])); + return; + } + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + String result; + try { + result = run(line.split("\t", -1)); + } catch (Exception e) { + result = "error"; + } + out.println(result); + } + } + } + + static String run(String[] f) throws Exception { + switch (f[0]) { + case "craft": { + int n = Integer.parseInt(f[1]); + List items = new ArrayList<>(); + for (int i = 0; i < n * n; i++) items.add(ParityData.stack(f[2 + i])); + var positioned = CraftingInput.ofPositioned(n, n, items); + var input = positioned.input(); + if (input.isEmpty()) return "none"; + var found = recipes.getRecipeFor(RecipeType.CRAFTING, input, null); + if (found.isEmpty()) return "none"; + var recipe = found.get().value(); + var result = recipe.assemble(input); + var rest = recipe.getRemainingItems(input); + StringJoiner joiner = new StringJoiner(";"); + for (int i = 0; i < rest.size(); i++) { + if (rest.get(i).isEmpty()) continue; + int at = (positioned.top() + i / input.width()) * n + positioned.left() + i % input.width(); + joiner.add(at + "=" + ParityData.canon(rest.get(i))); + } + return found.get().id().identifier().getPath() + "\t" + ParityData.canon(result) + "\t" + joiner; + } + case "cook": { + RecipeType type = switch (f[1]) { + case "smelting" -> RecipeType.SMELTING; + case "blasting" -> RecipeType.BLASTING; + case "smoking" -> RecipeType.SMOKING; + default -> RecipeType.CAMPFIRE_COOKING; + }; + return cook(type, ParityData.stack(f[2])); + } + case "stonecut": { + var stack = ParityData.stack(f[1]); + StringJoiner joiner = new StringJoiner(";"); + for (var entry : recipes.getSynchronizedStonecutterRecipes().selectByInput(stack).entries()) { + var holder = entry.recipe().recipe().get(); + joiner.add(holder.id().identifier().getPath() + "=" + ParityData.canon(holder.value().assemble(new SingleRecipeInput(stack)))); + } + return joiner.toString(); + } + case "smith": { + var input = new SmithingRecipeInput(ParityData.stack(f[1]), ParityData.stack(f[2]), ParityData.stack(f[3])); + var found = recipes.getRecipeFor(RecipeType.SMITHING, input, null); + if (found.isEmpty()) return "none"; + return ParityData.canon(found.get().value().assemble(input)); + } + default: + throw new IllegalArgumentException(f[0]); + } + } + + static String cook(RecipeType type, ItemStack stack) { + if (stack.isEmpty()) return "none"; + var input = new SingleRecipeInput(stack); + var found = recipes.getRecipeFor(type, input, null); + if (found.isEmpty()) return "none"; + var recipe = found.get().value(); + return found.get().id().identifier().getPath() + "\t" + ParityData.canon(recipe.assemble(input)) + "\t" + recipe.experience() + "\t" + recipe.cookingTime(); + } + + static String items(Ingredient ingredient) { + if (ingredient == null) return "[]"; + StringBuilder row = new StringBuilder("["); + var items = ingredient.items().toList(); + for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"'); + return row.append(']').toString(); + } + + static void dump(Path path) throws Exception { + try (var out = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) { + for (var holder : recipes.getRecipes()) { + var recipe = holder.value(); + if (recipe instanceof SmithingRecipe smithing) { + out.println("{\"id\":\"" + holder.id().identifier().getPath() + "\",\"kind\":\"" + recipe.getClass().getSimpleName() + + "\",\"template\":" + items(smithing.templateIngredient().orElse(null)) + ",\"base\":" + items(smithing.baseIngredient()) + + ",\"addition\":" + items(smithing.additionIngredient().orElse(null)) + "}"); + continue; + } + if (recipe.getType() != RecipeType.CRAFTING) continue; + var info = recipe.placementInfo(); + StringBuilder row = new StringBuilder(); + row.append("{\"id\":\"").append(holder.id().identifier().getPath()).append("\",\"kind\":\"").append(recipe.getClass().getSimpleName()).append("\",\"slots\":["); + for (int i = 0; i < info.slotsToIngredientIndex().size(); i++) row.append(i > 0 ? "," : "").append(info.slotsToIngredientIndex().getInt(i)); + row.append("],\"ingredients\":["); + boolean firstIngredient = true; + for (var ingredient : info.ingredients()) { + row.append(firstIngredient ? "" : ",").append('['); + firstIngredient = false; + var items = ingredient.items().toList(); + for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"'); + row.append(']'); + } + row.append("]}"); + out.println(row); + } + } + } +} diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py new file mode 100644 index 000000000..19cbd44bd --- /dev/null +++ b/tools/interaction_lab.py @@ -0,0 +1,71 @@ +"""Shared plumbing for the interaction/inventory differential harnesses +(test_recipe_parity, test_menu_click_parity, test_block_interaction_parity): +compile and run a vanilla Java oracle headlessly, run the matching Rust +example, and report differing lines grouped by a key.""" +import json +import os +from pathlib import Path +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +RESOURCES = lab.LOCAL / 'horizon-client' / '26.3' +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' + + +def work_dir(name): + path = lab.LOCAL / name + path.mkdir(parents=True, exist_ok=True) + return path + + +class Vanilla: + """Compiles oracles against the pinned server jar and runs them.""" + + def __init__(self, work): + self.lock, self.jars, self.libraries = base.verify_artifacts() + self.work = work + self.classes = work / 'classes' + self.classes.mkdir(exist_ok=True) + self.deps = os.pathsep.join(map(str, [self.jars['server'], *self.libraries])) + + def compile(self, *oracles): + sources = [PARITY / (name + '.java') for name in oracles] + subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', + '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', + '-cp', self.deps, '-d', str(self.classes), *map(str, sources)], check=True) + + def run(self, oracle, *args, heap='2G'): + subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps, + 'dev.horizonlab.parity.' + oracle, *map(str, args)], check=True) + + +def cargo_example(package, example, *args, profile=None): + command = ['cargo', 'run', '-q', '-j3'] + if profile: + command += ['--profile', profile] + command += ['-p', package, '--example', example, '--', *map(str, args)] + subprocess.run(command, check=True, cwd=lab.ROOT) + + +def compare(cases, native_path, rust_path, key, describe=None, limit=3): + """Print differing cases grouped by key(case, native_line); returns the count.""" + native = Path(native_path).read_text().split('\n') + rust = Path(rust_path).read_text().split('\n') + if len(native) != len(rust): + print(f'line counts differ: native {len(native)} rust {len(rust)}') + groups = {} + for case, a, b in zip(cases, native, rust): + if a != b: + groups.setdefault(key(case, a), []).append((case, a, b)) + describe = describe or (lambda case: case if isinstance(case, str) else json.dumps(case)) + total = sum(len(v) for v in groups.values()) + for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): + print(f'{name}: {len(entries)} differing') + for case, a, b in entries[:limit]: + print(f' case {describe(case)}\n native {a}\n rust {b}') + print(f'{len(cases) - total}/{len(cases)} cases match') + return total diff --git a/tools/test_recipe_parity.py b/tools/test_recipe_parity.py new file mode 100644 index 000000000..5f96e164e --- /dev/null +++ b/tools/test_recipe_parity.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Compare crafting, cooking, stonecutting and smithing with vanilla's RecipeManager. + +The Java oracle (VanillaRecipeOracle) loads the data pack's recipe registry and +answers craft/cook/stonecut/smith commands; the Rust example (recipe_fixture) +answers the same commands from horizon_client::crafting and ::stations. +Crafting cases are built from every recipe's own ingredients (placed at random +offsets, mirrored, perturbed) plus focused generators for the special recipes +(banners, books, fireworks, dyeing, repair, pots, tipped arrows, maps) and +random grids. Results are compared as canonical ItemStack NBT, with the +matched recipe id and the crafting remainders. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] +POTIONS = ['minecraft:healing', 'minecraft:swiftness', 'minecraft:water', 'minecraft:night_vision'] +SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst'] + + +def quote(text): + return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"' + + +def stack(item, count=1, **components): + """SNBT of an ItemStack.CODEC compound; component values are SNBT text.""" + body = ','.join(f'{quote("minecraft:" + key)}:{value}' for key, value in sorted(components.items())) + comp = f',components:{{{body}}}' if body else '' + return f'{{id:{quote(item)},count:{count}{comp}}}' + + +def colors(rng, n=None): + n = rng.randrange(0, 4) if n is None else n + return '[I;' + ','.join(str(rng.randrange(1 << 24)) for _ in range(n)) + ']' + + +def explosion(rng): + return ('{shape:%s,colors:%s,fade_colors:%s,has_trail:%db,has_twinkle:%db}' + % (quote(rng.choice(SHAPES)), colors(rng), colors(rng), rng.randrange(2), rng.randrange(2))) + + +class Gen: + def __init__(self, rng, items, recipes, patterns): + self.rng = rng + self.items = items + self.recipes = recipes + self.patterns = patterns + self.durable = [k for k, v in items.items() if v.get('minecraft:max_damage')] + + def layers(self, n=None): + n = self.rng.choice([0, 0, 1, 2, 6, 7]) if n is None else n + return '[' + ','.join('{pattern:%s,color:%s}' % (quote(self.rng.choice(self.patterns)), quote(self.rng.choice(DYES))) for _ in range(n)) + ']' + + def book(self, generation=None): + g = self.rng.randrange(4) if generation is None else generation + return stack('minecraft:written_book', written_book_content='{title:{raw:"T"},author:"A",generation:%d,pages:[{raw:"p1"},{raw:"p2"}]}' % g) + + def stack(self, item, count=None, rich=0.5): + """A stack of the item, with the components that apply to it.""" + rng = self.rng + info = self.items.get(item, {}) + count = rng.choice([1, 1, 1, 2, 3]) if count is None else count + c = {} + if rng.random() < rich: + if info.get('minecraft:max_damage') and rng.random() < 0.7: + c['damage'] = str(rng.randrange(0, info['minecraft:max_damage'] + 1)) + if info.get('minecraft:max_damage') and rng.random() < 0.3: + c['enchantments'] = '{%s:1}' % quote(rng.choice(['minecraft:binding_curse', 'minecraft:vanishing_curse', 'minecraft:mending', 'minecraft:unbreaking'])) + if item.endswith('_banner'): + c['banner_patterns'] = self.layers() + if item == 'minecraft:shield': + if rng.random() < 0.3: + c['banner_patterns'] = self.layers(rng.randrange(1, 3)) + c['base_color'] = quote(rng.choice(DYES)) + if item == 'minecraft:written_book': + return self.book() + if item == 'minecraft:firework_star': + c['firework_explosion'] = explosion(rng) + if item == 'minecraft:firework_rocket': + c['fireworks'] = '{flight_duration:%db,explosions:[%s]}' % (rng.randrange(1, 4), explosion(rng)) + if item in ('minecraft:lingering_potion', 'minecraft:potion', 'minecraft:splash_potion'): + c['potion_contents'] = '{potion:%s}' % quote(rng.choice(POTIONS)) + if item.startswith('minecraft:leather_') or item in ('minecraft:wolf_armor',): + if rng.random() < 0.6: + c['dyed_color'] = str(rng.randrange(1 << 24)) + if item.endswith('shulker_box'): + c['container'] = '[{slot:0,item:{id:"minecraft:stone",count:%d}}]' % rng.randrange(1, 64) + if item.endswith('_bundle') or item == 'minecraft:bundle': + c['bundle_contents'] = '[{id:"minecraft:stone",count:%d}]' % rng.randrange(1, 64) + if item == 'minecraft:filled_map': + c['map_id'] = str(rng.randrange(1, 5)) + return stack(item, count, **c) + + def plain(self, item): + return self.stack(item, rich=0.3) + + +def place(rng, cells, size): + """Cells (stack list) at random free positions of a size x size grid.""" + grid = ['-'] * (size * size) + spots = rng.sample(range(size * size), len(cells)) + for spot, cell in zip(spots, cells): + grid[spot] = cell + return grid + + +def place_box(rng, width, height, cells, size): + """A width x height pattern at a random offset of the grid.""" + x0 = rng.randrange(size - width + 1) + y0 = rng.randrange(size - height + 1) + grid = ['-'] * (size * size) + for i, cell in enumerate(cells): + grid[(y0 + i // width) * size + x0 + i % width] = cell + return grid + + +def craft_case(grid, size): + return 'craft\t%d\t%s' % (size, '\t'.join(grid)) + + +def recipe_cases(g, count_per): + rng = g.rng + for recipe in g.recipes: + if 'slots' not in recipe or not recipe['ingredients']: + continue + ingredients = recipe['ingredients'] + slots = recipe['slots'] + shaped = recipe['kind'] == 'ShapedRecipe' + if shaped: + width = recipe['width'] + height = len(slots) // width + for variant in range(count_per): + pick = [g.plain(rng.choice(i)) if i else '-' for i in ingredients] + if shaped: + cells = ['-' if s < 0 else pick[s] for s in slots] + if variant % 3 == 1: # mirrored + cells = [cells[y * width + width - 1 - x] for y in range(height) for x in range(width)] + size = rng.choice([s for s in (2, 3) if s >= max(width, height)]) + grid = place_box(rng, width, height, cells, size) + else: + size = 3 if len(pick) > 4 else rng.choice([2, 3]) + grid = place(rng, pick, size) + yield craft_case(grid, size) + # Perturbations: drop one, swap one for a stranger, add one, shift a count. + if variant < 2: + filled = [i for i, c in enumerate(grid) if c != '-'] + broken = list(grid) + broken[rng.choice(filled)] = '-' + yield craft_case(broken, size) + broken = list(grid) + broken[rng.choice(filled)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])) + yield craft_case(broken, size) + free = [i for i, c in enumerate(grid) if c == '-'] + if free: + broken = list(grid) + broken[rng.choice(free)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])) + yield craft_case(broken, size) + + +def special_cases(g, n): + rng = g.rng + items = g.items + banners = [f'minecraft:{d}_banner' for d in DYES] + dyes = [f'minecraft:{d}_dye' for d in DYES] + armor = [k for k in items if k.startswith('minecraft:leather_') and k.count('_') == 2] + ['minecraft:wolf_armor'] + boxes = [k for k in items if k.endswith('shulker_box')] + bundles = [k for k in items if k.endswith('bundle')] + skulls = [k for k in items if k.endswith('_head') or k.endswith('_skull')] + for _ in range(n): + size = rng.choice([2, 3]) + # banner duplicate / shield decoration + a, b = rng.choice(banners), rng.choice(banners) + yield craft_case(place(rng, [g.stack(a, 1, 1.0), g.stack(b if rng.random() < 0.3 else a, 1, 0.5)], size), size) + yield craft_case(place(rng, [g.stack(rng.choice(banners), 1, 1.0), g.stack('minecraft:shield', 1, 0.5)], size), size) + # book cloning + books = [g.book(rng.choice([0, 0, 1, 2, 3]))] + [stack('minecraft:writable_book') for _ in range(rng.randrange(0, 4))] + if rng.random() < 0.2: + books.append(g.book()) + yield craft_case(place(rng, books, 3), 3) + # fireworks + star = [stack(rng.choice(['minecraft:gunpowder'] + dyes[:2] + ['minecraft:gold_nugget', 'minecraft:feather', 'minecraft:fire_charge', + 'minecraft:diamond', 'minecraft:glowstone_dust', rng.choice(skulls)])) + for _ in range(rng.randrange(1, 7))] + star += [stack('minecraft:gunpowder'), stack(rng.choice(dyes))] + yield craft_case(place(rng, star[:9], 3), 3) + fade = [g.stack('minecraft:firework_star', 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))] + yield craft_case(place(rng, fade, 3), 3) + rocket = [stack('minecraft:paper')] + [stack('minecraft:gunpowder') for _ in range(rng.randrange(0, 5))] + \ + [g.stack('minecraft:firework_star', 1, 1.0) for _ in range(rng.randrange(0, 4))] + yield craft_case(place(rng, rocket[:9], 3), 3) + # armour dyeing, with leftovers + dye_cells = [g.stack(rng.choice(armor), 1, 0.7)] + [stack(rng.choice(dyes + ['minecraft:stick'] if rng.random() < 0.1 else dyes)) for _ in range(rng.randrange(1, 5))] + yield craft_case(place(rng, dye_cells[:9], 3), 3) + # repair + tool = rng.choice(g.durable) + pair = [g.stack(tool, 1, 1.0), g.stack(tool if rng.random() < 0.85 else rng.choice(g.durable), 1, 1.0)] + yield craft_case(place(rng, pair, size), size) + # shulker boxes and bundles + yield craft_case(place(rng, [g.stack(rng.choice(boxes + bundles), 1, 1.0), stack(rng.choice(dyes))], size), size) + multi = [g.stack(rng.choice(boxes + bundles), 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))] + yield craft_case(place(rng, multi, 3), 3) + # decorated pots + sherds = ['minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:archer_pottery_sherd', 'minecraft:stick', 'minecraft:blade_pottery_sherd'] + pot = ['-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-'] + if rng.random() < 0.2: + pot[rng.choice([0, 2, 6, 8, 4])] = stack('minecraft:brick') + yield craft_case(pot, 3) + yield craft_case([stack('minecraft:brick') if i in (1, 3, 5, 7) else '-' for i in range(9)], 3) + # tipped arrows + ring = [stack('minecraft:arrow', rng.choice([1, 2]))] * 9 + ring[4] = g.stack('minecraft:lingering_potion', 1, 1.0 if rng.random() < 0.8 else 0.0) + yield craft_case(ring, 3) + # map cloning + maps = [g.stack('minecraft:filled_map', 1, 1.0)] + [stack('minecraft:map') for _ in range(rng.randrange(1, 9))] + yield craft_case(place(rng, maps, 3), 3) + # mixed junk of the interesting items + pool = banners + dyes + armor + boxes + bundles + ['minecraft:written_book', 'minecraft:writable_book', 'minecraft:firework_star', + 'minecraft:paper', 'minecraft:gunpowder', 'minecraft:shield', 'minecraft:glass_bottle', + 'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:bowl', 'minecraft:stick'] + junk = [g.stack(rng.choice(pool), None, 0.7) for _ in range(rng.randrange(1, 6))] + yield craft_case(place(rng, junk, 3), 3) + + +def smithing_cases(g): + rng = g.rng + for recipe in g.recipes: + if recipe['kind'].startswith('Smithing'): + for _ in range(24): + pick = lambda key: g.plain(rng.choice(recipe[key])) if recipe[key] else '-' + yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), pick('addition')) + yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))) + # Armour with a trim already on it. + trims = ['{material:"minecraft:iron",pattern:"minecraft:coast"}', '{material:"minecraft:gold",pattern:"minecraft:sentry"}'] + for recipe in g.recipes: + if recipe['kind'] == 'SmithingTrimRecipe': + for trim in trims: + base = rng.choice(recipe['base']) + yield 'smith\t%s\t%s\t%s' % (stack(rng.choice(recipe['template'])), stack(base, 1, trim=trim), stack(rng.choice(recipe['addition']))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--variants', type=int, default=6) + parser.add_argument('--specials', type=int, default=1500) + parser.add_argument('--random', type=int, default=4000) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + work = lib.work_dir('recipe-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaRecipeOracle') + vanilla.run('VanillaRecipeOracle', 'dump', work / 'recipes.jsonl') + recipes = [json.loads(line) for line in (work / 'recipes.jsonl').read_text().splitlines()] + # Shaped recipes: widths come from the data pack. + for recipe in recipes: + path = lib.RESOURCES / 'data/minecraft/recipe' / (recipe['id'] + '.json') + data = json.loads(path.read_text()) + if recipe['kind'] == 'ShapedRecipe': + rows = [row.rstrip() for row in data['pattern']] + left = min(len(row) - len(row.lstrip()) for row in rows if row) + recipe['width'] = max(len(row) for row in rows) - left + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json')) + rng = random.Random(args.seed) + g = Gen(rng, items, recipes, patterns) + cases = list(recipe_cases(g, args.variants)) + cases += list(special_cases(g, args.specials)) + pool = [k for k in items if not k.endswith('_spawn_egg') and k != 'minecraft:air'] + interesting = [f'minecraft:{d}_dye' for d in DYES] + ['minecraft:paper', 'minecraft:gunpowder', 'minecraft:bowl', 'minecraft:stick', + 'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:water_bucket'] + for _ in range(args.random): + size = rng.choice([2, 3]) + cells = [g.stack(rng.choice(interesting if rng.random() < 0.6 else pool), None, 0.5) for _ in range(rng.randrange(1, size * size + 1))] + cases.append(craft_case(place(rng, cells, size), size)) + for kind in ['smelting', 'blasting', 'smoking', 'campfire_cooking']: + for item in [i for i in items if i != 'minecraft:air']: + cases.append('cook\t%s\t%s' % (kind, stack(item))) + for item in [i for i in items if i != 'minecraft:air']: + cases.append('stonecut\t' + stack(item)) + cases += list(smithing_cases(g)) + (work / 'cases.txt').write_text(''.join(c + '\n' for c in cases)) + vanilla.run('VanillaRecipeOracle', work / 'cases.txt', work / 'native.txt') + lib.cargo_example('horizon-client', 'recipe_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt') + + def key(case, native_line): + kind = case.split('\t')[0] + return kind if kind != 'craft' else 'craft ' + native_line.split('\t')[0] + + def describe(case): + return case if len(case) < 1200 else case[:1200] + '...' + total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', key, describe, args.limit) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From 513004936d195237b470c174ac2fe9fd0829436f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:17:24 +0200 Subject: [PATCH 02/16] Keep container names and saddle components, order and search the recipe book like vanilla Containers now remember a custom name: it is read and saved as CustomName, taken from the item when placed (including by dispensers), shown as the screen title of chests, furnaces, the brewing stand, hoppers, dispensers and the crafter, and given back to the dropped item when the block is broken. Saddles on pigs, striders and horses are kept as full item stacks instead of a flag, so their components survive taming, the horse menu, dispensers, saving and death drops. The recipe book lists dye, transmute (shulker box, bundle, map cloning) and tipped arrow recipes, searches the tooltip lines and ids of a collection's results the way the vanilla search tree does, and squeezes new recipes' tabs and buttons once, saving the pending recipes as toBeDisplayed. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/chunk.rs | 3 + crates/horizon-client/src/crafting.rs | 59 ++++++++++ crates/horizon-client/src/entity_nbt.rs | 30 ++--- crates/horizon-client/src/game.rs | 16 +++ crates/horizon-client/src/game/creatures.rs | 4 +- crates/horizon-client/src/game/dispenser.rs | 3 +- crates/horizon-client/src/game/machines.rs | 1 + .../src/game/machines/crafter.rs | 2 +- crates/horizon-client/src/game/mount_menu.rs | 11 +- crates/horizon-client/src/game/mounts.rs | 6 +- crates/horizon-client/src/game/recipe_book.rs | 108 ++++++++++++++++-- crates/horizon-client/src/game/stations.rs | 8 +- crates/horizon-client/src/game/storage.rs | 42 ++++++- crates/horizon-client/src/hud.rs | 8 ++ crates/horizon-client/src/mobs.rs | 22 ++++ crates/horizon-client/src/recipe_book.rs | 94 +++++++++++---- crates/horizon-client/src/save.rs | 17 ++- crates/horizon-client/src/streaming.rs | 3 + crates/horizon-client/src/world.rs | 3 + 19 files changed, 376 insertions(+), 64 deletions(-) diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index d5e65655c..6e76783ba 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -100,6 +100,8 @@ pub struct Chunk { pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>, + /// `CustomName` of the container block entities (shown as the screen title). + pub block_names: Vec<((i32, i32, i32), String)>, /// Generation postprocessing marks (ProtoChunk.postProcessing) as world /// positions, applied once by LevelChunk.postProcessGeneration. pub postprocess: Vec<[i32; 3]>, @@ -125,6 +127,7 @@ impl Chunk { light_loaded: false, fresh: false, block_entities: Vec::new(), + block_names: Vec::new(), structure_refs: Vec::new(), postprocess: Vec::new(), saved: None, diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index cf2e43f03..754c701b3 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -253,6 +253,65 @@ pub enum Special { /// `RepairItemRecipe`: two damaged items of one kind. RepairItem, } +impl Special { + /// The recipe-book displays of a learnable (non-custom) crafting recipe: + /// its layout and result. + pub fn book_displays(&self) -> Vec<(crate::recipe_book::Display, ItemStack)> { + use crate::recipe_book::Display; + match self { + Self::Transmute { + input, + material, + min, + max, + add_count, + result, + } => (*min..=*max) + .map(|n| { + let mut ingredients = vec![input.clone()]; + ingredients.extend(std::iter::repeat_n(material.clone(), n)); + let mut made = result.create(); + if result.item.is_none() { + // The result keeps the input's item: show the first one. + if let Some(first) = input.0.iter().min() { + made.item = Arc::from(first.as_str()); + } + } + if *add_count { + made.count += n as u32; + } + (Display::Shapeless(ingredients), made) + }) + .collect(), + Self::Dye { + target, + dye, + result, + } => vec![( + Display::Shapeless(vec![target.clone(), dye.clone()]), + result.create(), + )], + Self::Imbue { + source, + material, + result, + } => { + let cells = (0..9) + .map(|i| Some(if i == 4 { source } else { material }.clone())) + .collect(); + vec![( + Display::Shaped { + width: 3, + height: 3, + cells, + }, + result.create(), + )] + } + _ => Vec::new(), + } + } +} /// `CraftingInput`: the occupied bounding box of the grid. pub struct Input<'a> { pub width: usize, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index ea44c09be..0cc6b4ec8 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -211,11 +211,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&"Items".into()); } let mut equipment = Vec::new(); - if m.extra.saddled { - equipment.push(( - "saddle", - Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]), - )); + if let Some(saddle) = m.saddle_item() { + equipment.push(("saddle", crate::save::item_to_nbt(&saddle))); } if let Some(armor) = &m.extra.head { equipment.push(( @@ -241,11 +238,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { Some(Tag::Compound(c)) => c.clone(), _ => Compound::new(), }; - if m.extra.saddled { - equipment.insert( - "saddle".into(), - Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]), - ); + if let Some(saddle) = m.saddle_item() { + equipment.insert("saddle".into(), crate::save::item_to_nbt(&saddle)); } else { equipment.remove(&"saddle".into()); } @@ -499,8 +493,15 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.species(), crate::mobs::Species::Pig | crate::mobs::Species::Strider ) { - m.extra.saddled = - tag.get("equipment").and_then(|e| e.get("saddle")).is_some() || flag(tag, "Saddle"); + let saddle = tag + .get("equipment") + .and_then(|e| e.get("saddle")) + .and_then(crate::save::item_from_nbt); + if saddle.is_some() || flag(tag, "Saddle") { + m.set_saddle(Some(saddle.unwrap_or_else(|| { + crate::items::ItemStack::new("minecraft:saddle", 1) + }))); + } } if crate::mobs::equine::is_equine(m.species()) { m.extra.tame = flag(tag, "Tame"); @@ -514,7 +515,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.items = crate::save::decode_items(tag.get("Items"), 15); } let eq = tag.get("equipment"); - m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some(); + m.set_saddle( + eq.and_then(|e| e.get("saddle")) + .and_then(crate::save::item_from_nbt), + ); m.extra.head = eq .and_then(|e| e.get("body")) .and_then(|b| text(b.get("id"))) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e8d7eb2e4..afbe3345c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -630,6 +630,8 @@ struct Game<'a> { pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, /// Layers of broken banners waiting for their dropped item. pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, + /// Custom names of broken containers, for the dropped item (`copy_components`). + pending_names: HashMap<[i32; 3], (String, String)>, /// The recipe book of the open screen (game/recipe_book.rs). recipe_ui: recipe_book::RecipeUi, /// The horse inventory (game/mount_menu.rs). @@ -1005,6 +1007,7 @@ impl Game<'_> { /// Block.popResource fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { self.attach_shulker_contents(pos, &mut stack); + self.attach_container_name(pos, &mut stack); self.attach_banner_layers(pos, &mut stack); let r = &mut self.world.random; let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; @@ -1838,6 +1841,7 @@ impl Game<'_> { .block_entities .insert((target[0], target[1], target[2]), entity); self.fill_placed_box(target, &stack); + self.name_placed_container(target, &stack); self.fill_placed_banner(target, &stack); if sign { self.open_sign_editor((target[0], target[1], target[2]), true); @@ -3249,6 +3253,7 @@ impl Game<'_> { } }; part(batch, tex, 0.0, 0.0, 176.0, 166.0, ox, oy); + let title = &self.container_title(title.to_owned()); let tw = HudBatch::text_width(atlas, title); batch.text(atlas, title, ox + (176.0 - tw) / 2.0, oy + 6.0, grey, false); batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); @@ -4416,6 +4421,13 @@ impl Game<'_> { .filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z) .map(|(p, e)| (*p, e.clone())) .collect(); + c.block_names = self + .world + .block_names + .iter() + .filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z) + .map(|(p, n)| (*p, n.clone())) + .collect(); self.attach_save_data(&mut c); Arc::new(c) } @@ -6999,6 +7011,9 @@ impl Game<'_> { self.world .block_entities .retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z)); + self.world + .block_names + .retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z)); } if !modified.is_empty() && let Err(e) = self @@ -7751,6 +7766,7 @@ pub fn run() -> Result<()> { ender_open: None, pending_shulker: HashMap::new(), pending_banner: HashMap::new(), + pending_names: HashMap::new(), recipe_ui: Default::default(), mount_menu: Default::default(), hook: None, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 81f17ed01..afba945ab 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -727,8 +727,8 @@ impl Game<'_> { } // Saddles, horse armour and chests always drop. let mut gear: Vec<&str> = Vec::new(); - if m.extra.saddled { - gear.push("minecraft:saddle"); + if let Some(saddle) = m.saddle_item() { + self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10); } // WitherBoss.dropCustomDeathLoot. if m.species() == Species::Wither { diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 75f39881d..9eb27a255 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -578,7 +578,7 @@ impl Game<'_> { (_, Some(1)) => m.extra.chest = Some(item.clone()), (_, Some(2)) => m.extra.legs = Some(item.clone()), (_, Some(3)) => m.extra.feet = Some(item.clone()), - ("saddle", _) => m.extra.saddled = true, + ("saddle", _) => m.set_saddle(Some(one.clone())), _ => m.extra.head = Some(item.clone()), } // setGuaranteedDrop / setPersistenceRequired. @@ -1155,6 +1155,7 @@ impl Game<'_> { if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { self.world.block_entities.insert(target, entity); self.fill_placed_box([target.0, target.1, target.2], &stack); + self.name_placed_container([target.0, target.1, target.2], &stack); } let sounds = self.res.facts.get(state).sounds.clone(); self.audio.play( diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 5f75bf86d..418d0eafc 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -746,6 +746,7 @@ impl Game<'_> { batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX); } let grey = horizon_client::hud::rgba(64, 64, 64, 255); + let title = &self.container_title(title.to_owned()); let title_x = if screen == Screen::Hopper { 8.0 } else { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 470424c44..1c8a558e6 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -270,7 +270,7 @@ impl Game<'_> { 256.0, ); let grey = rgba(64, 64, 64, 255); - let title = self.translate("container.crafter", "Crafter"); + let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); batch.text( atlas, diff --git a/crates/horizon-client/src/game/mount_menu.rs b/crates/horizon-client/src/game/mount_menu.rs index 3e33872cb..8fe819a96 100644 --- a/crates/horizon-client/src/game/mount_menu.rs +++ b/crates/horizon-client/src/game/mount_menu.rs @@ -67,10 +67,7 @@ impl Game<'_> { mob: m.id, species, columns, - saddle: m - .extra - .saddled - .then(|| ItemStack::new("minecraft:saddle", 1)), + saddle: m.saddle_item(), armor: m .extra .head @@ -137,18 +134,18 @@ impl Game<'_> { let Some(index) = self.mount_mob_index(open.mob) else { return; }; - let (saddle, armor) = (open.saddle.is_some(), open.armor.clone()); + let (saddle, armor) = (open.saddle.clone(), open.armor.clone()); let items = open.items.clone(); let m = &mut self.mobs[index]; let at = m.center(); - let sound = if saddle && !m.extra.saddled { + let sound = if saddle.is_some() && !m.extra.saddled { Some("minecraft:entity.horse.saddle") } else if armor.is_some() && m.extra.head.is_none() { Some("minecraft:entity.horse.armor") } else { None }; - m.extra.saddled = saddle; + m.set_saddle(saddle); if open.show_armor { m.extra.head = armor.map(|a| a.item); } diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index bfe73d235..fdd6c5ece 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -38,13 +38,14 @@ impl Game<'_> { } /// `Pig` / `Strider.mobInteract`: saddle an adult, or ride a saddled one. fn interact_steerable(&mut self, index: usize, item: &str) -> bool { + let held = self.inventory[self.selected].clone(); let m = &mut self.mobs[index]; if m.is_baby() || !m.alive() || Some(m.id) == self.riding { return false; } let at = m.center(); if item == "minecraft:saddle" && !m.extra.saddled { - m.extra.saddled = true; + m.set_saddle(held); let sound = if m.species() == Species::Strider { "minecraft:entity.strider.saddle" } else { @@ -91,6 +92,7 @@ impl Game<'_> { } /// `AbstractHorse.mobInteract`. Returns whether the click was used. pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool { + let held = self.inventory[self.selected].clone(); let m = &self.mobs[index]; let species = m.species(); if matches!(species, Species::Pig | Species::Strider) { @@ -118,7 +120,7 @@ impl Game<'_> { let at = m.center(); let tamed = m.extra.tame; let sound = if item == "minecraft:saddle" && tamed && !m.extra.saddled { - m.extra.saddled = true; + m.set_saddle(held); Some("minecraft:entity.horse.saddle") } else if item.ends_with("_horse_armor") && species == Species::Horse diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 658db4ada..60fc4ec50 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -68,6 +68,9 @@ pub(super) struct RecipeUi { overlay: Option, view: View, view_key: u64, + /// Squeeze animations of new recipes: ticks left per button index and tab. + button_anim: Vec<(usize, f32)>, + tab_anim: Vec<(Tab, f32)>, } impl RecipeUi { @@ -179,6 +182,11 @@ impl Game<'_> { return; } self.ensure_book(); + for id in recipes { + if !self.level.recipe_book.to_be_displayed.contains(id) { + self.level.recipe_book.to_be_displayed.push(id.clone()); + } + } let icon = self .recipe_ui .book @@ -291,6 +299,71 @@ impl Game<'_> { if self.recipe_ui.page >= pages.max(1) { self.recipe_ui.page = 0; } + self.start_new_recipe_animations(book_type); + } + /// `RecipeBookTabButton.startAnimation` and `RecipeButton.init`: tabs + /// holding a recipe still to be displayed squeeze, and the buttons of the + /// shown page squeeze once and clear their recipes' highlight. + fn start_new_recipe_animations(&mut self, book_type: BookType) { + if self.level.recipe_book.to_be_displayed.is_empty() { + return; + } + let Some(book) = self.recipe_ui.book.take() else { + return; + }; + let unlocked = self.unlocked_recipes(); + let filtering = self.book_filtering(book_type); + let (gw, gh) = self.book_grid(); + let available = self.book_available(book_type); + let shown = |e: &Entry| { + (book_type != BookType::Crafting || e.fits(gw, gh)) + && (!filtering || available.can_craft(&e.requirements())) + }; + let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id); + let mut tabs = Vec::new(); + for tab in self.recipe_ui.view.tabs.clone() { + if tab == Tab::Search { + continue; + } + let hit = book + .collections(&unlocked, book_type, tab) + .iter() + .flat_map(|c| c.entries.iter()) + .any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i])); + if hit { + tabs.push((tab, 15.0)); + } + } + self.recipe_ui.tab_anim = tabs; + let first = self.recipe_ui.page * 20; + let mut buttons = Vec::new(); + let mut cleared = Vec::new(); + for (n, button) in self + .recipe_ui + .view + .buttons + .iter() + .skip(first) + .take(20) + .enumerate() + { + let ids: Vec<&String> = button + .entries + .iter() + .map(|e| &book.entries[e.0].id) + .filter(|id| self.level.recipe_book.to_be_displayed.contains(*id)) + .collect(); + if !ids.is_empty() { + buttons.push((first + n, 15.0)); + cleared.extend(ids.into_iter().cloned()); + } + } + self.level + .recipe_book + .to_be_displayed + .retain(|id| !cleared.contains(id)); + self.recipe_ui.button_anim = buttons; + self.recipe_ui.book = Some(book); } fn build_view(&mut self, ui: &RecipeUi, book_type: BookType) -> View { let Some(book) = ui.book.as_ref() else { @@ -329,9 +402,8 @@ impl Game<'_> { continue; } if !query.is_empty() - && !c.entries.iter().any(|&i| { - let e = &book.entries[i]; - book.matches_search(e, &query, &self.res.names.item(&e.result.item)) + && !book.collection_matches(&c.entries, &query, &|stack| { + self.stack_tooltip(stack).into_iter().map(|l| l.0).collect() }) { continue; @@ -972,26 +1044,30 @@ impl Game<'_> { .tab .filter(|t| tabs.contains(t)) .unwrap_or(Tab::Search); - let mut tab_icons = Vec::new(); + let frame = self.frame_ticks; for (n, tab) in tabs.iter().enumerate() { let (x, y) = self.tab_pos(xo, yo, n); let selected = *tab == current; let name = if selected { "tab_selected" } else { "tab" }; let sx = if selected { x - 2.0 } else { x }; + let start = batch.vertices.len(); batch.sprite(&self.res.atlas, &sprite(name), sx, y); let (a, b) = tab.icons(); let shift = if selected { -2.0 } else { 0.0 }; match b { Some(b) => { - tab_icons.push((a, x + 3.0 + shift, y + 5.0)); - tab_icons.push((b, x + 14.0 + shift, y + 5.0)); + self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0); + self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0); } - None => tab_icons.push((a, x + 9.0 + shift, y + 5.0)), + None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0), + } + if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) { + let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin(); + batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze); + entry.1 -= frame; } } - for (item, x, y) in tab_icons { - self.draw_item(batch, &ItemStack::new(item, 1), x, y); - } + self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0); // Craftable filter. let filtering = self.book_filtering(book_type); let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0); @@ -1019,6 +1095,7 @@ impl Game<'_> { break; }; let (x, y) = Self::button_pos(xo, yo, n); + let anim_start = batch.vertices.len(); let many = button.entries.len() > 1; let name = match (button.craftable(), many) { (true, true) => "slot_many_craftable", @@ -1048,6 +1125,16 @@ impl Game<'_> { offset -= 1.0; } self.draw_item_plain(batch, &stack, x + offset, y + offset); + if let Some(entry) = self + .recipe_ui + .button_anim + .iter_mut() + .find(|e| e.0 == first + n) + { + let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin(); + batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze); + entry.1 -= self.frame_ticks; + } if inside(cursor, x, y, 25.0, 25.0) && !overlay_open { let mut lines = self.stack_tooltip(&stack); if many { @@ -1059,6 +1146,7 @@ impl Game<'_> { tooltip = Some(lines); } } + self.recipe_ui.button_anim.retain(|e| e.1 > 0.0); // Page arrows and number. if pages > 1 { let page_text = self diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 9d01ff059..90892be56 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1305,7 +1305,13 @@ impl Game<'_> { ); } } - let title = self.translate("container.brewing", "Brewing Stand"); + let default = self.translate("container.brewing", "Brewing Stand"); + let title = self + .station + .as_ref() + .and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2]))) + .cloned() + .unwrap_or(default); let tw = HudBatch::text_width(atlas, &title); batch.text( atlas, diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 865852fc7..cf9a3a1ac 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -11,6 +11,14 @@ impl Game<'_> { /// Block-entity contents on removal: shulker boxes keep theirs for the /// dropped box (`copy_components`), other containers spill them. pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) { + if let Some(name) = self + .world + .block_names + .remove(&(pos[0], pos[1], pos[2])) + .filter(|_| !matches!(entity, BlockEntity::Banner(_))) + { + self.pending_names.insert(pos, (block.to_owned(), name)); + } if let BlockEntity::Banner(banner) = entity { self.pending_banner.insert(pos, banner); return; @@ -41,6 +49,38 @@ impl Game<'_> { stack.data_mut().container = contents; } } + /// The custom name a broken container drops with (`copy_components`). + pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) { + if self + .pending_names + .get(&pos) + .is_some_and(|(item, _)| **item == *stack.item) + && let Some((_, name)) = self.pending_names.remove(&pos) + { + stack.data_mut().custom_name = Some(name); + } + } + /// A placed container takes the item's custom name. + pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) { + let key = (pos[0], pos[1], pos[2]); + if let Some(name) = stack.custom_name() + && !matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Banner(_) | BlockEntity::Sign(_)) + ) + { + self.world.block_names.insert(key, name.to_owned()); + } + } + /// The custom name of the open container, or its default title + /// (a double chest is named by whichever half has a name). + pub(super) fn container_title(&self, default: String) -> String { + self.container_parts() + .iter() + .find_map(|(key, _)| self.world.block_names.get(key)) + .cloned() + .unwrap_or(default) + } /// A placed shulker box takes the item's contents. pub(super) fn fill_placed_box(&mut self, pos: [i32; 3], stack: &ItemStack) { let Some(data) = stack.data() else { return }; @@ -234,7 +274,7 @@ impl Game<'_> { _ if rows > 3 => ("container.chestDouble", "Large Chest"), _ => ("container.chest", "Chest"), }; - self.translate(key, fallback) + self.container_title(self.translate(key, fallback)) } /// `ContainerScreen` / `ShulkerBoxScreen`: the background with its /// container rows, the title and the inventory label. diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 93e011d51..ed1a91c15 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -278,6 +278,14 @@ impl HudBatch { /// Clip the quads drawn since `start` to `[x0, x1) x [y0, y1)` (the /// GUI scissor): axis-aligned quads are cut with their UVs, others are /// kept or dropped by their centre. + /// Scale the vertices pushed since `start` about `(cx, cy)` (a GUI pose + /// matrix of translate, scale, translate back). + pub fn scale_since(&mut self, start: usize, cx: f32, cy: f32, sx: f32, sy: f32) { + for v in &mut self.vertices[start..] { + v.pos[0] = cx + (v.pos[0] - cx) * sx; + v.pos[1] = cy + (v.pos[1] - cy) * sy; + } + } pub fn clip_since(&mut self, start: usize, x0: f32, y0: f32, x1: f32, y1: f32) { let quads: Vec<[HudVertex; 6]> = self.vertices[start..].as_chunks::<6>().0.to_vec(); self.vertices.truncate(start); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 929f205ac..dea18eca2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -438,6 +438,9 @@ pub struct Extra { /// `Mob.canPickUpLoot` (also lets dispensers equip it). pub pick_up_loot: bool, pub saddled: bool, + /// The saddle's components (name, enchantments...) when it is not a bare + /// one; `saddled` stays the gameplay flag. + pub saddle_stack: Option, pub chested: bool, /// The chest contents of a donkey or mule (15 slots). pub items: Vec>, @@ -1136,3 +1139,22 @@ pub fn render_model( } } } + +impl Mob { + /// The saddle worn, with its components. + pub fn saddle_item(&self) -> Option { + self.extra.saddled.then(|| { + self.extra + .saddle_stack + .clone() + .unwrap_or_else(|| crate::items::ItemStack::new("minecraft:saddle", 1)) + }) + } + /// Wear (or take off) a saddle stack, keeping its components. + pub fn set_saddle(&mut self, saddle: Option) { + self.extra.saddled = saddle.is_some(); + self.extra.saddle_stack = saddle + .map(|s| crate::items::ItemStack { count: 1, ..s }) + .filter(|s| s.damage != 0 || s.extra.is_some()); + } +} diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 4aeb50f7c..674882b8b 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -280,7 +280,20 @@ impl Book { ingredients, result, } => (Display::Shapeless(ingredients.clone()), result), - Recipe::Special(_) => continue, + // Custom recipes are never learnable; the others show one + // display per material count (TransmuteRecipe.display). + Recipe::Special(special) => { + for (display, result) in special.book_displays() { + entries.push(Entry { + id: format!("minecraft:{name}"), + category: crafting_category(&category), + group: group(&grp), + display, + result, + }); + } + continue; + } }; entries.push(Entry { id: format!("minecraft:{name}"), @@ -376,24 +389,33 @@ impl Book { items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone())); items } - /// `RecipeCollection` search: the result's name or registry path, or - /// `@namespace`. - pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool { + /// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a + /// `FullTextSearchTree`): without a colon the text must occur in a + /// tooltip line of a result item of the collection; `namespace:path` + /// needs the namespace in a result id and the path in an id or a line. + pub fn collection_matches( + &self, + entries: &[usize], + query: &str, + tooltip: &dyn Fn(&ItemStack) -> Vec, + ) -> bool { let query = query.to_lowercase(); - if let Some(ns) = query.strip_prefix('@') { - return entry - .result - .item - .split(':') - .next() - .is_some_and(|n| n.starts_with(ns)); - } - name.to_lowercase().contains(&query) - || entry - .result - .item - .trim_start_matches("minecraft:") - .contains(&query) + let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect(); + let in_lines = |text: &str| { + results + .iter() + .any(|r| tooltip(r).iter().any(|l| l.to_lowercase().contains(text))) + }; + let Some((namespace, path)) = query.split_once(':') else { + return in_lines(&query); + }; + let (namespace, path) = (namespace.trim(), path.trim()); + let id = |r: &&ItemStack| { + let (ns, p) = r.item.split_once(':').unwrap_or(("minecraft", &r.item)); + (ns.to_lowercase(), p.to_lowercase()) + }; + results.iter().any(|r| id(r).0.contains(namespace)) + && (results.iter().any(|r| id(r).1.contains(path)) || in_lines(path)) } } @@ -524,6 +546,8 @@ pub struct Settings { pub filtering: [bool; 4], /// Unlocked recipe ids (`recipes`). pub recipes: Vec, + /// Recipes not yet shown in the book (`toBeDisplayed`): they animate once. + pub to_be_displayed: Vec, } impl Settings { pub fn read(tag: Option<&Tag>) -> Self { @@ -535,18 +559,21 @@ impl Settings { s.open[b.index()] = flag(open); s.filtering[b.index()] = flag(filter); } - if let Some(Tag::List(list)) = tag.get("recipes") { - s.recipes = list + let ids = |key: &str| match tag.get(key) { + Some(Tag::List(list)) => list .iter() .filter_map(|t| match t { Tag::String(id) => Some(id.to_string_lossy()), _ => None, }) - .collect(); - } + .collect(), + _ => Vec::new(), + }; + s.recipes = ids("recipes"); + s.to_be_displayed = ids("toBeDisplayed"); s } - /// The compound written to the player file; `toBeDisplayed` stays empty. + /// The compound written to the player file. pub fn write(&self) -> Tag { let mut entries: Vec<(&str, Tag)> = Vec::new(); for b in BookType::ALL { @@ -558,7 +585,7 @@ impl Settings { Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect()) }; entries.push(("recipes", list(&self.recipes))); - entries.push(("toBeDisplayed", Tag::List(Vec::new()))); + entries.push(("toBeDisplayed", list(&self.to_be_displayed))); Tag::compound(entries) } } @@ -672,6 +699,25 @@ mod tests { assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1); } #[test] + fn search_reads_tooltip_lines_and_ids() { + let book = Book { + entries: vec![Entry { + id: "minecraft:stick".into(), + category: Category::CraftingMisc, + group: None, + display: Display::Shapeless(Vec::new()), + result: ItemStack::new("minecraft:stick", 4), + }], + order: HashMap::new(), + }; + let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()]; + assert!(book.collection_matches(&[0], "STI", &lines)); + // Plain text searches tooltips only, not the registry path. + assert!(!book.collection_matches(&[0], "stick:", &lines)); + assert!(book.collection_matches(&[0], "minecraft:stic", &lines)); + assert!(!book.collection_matches(&[0], "other:stick", &lines)); + } + #[test] fn settings_round_trip() { let mut s = Settings::default(); s.open[BookType::Furnace.index()] = true; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 7ab494bbf..f81a13cea 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -730,7 +730,15 @@ pub fn encode_with( let mut block_entities: Vec = chunk .block_entities .iter() - .map(|(p, e)| encode_block_entity(*p, e, &block_name(p))) + .map(|(p, e)| { + let mut tag = encode_block_entity(*p, e, &block_name(p)); + if let Some((_, name)) = chunk.block_names.iter().find(|(q, _)| q == p) + && let Tag::Compound(map) = &mut tag + { + map.insert("CustomName".into(), string(name)); + } + tag + }) .collect(); if let Some(extras) = extras { for raw in &extras.block_entities { @@ -940,7 +948,12 @@ pub fn decode_with( if let Some(Tag::List(entities)) = tag.get("block_entities") { for e in entities { match decode_block_entity(e) { - Some(be) => chunk.block_entities.push(be), + Some(be) => { + if let Some(name) = text(e.get("CustomName")) { + chunk.block_names.push((be.0, name)); + } + chunk.block_entities.push(be); + } None => extras.block_entities.push(e.clone()), } } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index c43e82e69..fdaf96332 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -320,6 +320,9 @@ impl Streaming { world .block_entities .extend(std::mem::take(&mut chunk.block_entities)); + world + .block_names + .extend(std::mem::take(&mut chunk.block_names)); let entities = std::mem::take(&mut chunk.entities); if !entities.is_empty() { world.loaded_entities.push(((chunk.x, chunk.z), entities)); diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 657f4635f..fe3d9cc40 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -26,6 +26,8 @@ pub struct World { /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// `BaseContainerBlockEntity.name`: custom names of container block entities. + pub block_names: HashMap<(i32, i32, i32), String>, /// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent /// within spawning range (local difficulty). pub inhabited: HashMap<(i32, i32), i64>, @@ -106,6 +108,7 @@ impl World { loaded_entities: Vec::new(), modified: HashSet::new(), block_entities: HashMap::new(), + block_names: HashMap::new(), inhabited: HashMap::new(), game_time: 0, day_time: 1000, From c9ad9869d9c9387fa7e562e433a06f0b1013282f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:49:56 +0200 Subject: [PATCH 03/16] Start the menu click oracle and tweak the interaction lab Work in progress on the vanilla menu oracle adapter used by the upcoming menu click parity harness. Co-Authored-By: Claude Sonnet 5.5 --- .../horizonlab/parity/VanillaMenuOracle.java | 201 ++++++++++++++++++ tools/interaction_lab.py | 9 +- 2 files changed, 207 insertions(+), 3 deletions(-) create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java new file mode 100644 index 000000000..674ffa00e --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -0,0 +1,201 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeManager; + +/** + * Original oracle: AbstractContainerMenu.clicked over vanilla's real menu + * classes. A stand-in player (inventory, drops recorded) and a stand-in server + * level (real RecipeManager, no networking) run each case's clicks; after + * every click the slots, carried stack, data slots, drops and player state + * are printed as canonical NBT. + */ +public final class VanillaMenuOracle { + static Object unsafe; + static java.lang.reflect.Method allocate; + static RecipeManager recipes; + static final List drops = new ArrayList<>(); + + @SuppressWarnings("unchecked") + static T make(Class type) { + try { + return (T) allocate.invoke(unsafe, type); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + static void set(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + f.set(target, value); + } + + static final class Server extends net.minecraft.server.dedicated.DedicatedServer { + Server() { + super(null, null, null, null, null, null, null, null, null, null); + } + @Override public RecipeManager getRecipeManager() { return recipes; } + } + + static final class Connection extends ServerGamePacketListenerImpl { + Connection() { + super(null, null, null, null); + } + @Override public void send(net.minecraft.network.protocol.Packet packet) { } + } + + static final class World extends ServerLevel { + Server server; + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public net.minecraft.server.MinecraftServer getServer() { return server; } + @Override public RecipeManager recipeAccess() { return recipes; } + @Override public boolean isClientSide() { return false; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; } + @Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; } + @Override public net.minecraft.world.level.gamerules.GameRules getGameRules() { return new net.minecraft.world.level.gamerules.GameRules(FeatureFlags.DEFAULT_FLAGS); } + @Override public void levelEvent(net.minecraft.world.entity.Entity p, int type, BlockPos pos, int data) { } + @Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { } + @Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; } + @Override public void gameEvent(net.minecraft.core.Holder e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + } + + static final class FakePlayer extends ServerPlayer { + World world; + boolean creative; + Inventory inv; + FakePlayer() { + super(null, null, null, null); + } + @Override public Inventory getInventory() { return inv; } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public boolean isSpectator() { return false; } + @Override public EntityType getType() { return net.minecraft.world.entity.EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public boolean canUseSlot(EquipmentSlot slot) { return true; } + @Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { } + @Override public boolean hasDisconnected() { return false; } + @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { + if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); + return null; + } + @Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); } + @Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); } + } + + static AbstractContainerMenu menu(String kind, FakePlayer player, Inventory inv) { + var access = ContainerLevelAccess.create(player.world, BlockPos.ZERO); + if (kind.startsWith("chest")) { + int rows = Integer.parseInt(kind.substring(5)); + MenuType type = new MenuType[]{MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6}[rows - 1]; + return new ChestMenu(type, 0, inv, new SimpleContainer(9 * rows), rows); + } + return switch (kind) { + case "inventory" -> new InventoryMenu(inv, true, player); + case "crafting" -> new CraftingMenu(0, inv, access); + case "hopper" -> new HopperMenu(0, inv); + case "dispenser" -> new DispenserMenu(0, inv); + case "shulker" -> new ShulkerBoxMenu(0, inv); + case "furnace" -> new FurnaceMenu(0, inv); + case "blast_furnace" -> new BlastFurnaceMenu(0, inv); + case "smoker" -> new SmokerMenu(0, inv); + case "brewing" -> new BrewingStandMenu(0, inv); + case "crafter" -> new CrafterMenu(0, inv); + default -> throw new IllegalArgumentException(kind); + }; + } + + static String state(AbstractContainerMenu menu, Inventory inv) throws Exception { + StringBuilder out = new StringBuilder(); + for (int i = 0; i < menu.slots.size(); i++) { + out.append(i > 0 ? " " : "").append(ParityData.canon(menu.getSlot(i).getItem())); + } + out.append(" | ").append(ParityData.canon(menu.getCarried())); + Field dataSlots = AbstractContainerMenu.class.getDeclaredField("dataSlots"); + dataSlots.setAccessible(true); + List data = (List) dataSlots.get(menu); + out.append(" |"); + for (DataSlot d : data) out.append(' ').append(d.get()); + out.append(" | ").append(String.join(";", drops)); + return out.toString(); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + try { + drops.clear(); + var world = make(World.class); + world.server = make(Server.class); + var player = make(FakePlayer.class); + player.world = world; + player.creative = f.get("creative").getAsBoolean(); + set(player, ServerPlayer.class, "connection", make(Connection.class)); + var inv = new Inventory(player, new EntityEquipment()); + player.inv = inv; + AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv); + set(player, Player.class, "inventoryMenu", menu); + var slotsJson = f.getAsJsonArray("slots"); + for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString())); + menu.setCarried(ParityData.stack(f.get("carried").getAsString())); + var dataJson = f.getAsJsonArray("data"); + for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); + drops.clear(); + out.println("init " + state(menu, inv)); + for (var opJson : f.getAsJsonArray("ops")) { + var op = opJson.getAsJsonArray(); + int slot = op.get(0).getAsInt(); + int button = op.get(1).getAsInt(); + var input = ContainerInput.valueOf(op.get(2).getAsString()); + try { + menu.clicked(slot, button, input, player); + } catch (RuntimeException e) { + Throwable cause = e.getCause() != null ? e.getCause() : e; + out.println("error " + cause.getClass().getSimpleName()); + if (System.getenv("MENU_TRACE") != null) cause.printStackTrace(); + continue; + } + out.println(state(menu, inv)); + } + out.println("end"); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py index 19cbd44bd..2c8944f02 100644 --- a/tools/interaction_lab.py +++ b/tools/interaction_lab.py @@ -34,9 +34,12 @@ class Vanilla: def compile(self, *oracles): sources = [PARITY / (name + '.java') for name in oracles] - subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', - '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', - '-cp', self.deps, '-d', str(self.classes), *map(str, sources)], check=True) + done = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', + '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', '-Xmaxerrs', '30', + '-cp', self.deps, '-d', str(self.classes), *map(str, sources)], capture_output=True, text=True) + if done.returncode: + print(done.stderr.replace(str(lab.ROOT) + '/', '')) + raise SystemExit('javac failed') def run(self, oracle, *args, heap='2G'): subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps, From 89630c80fe537829757d447662cee4d3c4ba78a3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:01:09 +0200 Subject: [PATCH 04/16] Port AbstractContainerMenu clicks and test them against vanilla menus A pure menu engine now implements every click type (pickup, quick move, swap, clone, throw, the three quick craft drags, pickup all) for the player inventory, crafting table, chests, hopper, dispenser, shulker box and the furnaces, with armour, fuel, output and crafting result slot rules, the crafting result recompute and remainders, and Inventory.add. The new menu click harness runs thousands of randomized click sequences through vanilla's real menu classes and this engine and compares every slot, the carried stack, data slots and drops. Co-Authored-By: Claude Sonnet 5.5 --- .../horizon-client/examples/menu_fixture.rs | 69 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu.rs | 1186 +++++++++++++++++ .../horizonlab/parity/VanillaMenuOracle.java | 6 +- tools/logs/latest.log | 0 tools/test_menu_click_parity.py | 164 +++ 6 files changed, 1425 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/examples/menu_fixture.rs create mode 100644 crates/horizon-client/src/menu.rs create mode 100644 tools/logs/latest.log create mode 100644 tools/test_menu_click_parity.py diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs new file mode 100644 index 000000000..ded828ef3 --- /dev/null +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -0,0 +1,69 @@ +//! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per +//! line (menu, creative, slots, carried, data, ops) and prints the oracle's +//! state lines after every click. +//! +//! usage: menu_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + crafting::Recipes, + item_data::{canon_stack, parse_stack}, + items::Items, + menu::{Env, Input, Kind, Menu}, +}; +use serde_json::Value; +use std::{fs, path::Path}; + +fn state(menu: &Menu) -> String { + let slots: Vec = (0..menu.slot_count()) + .map(|i| canon_stack(menu.slot(i))) + .collect(); + let data: String = menu.data.iter().map(|d| format!(" {d}")).collect(); + format!( + "{} | {} |{data} | {}", + slots.join(" "), + canon_stack(menu.carried.as_ref()), + menu.drops.join(";") + ) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let env = Env { + items: &items, + recipes: &recipes, + }; + let mut out = String::new(); + for line in input.lines() { + let case: Value = serde_json::from_str(line)?; + let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?; + let mut menu = Menu::new(kind); + menu.creative = case["creative"].as_bool().unwrap_or(false); + for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { + menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); + } + menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { + menu.data[i] = v.as_i64().unwrap_or(0) as i32; + } + menu.drops.clear(); + out += &format!("init {}\n", state(&menu)); + for op in case["ops"].as_array().ok_or("ops")? { + let slot = op[0].as_i64().unwrap_or(0) as i32; + let button = op[1].as_i64().unwrap_or(0) as i32; + let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?; + match menu.click(&env, slot, button, kind) { + Ok(()) => out += &format!("{}\n", state(&menu)), + Err(name) => out += &format!("error {name}\n"), + } + } + out += "end\n"; + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 09c1ecbb0..bb2dd3763 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -46,6 +46,7 @@ pub mod keybinds; pub mod landing; pub mod lang; pub mod light; +pub mod menu; pub mod merchant; pub mod mesher; pub mod mobs; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs new file mode 100644 index 000000000..5190cf16f --- /dev/null +++ b/crates/horizon-client/src/menu.rs @@ -0,0 +1,1186 @@ +//! `AbstractContainerMenu.clicked` over vanilla's slot layouts: every +//! `ContainerInput` (pickup, quick move, swap, clone, throw, the three quick +//! craft drags, pickup all) for the player inventory, the crafting table, the +//! chest family, hoppers, dispensers, shulker boxes and the furnaces. +//! `tools/test_menu_click_parity.py` compares every click with vanilla's menu +//! classes. +use crate::{ + crafting::Recipes, + items::{ItemStack, Items}, +}; + +/// What a menu needs to know about items and recipes. +pub struct Env<'a> { + pub items: &'a Items, + pub recipes: &'a Recipes, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Input { + Pickup, + QuickMove, + Swap, + Clone, + Throw, + QuickCraft, + PickupAll, +} + +impl Input { + pub fn parse(name: &str) -> Option { + Some(match name { + "PICKUP" => Self::Pickup, + "QUICK_MOVE" => Self::QuickMove, + "SWAP" => Self::Swap, + "CLONE" => Self::Clone, + "THROW" => Self::Throw, + "QUICK_CRAFT" => Self::QuickCraft, + "PICKUP_ALL" => Self::PickupAll, + _ => return None, + }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + Inventory, + Crafting, + Chest(usize), + Hopper, + Dispenser, + Shulker, + /// The cooking recipe type: smelting, blasting or smoking. + Furnace(&'static str), +} + +impl Kind { + pub fn parse(name: &str) -> Option { + if let Some(rows) = name.strip_prefix("chest") { + return rows.parse().ok().map(Self::Chest); + } + Some(match name { + "inventory" => Self::Inventory, + "crafting" => Self::Crafting, + "hopper" => Self::Hopper, + "dispenser" => Self::Dispenser, + "shulker" => Self::Shulker, + "furnace" => Self::Furnace("smelting"), + "blast_furnace" => Self::Furnace("blasting"), + "smoker" => Self::Furnace("smoking"), + _ => return None, + }) + } +} + +/// `Slot` subclasses that change the rules. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Role { + Plain, + /// `ArmorSlot` for the equipment slot with this `EquipmentSlot.getIndex`. + Armor(usize), + Shulker, + Fuel, + /// `FurnaceResultSlot`. + Output, + /// `ResultSlot` of a crafting grid. + CraftResult, +} + +#[derive(Clone, Copy)] +struct Slot { + container: usize, + index: usize, + role: Role, +} + +/// The containers a menu spans. +const PLAYER: usize = 0; +const MAIN: usize = 1; +const GRID: usize = 2; +const RESULT: usize = 3; +/// `Container.getMaxStackSize`. +const CONTAINER_MAX: u32 = 99; +const OFFHAND: usize = 40; + +pub struct Menu { + kind: Kind, + slots: Vec, + containers: [Vec>; 4], + grid_size: usize, + pub carried: Option, + pub data: Vec, + pub creative: bool, + /// Dropped stacks (canonical text), `xp+N` and the like, in order. + pub drops: Vec, + quick_status: i32, + quick_type: i32, + quick_slots: Vec, +} + +fn same_item(a: &ItemStack, b: &ItemStack) -> bool { + a.item == b.item +} + +fn split(stack: &mut ItemStack, amount: u32) -> ItemStack { + let real = amount.min(stack.count); + let mut out = stack.clone(); + out.count = real; + stack.count -= real; + out +} + +fn tidy(slot: &mut Option) { + if slot.as_ref().is_some_and(|s| s.count == 0) { + *slot = None; + } +} + +/// An index outside the slot list: vanilla's `IndexOutOfBoundsException`. +pub const OUT_OF_BOUNDS: &str = "IndexOutOfBoundsException"; + +impl Menu { + pub fn new(kind: Kind) -> Self { + let mut containers: [Vec>; 4] = Default::default(); + containers[PLAYER] = vec![None; 41]; + let mut slots = Vec::new(); + let mut grid_size = 0; + let main = |n: usize, role: Role| -> Vec { + (0..n) + .map(|index| Slot { + container: MAIN, + index, + role, + }) + .collect() + }; + let player = |slots: &mut Vec| { + for i in (9..36).chain(0..9) { + slots.push(Slot { + container: PLAYER, + index: i, + role: Role::Plain, + }); + } + }; + let grid = |slots: &mut Vec, n: usize| { + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CraftResult, + }); + for index in 0..n * n { + slots.push(Slot { + container: GRID, + index, + role: Role::Plain, + }); + } + }; + let mut data = 0; + match kind { + Kind::Inventory => { + grid_size = 2; + grid(&mut slots, 2); + for (i, eq) in [3usize, 2, 1, 0].into_iter().enumerate() { + slots.push(Slot { + container: PLAYER, + index: 39 - i, + role: Role::Armor(eq), + }); + } + player(&mut slots); + slots.push(Slot { + container: PLAYER, + index: OFFHAND, + role: Role::Plain, + }); + } + Kind::Crafting => { + grid_size = 3; + grid(&mut slots, 3); + player(&mut slots); + } + Kind::Chest(rows) => { + containers[MAIN] = vec![None; rows * 9]; + slots.extend(main(rows * 9, Role::Plain)); + player(&mut slots); + } + Kind::Hopper => { + containers[MAIN] = vec![None; 5]; + slots.extend(main(5, Role::Plain)); + player(&mut slots); + } + Kind::Dispenser => { + containers[MAIN] = vec![None; 9]; + slots.extend(main(9, Role::Plain)); + player(&mut slots); + } + Kind::Shulker => { + containers[MAIN] = vec![None; 27]; + slots.extend(main(27, Role::Shulker)); + player(&mut slots); + } + Kind::Furnace(_) => { + containers[MAIN] = vec![None; 3]; + slots.extend([ + Slot { + container: MAIN, + index: 0, + role: Role::Plain, + }, + Slot { + container: MAIN, + index: 1, + role: Role::Fuel, + }, + Slot { + container: MAIN, + index: 2, + role: Role::Output, + }, + ]); + player(&mut slots); + data = 4; + } + } + containers[GRID] = vec![None; grid_size * grid_size]; + containers[RESULT] = vec![None; 1]; + Self { + kind, + slots, + containers, + grid_size, + carried: None, + data: vec![0; data], + creative: false, + drops: Vec::new(), + quick_status: 0, + quick_type: 0, + quick_slots: Vec::new(), + } + } + + pub fn slot_count(&self) -> usize { + self.slots.len() + } + + pub fn slot(&self, i: usize) -> Option<&ItemStack> { + let s = self.slots[i]; + self.containers[s.container][s.index].as_ref() + } + + /// Sets a slot as a test fixture does (`Slot.set`). + pub fn set_slot(&mut self, env: &Env, i: usize, stack: Option) { + self.put(env, i, stack); + } + + pub fn player_item(&self, i: usize) -> Option<&ItemStack> { + self.containers[PLAYER][i].as_ref() + } + + // ---- item helpers ---- + + fn max_stack(env: &Env, stack: &ItemStack) -> u32 { + env.items.get(&stack.item).map_or(64, |i| i.max_stack) + } + + fn damageable(env: &Env, stack: &ItemStack) -> bool { + env.items.get(&stack.item).is_some_and(|i| i.max_damage > 0) + } + + /// `ItemStack.isStackable`. + fn stackable(env: &Env, stack: &ItemStack) -> bool { + Self::max_stack(env, stack) > 1 && !(Self::damageable(env, stack) && stack.damage > 0) + } + + fn is_bucket(stack: &ItemStack) -> bool { + &*stack.item == "minecraft:bucket" + } + + fn is_fuel(env: &Env, stack: &ItemStack) -> bool { + env.items.get(&stack.item).is_some_and(|i| i.fuel.is_some()) + } + + /// `Item.canFitInsideContainerItems`: shulker boxes cannot nest. + fn fits_inside(stack: &ItemStack) -> bool { + !(stack.item.ends_with("shulker_box")) + } + + // ---- Slot ---- + + fn may_place(&self, env: &Env, s: usize, stack: &ItemStack) -> bool { + match self.slots[s].role { + Role::Plain => true, + Role::Armor(eq) => env + .items + .get(&stack.item) + .and_then(|i| { + let slot = match i.equip_slot.as_deref()? { + "feet" => 0, + "legs" => 1, + "chest" => 2, + "head" => 3, + _ => return None, + }; + let allowed = i + .equip_allowed + .as_ref() + .is_none_or(|a| a.contains("minecraft:player")); + Some(slot == eq && allowed) + }) + .unwrap_or(false), + Role::Shulker => Self::fits_inside(stack), + Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), + Role::Output | Role::CraftResult => false, + } + } + + fn may_pickup(&self, s: usize) -> bool { + match self.slots[s].role { + Role::Armor(_) => match self.slot(s) { + Some(stack) => { + self.creative || stack.enchantment_level("minecraft:binding_curse") == 0 + } + None => true, + }, + _ => true, + } + } + + /// `Slot.getMaxStackSize(stack)`. + fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { + let own = match self.slots[s].role { + Role::Armor(_) => 1, + Role::Fuel if Self::is_bucket(stack) => return 1, + _ => CONTAINER_MAX, + }; + own.min(Self::max_stack(env, stack)) + } + + /// `Container.setItem` (a grid change recomputes the result). + fn put(&mut self, env: &Env, s: usize, mut stack: Option) { + tidy(&mut stack); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = stack; + if slot.container == GRID { + self.recompute(env); + } + } + + /// `Slot.remove`: the container's `removeItem`. + fn remove(&mut self, env: &Env, s: usize, amount: u32) -> Option { + let slot = self.slots[s]; + if slot.container == RESULT { + return self.containers[RESULT][0].take(); + } + let cell = &mut self.containers[slot.container][slot.index]; + let out = cell + .as_mut() + .filter(|c| c.count > 0) + .map(|c| split(c, amount)); + tidy(cell); + if out.is_some() && slot.container == GRID { + self.recompute(env); + } + out + } + + /// `CraftingMenu.slotChangedCraftingGrid`. + fn recompute(&mut self, env: &Env) { + if self.grid_size == 0 { + return; + } + let result = env + .recipes + .find(&self.containers[GRID], self.grid_size) + .map(|(_, stack)| stack); + self.containers[RESULT][0] = result; + } + + /// `ResultSlot.onTake` and the other `Slot.onTake` overrides. + fn on_take(&mut self, env: &Env, s: usize) { + if self.slots[s].role != Role::CraftResult { + return; + } + let n = self.grid_size; + let grid = self.containers[GRID].clone(); + let remaining = env + .recipes + .find(&grid, n) + .map(|(id, _)| env.recipes.remainders(id, &grid, n)) + .unwrap_or_else(|| { + // CraftingRecipe.defaultCraftingReminder + grid.iter() + .map(|cell| { + cell.as_ref().and_then(|stack| { + env.items + .get(&stack.item) + .and_then(|i| i.crafting_remainder.as_deref()) + .map(|r| ItemStack::new(r, 1)) + }) + }) + .collect() + }); + for cell in 0..n * n { + let mut here = self.containers[GRID][cell].take(); + if let Some(stack) = here.as_mut() { + stack.count -= 1; + } + tidy(&mut here); + self.containers[GRID][cell] = here; + if let Some(replacement) = remaining.get(cell).cloned().flatten() { + match self.containers[GRID][cell].as_mut() { + None => self.containers[GRID][cell] = Some(replacement), + Some(have) if have.same_item_same_components(&replacement) => { + let mut merged = replacement; + merged.count += have.count; + self.containers[GRID][cell] = Some(merged); + } + Some(_) => { + let mut left = replacement; + if !self.inventory_add(env, &mut left) { + self.drop_stack(&left); + } + } + } + } + } + self.recompute(env); + } + + fn drop_stack(&mut self, stack: &ItemStack) { + if stack.count > 0 { + self.drops.push(crate::item_data::canon_stack(Some(stack))); + } + } + + /// `Slot.tryRemove`. + fn try_remove( + &mut self, + env: &Env, + s: usize, + amount: u32, + max_amount: u32, + ) -> Option { + if !self.may_pickup(s) { + return None; + } + if !self.allow_modification(env, s) && max_amount < self.slot(s).map_or(0, |c| c.count) { + return None; + } + let result = self.remove(env, s, amount.min(max_amount))?; + if self.slot(s).is_none() { + self.put(env, s, None); + } + Some(result) + } + + fn allow_modification(&self, env: &Env, s: usize) -> bool { + self.may_pickup(s) + && match self.slot(s) { + Some(stack) => self.may_place(env, s, stack), + None => true, + } + } + + fn safe_take( + &mut self, + env: &Env, + s: usize, + amount: u32, + max_amount: u32, + ) -> Option { + let result = self.try_remove(env, s, amount, max_amount)?; + self.on_take(env, s); + Some(result) + } + + /// `Slot.safeInsert`: puts up to `amount` of `input` into the slot. + fn safe_insert(&mut self, env: &Env, s: usize, input: &mut Option, amount: u32) { + let Some(stack) = input.as_mut() else { return }; + if !self.may_place(env, s, stack) { + return; + } + let have = self.slot(s).map_or(0, |c| c.count); + let max = self.slot_max(env, s, stack); + let transferable = amount.min(stack.count).min(max.saturating_sub(have)); + if transferable == 0 { + return; + } + match self.slot(s).cloned() { + None => { + let part = split(stack, transferable); + self.put(env, s, Some(part)); + } + Some(mut current) if current.same_item_same_components(stack) => { + stack.count -= transferable; + current.count += transferable; + self.put(env, s, Some(current)); + } + Some(_) => {} + } + tidy(input); + } + + // ---- Inventory ---- + + /// `Inventory.getSlotWithRemainingSpace` (selected slot 0, offhand, rest). + fn slot_with_space(&self, env: &Env, stack: &ItemStack) -> Option { + let inv = &self.containers[PLAYER]; + [0, OFFHAND].into_iter().chain(0..36).find(|&i| { + inv[i].as_ref().is_some_and(|have| { + have.same_item_same_components(stack) + && Self::stackable(env, have) + && have.count < CONTAINER_MAX.min(Self::max_stack(env, have)) + }) + }) + } + + /// `Inventory.addResource`: returns what did not fit. + fn add_resource(&mut self, env: &Env, stack: &ItemStack) -> u32 { + let slot = self.slot_with_space(env, stack).or_else(|| { + self.containers[PLAYER][..36] + .iter() + .position(Option::is_none) + }); + let Some(slot) = slot else { return stack.count }; + let cell = self.containers[PLAYER][slot].get_or_insert_with(|| { + let mut empty = stack.clone(); + empty.count = 0; + empty + }); + let room = CONTAINER_MAX.min(Self::max_stack(env, cell)) - cell.count; + let add = stack.count.min(room); + cell.count += add; + tidy(&mut self.containers[PLAYER][slot]); + stack.count - add + } + + /// `Inventory.add(stack)`: the leftover stays in `stack`. + fn inventory_add(&mut self, env: &Env, stack: &mut ItemStack) -> bool { + if stack.count == 0 { + return false; + } + if Self::damageable(env, stack) && stack.damage > 0 { + if let Some(slot) = self.containers[PLAYER][..36] + .iter() + .position(Option::is_none) + { + self.containers[PLAYER][slot] = Some(stack.clone()); + stack.count = 0; + return true; + } + if self.creative { + stack.count = 0; + return true; + } + return false; + } + loop { + let last = stack.count; + stack.count = self.add_resource(env, stack); + if stack.count == 0 || stack.count >= last { + if stack.count == last && self.creative { + stack.count = 0; + return true; + } + return stack.count < last; + } + } + } +} + +/// `EquipmentSlot` of an item as the inventory menu's quick move sees it. +enum Equip { + Armor(usize), + Offhand, + Other, +} + +impl Menu { + fn equip(env: &Env, stack: &ItemStack) -> Equip { + match env + .items + .get(&stack.item) + .and_then(|i| i.equip_slot.as_deref()) + { + Some("feet") => Equip::Armor(0), + Some("legs") => Equip::Armor(1), + Some("chest") => Equip::Armor(2), + Some("head") => Equip::Armor(3), + Some("offhand") => Equip::Offhand, + _ => Equip::Other, + } + } + + fn has_item(&self, s: usize) -> bool { + self.slot(s).is_some() + } + + /// `AbstractContainerMenu.moveItemStackTo`. + fn move_to( + &mut self, + env: &Env, + stack: &mut ItemStack, + start: usize, + end: usize, + backwards: bool, + ) -> bool { + let mut changed = false; + let order = |_: ()| -> Vec { + if backwards { + (start..end).rev().collect() + } else { + (start..end).collect() + } + }; + if Self::stackable(env, stack) { + for dest in order(()) { + if stack.count == 0 { + break; + } + let max = match self.slot(dest) { + Some(target) if target.same_item_same_components(stack) => { + self.slot_max(env, dest, target) + } + _ => continue, + }; + let slot = self.slots[dest]; + let target = self.containers[slot.container][slot.index] + .as_mut() + .expect("checked"); + let total = target.count + stack.count; + if total <= max { + stack.count = 0; + target.count = total; + changed = true; + } else if target.count < max { + stack.count -= max - target.count; + target.count = max; + changed = true; + } + } + } + if stack.count > 0 { + for dest in order(()) { + if !self.has_item(dest) && self.may_place(env, dest, stack) { + let max = self.slot_max(env, dest, stack); + let part = split(stack, stack.count.min(max)); + self.put(env, dest, Some(part)); + changed = true; + break; + } + } + } + changed + } + + /// `quickMoveStack` of the menu's kind; the moved stack's original copy + /// (None when nothing moved). + fn quick_move(&mut self, env: &Env, index: usize) -> Option { + let mut stack = self.slot(index)?.clone(); + let clicked = stack.clone(); + let total = self.slots.len(); + let mut check_count = true; + let mut after_take = false; + match self.kind { + Kind::Chest(rows) => { + check_count = false; + let n = rows * 9; + if index < n { + if !self.move_to(env, &mut stack, n, total, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, n, false) { + return None; + } + } + Kind::Hopper => { + check_count = false; + if index < 5 { + if !self.move_to(env, &mut stack, 5, 41, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 5, false) { + return None; + } + } + Kind::Shulker => { + check_count = false; + if index < 27 { + if !self.move_to(env, &mut stack, 27, total, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 27, false) { + return None; + } + } + Kind::Dispenser => { + after_take = true; + if index < 9 { + if !self.move_to(env, &mut stack, 9, 45, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 9, false) { + return None; + } + } + Kind::Furnace(recipe) => { + after_take = true; + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index != 1 && index != 0 { + let smelts = env + .recipes + .cook(&format!("minecraft:{recipe}"), &stack) + .is_some(); + if smelts { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if Self::is_fuel(env, &stack) { + if !self.move_to(env, &mut stack, 1, 2, false) { + return None; + } + } else if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } + Kind::Crafting => { + after_take = true; + if index == 0 { + if !self.move_to(env, &mut stack, 10, 46, true) { + return None; + } + } else if (10..46).contains(&index) { + if !self.move_to(env, &mut stack, 1, 10, false) { + if index < 37 { + if !self.move_to(env, &mut stack, 37, 46, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 10, 37, false) { + return None; + } + } + } else if !self.move_to(env, &mut stack, 10, 46, false) { + return None; + } + } + Kind::Inventory => { + after_take = true; + let equip = Self::equip(env, &clicked); + let armor_free = |m: &Self, eq: usize| !m.has_item(8 - eq); + if index == 0 { + if !self.move_to(env, &mut stack, 9, 45, true) { + return None; + } + } else if (1..9).contains(&index) { + if !self.move_to(env, &mut stack, 9, 45, false) { + return None; + } + } else if matches!(equip, Equip::Armor(eq) if armor_free(self, eq)) { + let Equip::Armor(eq) = equip else { + unreachable!() + }; + let pos = 8 - eq; + if !self.move_to(env, &mut stack, pos, pos + 1, false) { + return None; + } + } else if matches!(equip, Equip::Offhand) && !self.has_item(45) { + if !self.move_to(env, &mut stack, 45, 46, false) { + return None; + } + } else if (9..36).contains(&index) { + if !self.move_to(env, &mut stack, 36, 45, false) { + return None; + } + } else if (36..45).contains(&index) { + if !self.move_to(env, &mut stack, 9, 36, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 9, 45, false) { + return None; + } + } + } + // The stack was edited in place in its slot. + let slot = self.slots[index]; + if stack.count == 0 { + self.put(env, index, None); + } else { + self.containers[slot.container][slot.index] = Some(stack.clone()); + } + if check_count && stack.count == clicked.count { + return None; + } + 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) { + self.drop_stack(&stack); + } + Some(clicked) + } + + fn quick_replace(&self, s: usize, stack: &ItemStack, env: &Env) -> bool { + match self.slot(s) { + None => true, + Some(have) if have.same_item_same_components(stack) => { + have.count <= Self::max_stack(env, stack) + } + Some(_) => false, + } + } + + fn reset_quick_craft(&mut self) { + self.quick_status = 0; + self.quick_slots.clear(); + } + + /// `AbstractContainerMenu.clicked`: Err carries a vanilla exception name. + pub fn click( + &mut self, + env: &Env, + slot_index: i32, + button: i32, + input: Input, + ) -> Result<(), &'static str> { + let size = self.slots.len() as i32; + let in_range = |i: i32| (0..size).contains(&i); + if input == Input::QuickCraft { + let expected = self.quick_status; + self.quick_status = button & 3; + if (expected != 1 || self.quick_status != 2) && expected != self.quick_status { + self.reset_quick_craft(); + } else if self.carried.is_none() { + self.reset_quick_craft(); + } else if self.quick_status == 0 { + self.quick_type = (button >> 2) & 3; + if self.quick_type == 0 + || self.quick_type == 1 + || (self.quick_type == 2 && self.creative) + { + self.quick_status = 1; + self.quick_slots.clear(); + } else { + self.reset_quick_craft(); + } + } else if self.quick_status == 1 { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + let s = slot_index as usize; + let carried = self.carried.clone().expect("checked"); + if self.quick_replace(s, &carried, env) + && self.may_place(env, s, &carried) + && (self.quick_type == 2 || carried.count as usize > self.quick_slots.len()) + && !self.quick_slots.contains(&s) + { + self.quick_slots.push(s); + } + } else if self.quick_status == 2 { + if !self.quick_slots.is_empty() { + if self.quick_slots.len() == 1 { + let s = self.quick_slots[0] as i32; + let ty = self.quick_type; + self.reset_quick_craft(); + return self.click(env, s, ty, Input::Pickup); + } + let mut source = self.carried.clone().expect("checked"); + let mut remaining = source.count as i64; + let carried = self.carried.clone().expect("checked"); + for s in self.quick_slots.clone() { + if self.quick_replace(s, &carried, env) + && self.may_place(env, s, &carried) + && (self.quick_type == 2 + || carried.count as usize >= self.quick_slots.len()) + { + let have = self.slot(s).map_or(0, |c| c.count); + let max = + Self::max_stack(env, &source).min(self.slot_max(env, s, &source)); + let each = match self.quick_type { + 0 => (source.count as f32 / self.quick_slots.len() as f32).floor() + as u32, + 1 => 1, + 2 => Self::max_stack(env, &source), + _ => source.count, + }; + let new_count = (each + have).min(max); + remaining -= i64::from(new_count) - i64::from(have); + let mut placed = source.clone(); + placed.count = new_count; + self.put(env, s, Some(placed)); + } + } + source.count = remaining.max(0) as u32; + self.carried = Some(source); + tidy(&mut self.carried); + } + self.reset_quick_craft(); + } else { + self.reset_quick_craft(); + } + return Ok(()); + } + if self.quick_status != 0 { + self.reset_quick_craft(); + return Ok(()); + } + if matches!(input, Input::Pickup | Input::QuickMove) && (button == 0 || button == 1) { + let primary = button == 0; + if slot_index == -999 { + if let Some(carried) = self.carried.as_mut() { + if primary { + let dropped = self.carried.take().expect("some"); + self.drop_stack(&dropped); + } else { + let one = split(carried, 1); + self.drop_stack(&one); + tidy(&mut self.carried); + } + } + } else if input == Input::QuickMove { + if slot_index < 0 { + return Ok(()); + } + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + let s = slot_index as usize; + if !self.may_pickup(s) { + return Ok(()); + } + let mut clicked = self.quick_move(env, s); + while let Some(c) = &clicked { + if !self.slot(s).is_some_and(|now| same_item(now, c)) { + break; + } + clicked = self.quick_move(env, s); + } + } else { + if slot_index < 0 { + return Ok(()); + } + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + self.pickup(env, slot_index as usize, primary); + } + } else if input == Input::Swap && ((0..9).contains(&button) || button == 40) { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + self.swap(env, slot_index as usize, button as usize); + } else if input == Input::Clone + && self.creative + && self.carried.is_none() + && slot_index >= 0 + { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + if let Some(stack) = self.slot(slot_index as usize) { + let mut copy = stack.clone(); + copy.count = Self::max_stack(env, stack); + self.carried = Some(copy); + } + } else if input == Input::Throw && self.carried.is_none() && slot_index >= 0 { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + let s = slot_index as usize; + let amount = if button == 0 { + 1 + } else { + self.slot(s).map_or(0, |c| c.count) + }; + let mut taken = self.safe_take(env, s, amount, u32::MAX); + if let Some(t) = &taken { + self.drop_stack(t); + } + if button == 1 { + while let Some(t) = &taken { + if !self.slot(s).is_some_and(|now| same_item(now, t)) { + break; + } + taken = self.safe_take(env, s, amount, u32::MAX); + if let Some(t) = &taken { + self.drop_stack(t); + } + } + } + } else if input == Input::PickupAll && slot_index >= 0 { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + self.pickup_all(env, slot_index as usize, button); + } + Ok(()) + } + + /// The PICKUP branch of `doClick` (without the bundle overrides). + fn pickup(&mut self, env: &Env, s: usize, primary: bool) { + let clicked = self.slot(s).cloned(); + match clicked { + None => { + if let Some(mut carried) = self.carried.take() { + let amount = if primary { carried.count } else { 1 }; + let mut input = Some(carried.clone()); + self.safe_insert(env, s, &mut input, amount); + carried = input.unwrap_or_else(|| { + let mut e = carried.clone(); + e.count = 0; + e + }); + self.carried = Some(carried); + tidy(&mut self.carried); + } + } + Some(clicked) if self.may_pickup(s) => match self.carried.take() { + None => { + let amount = if primary { + clicked.count + } else { + (clicked.count + 1) / 2 + }; + if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { + self.carried = Some(taken); + self.on_take(env, s); + } + } + Some(mut carried) => { + if self.may_place(env, s, &carried) { + if clicked.same_item_same_components(&carried) { + let amount = if primary { carried.count } else { 1 }; + let mut input = Some(carried.clone()); + self.safe_insert(env, s, &mut input, amount); + carried = input.unwrap_or_else(|| { + let mut e = carried.clone(); + e.count = 0; + e + }); + self.carried = Some(carried); + tidy(&mut self.carried); + } else if carried.count <= self.slot_max(env, s, &carried) { + self.carried = Some(clicked); + self.put(env, s, Some(carried)); + } else { + self.carried = Some(carried); + } + } else if clicked.same_item_same_components(&carried) { + let room = Self::max_stack(env, &carried).saturating_sub(carried.count); + self.carried = Some(carried.clone()); + if let Some(taken) = self.try_remove(env, s, clicked.count, room) { + if let Some(c) = self.carried.as_mut() { + c.count += taken.count; + } + self.on_take(env, s); + } + } else { + self.carried = Some(carried); + } + } + }, + Some(_) => {} + } + } + + /// The SWAP branch of `doClick`. + fn swap(&mut self, env: &Env, target: usize, button: usize) { + let inv_slot = button; + let source = self.containers[PLAYER][inv_slot].clone(); + let target_stack = self.slot(target).cloned(); + if source.is_none() && target_stack.is_none() { + return; + } + match (source, target_stack) { + (None, Some(taken)) => { + if self.may_pickup(target) { + self.containers[PLAYER][inv_slot] = Some(taken.clone()); + self.put(env, target, None); + self.on_take(env, target); + } + } + (Some(mut source), None) => { + if self.may_place(env, target, &source) { + let max = self.slot_max(env, target, &source); + if source.count > max { + let part = split(&mut source, max); + self.containers[PLAYER][inv_slot] = Some(source); + self.put(env, target, Some(part)); + } else { + self.containers[PLAYER][inv_slot] = None; + self.put(env, target, Some(source)); + } + } + } + (Some(mut source), Some(mut taken)) => { + if self.may_pickup(target) && self.may_place(env, target, &source) { + let max = self.slot_max(env, target, &source); + if source.count > max { + let part = split(&mut source, max); + self.containers[PLAYER][inv_slot] = Some(source); + self.put(env, target, Some(part)); + self.on_take(env, target); + if !self.inventory_add(env, &mut taken) { + self.drop_stack(&taken); + } + } else { + self.containers[PLAYER][inv_slot] = Some(taken); + self.put(env, target, Some(source)); + self.on_take(env, target); + } + } + } + (None, None) => {} + } + } + + /// The PICKUP_ALL branch (double click). + fn pickup_all(&mut self, env: &Env, s: usize, button: i32) { + let Some(carried) = self.carried.clone() else { + return; + }; + if self.has_item(s) && self.may_pickup(s) { + return; + } + let total = self.slots.len() as i32; + let (start, step) = if button == 0 { (0, 1) } else { (total - 1, -1) }; + let carried_max = Self::max_stack(env, &carried); + for pass in 0..2 { + let mut i = start; + while i >= 0 && i < total && self.carried.as_ref().map_or(0, |c| c.count) < carried_max + { + let t = i as usize; + i += step; + let have = self.carried.clone().expect("some"); + if self.has_item(t) + && self.quick_replace(t, &have, env) + && self.may_pickup(t) + && self.slots[t].container != RESULT + { + let item = self.slot(t).expect("has item").clone(); + if pass != 0 || item.count != Self::max_stack(env, &item) { + let room = carried_max - have.count; + if let Some(removed) = self.safe_take(env, t, item.count, room) { + if let Some(c) = self.carried.as_mut() { + c.count += removed.count; + } + } + } + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 674ffa00e..a505cb0bc 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -103,6 +103,9 @@ public final class VanillaMenuOracle { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); return null; } + @Override public void triggerRecipeCrafted(net.minecraft.world.item.crafting.RecipeHolder recipe, java.util.List items) { } + @Override public int awardRecipes(java.util.Collection> recipes) { return 0; } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { } @Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); } @Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); } } @@ -167,7 +170,8 @@ public final class VanillaMenuOracle { var inv = new Inventory(player, new EntityEquipment()); player.inv = inv; AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv); - set(player, Player.class, "inventoryMenu", menu); + set(player, Player.class, "containerMenu", menu); + if (menu instanceof InventoryMenu im) set(player, Player.class, "inventoryMenu", im); var slotsJson = f.getAsJsonArray("slots"); for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString())); menu.setCarried(ParityData.stack(f.get("carried").getAsString())); diff --git a/tools/logs/latest.log b/tools/logs/latest.log new file mode 100644 index 000000000..e69de29bb diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py new file mode 100644 index 000000000..cd015e703 --- /dev/null +++ b/tools/test_menu_click_parity.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Compare AbstractContainerMenu.clicked with vanilla's menu classes. + +The Java oracle (VanillaMenuOracle) runs each case's clicks on the real menu +class with a stand-in player and level; the Rust example (menu_fixture) runs +horizon_client::menu. Cases are randomized slot contents with random click +sequences covering every ContainerInput (pickup, quick move, swap, clone, +throw, the three quick craft drags, pickup all) over the player inventory, +crafting table, chests, hopper, dispenser, shulker box and the furnaces. After +every click the slots, carried stack, data slots and drops are compared. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +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} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4} +COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', + 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', + 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', + 'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box', + 'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling', + 'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest'] + + +def quote(text): + return '"' + text + '"' + + +def snbt(item, count, damage=0, curse=False): + comps = [] + if damage: + comps.append('"minecraft:damage":%d' % damage) + if curse: + comps.append('"minecraft:enchantments":{"minecraft:binding_curse":1}') + body = ',components:{%s}' % ','.join(comps) if comps else '' + return '{id:%s,count:%d%s}' % (quote(item), count, body) + + +class Gen: + def __init__(self, rng, items): + self.rng = rng + self.items = items + self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items] + self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k + and not k.endswith('_spawn_egg')] + + def stack(self): + rng = self.rng + item = rng.choice(self.pool if rng.random() < 0.85 else self.all) + info = self.items[item] + top = info.get('minecraft:max_stack_size', 64) + damage = 0 + if info.get('minecraft:max_damage') and rng.random() < 0.3: + damage = rng.randrange(1, info['minecraft:max_damage']) + count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) + return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info)) + + def slots(self, size, density): + return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] + + def recipe(self, slots, width): + """Fills the crafting grid (slots 1..) with a small known recipe.""" + rng = self.rng + amount = lambda: rng.choice([1, 1, 2, 5, 64]) + choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')], + [('iron_ingot',) * 3] * 3, [('milk_bucket',) * 3, ('sugar', 'egg', 'sugar'), ('wheat',) * 3], + [('wheat',) * 3], [('white_wool',) * 2, ('white_wool',) * 2], [('coal',), ('stick',)]] + pattern = rng.choice(choices) + if len(pattern) > width or any(len(row) > width for row in pattern): + pattern = [('oak_planks',), ('oak_planks',)] + for y, row in enumerate(pattern): + for x, name in enumerate(row): + slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1) + + def ops(self, size): + rng = self.rng + out = [] + for _ in range(rng.randrange(1, 9)): + kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'], + [30, 20, 8, 3, 6, 14, 6, 2])[0] + slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size) + if kind == 'PICKUP': + out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind]) + elif kind == 'QUICK_MOVE': + out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind]) + elif kind == 'SWAP': + out.append([slot, rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 40, 9, -1]), kind]) + elif kind in ('CLONE', 'THROW', 'PICKUP_ALL'): + out.append([slot, rng.randrange(0, 2), kind]) + elif kind == 'DRAG': + ty = rng.randrange(0, 4) + out.append([-999, 0 | ty << 2, 'QUICK_CRAFT']) + for _ in range(rng.randrange(0, 6)): + out.append([rng.randrange(size), 1 | ty << 2, 'QUICK_CRAFT']) + out.append([-999, 2 | ty << 2, 'QUICK_CRAFT']) + else: + out.append([rng.choice([slot, 999, -5]), rng.randrange(-1, 5), rng.choice( + ['PICKUP', 'QUICK_MOVE', 'QUICK_CRAFT', 'SWAP', 'THROW', 'PICKUP_ALL'])]) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--cases', type=int, default=6000) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + work = lib.work_dir('menu-click-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaMenuOracle') + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + rng = random.Random(args.seed) + g = Gen(rng, items) + cases = [] + for n in range(args.cases): + menu = list(MENUS)[n % len(MENUS)] + size = MENUS[menu] + slots = g.slots(size, rng.choice([0.1, 0.4, 0.8])) + if menu in ('inventory', 'crafting'): + slots[0] = '-' + if menu in ('inventory', 'crafting') and rng.random() < 0.6: + g.recipe(slots, 2 if menu == 'inventory' else 3) + cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, + 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [0] * DATA.get(menu, 0), + 'ops': g.ops(size)}) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt') + lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + native = (work / 'native.txt').read_text().split('\n') + rust = (work / 'rust.txt').read_text().split('\n') + + def by_case(lines): + out, cur = [], [] + for line in lines: + cur.append(line) + if line == 'end' or line.startswith('error-case'): + out.append(cur) + cur = [] + return out + native, rust = by_case(native), by_case(rust) + bad = {} + for case, a, b in zip(cases, native, rust): + if a != b: + step = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else 0 + op = case['ops'][step - 1] if 0 < step <= len(case['ops']) else None + bad.setdefault((case['menu'], op[2] if op else 'init'), []).append((case, step, a, b)) + total = sum(len(v) for v in bad.values()) + for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])): + print(f'{key}: {len(entries)} differing') + for case, step, a, b in entries[:args.limit]: + print(f' ops {case["ops"][:step]}\n start {a[0]}\n native {a[step]}\n rust {b[step]}') + print(f'{len(cases) - total}/{len(cases)} cases match') + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From d900b2a8e6bca73e018f62730ed45309dda1b265 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:08:27 +0200 Subject: [PATCH 05/16] Read the axe, hoe and shovel block transformers from the data pack A new block transformer module evaluates the data pack's rule based state providers the way BlockTransformer.transformBlock does (matching blocks and tags, all-of, copy properties) and derives the waxed twin of a copper block from the wax-off transforms. A harness compares every transformer, block state, face and block above with vanilla's own providers and with HoneycombItem.getWaxed. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/block_transform_fixture.rs | 94 +++++++ crates/horizon-client/src/block_transform.rs | 259 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + .../parity/VanillaBlockTransformerOracle.java | 118 ++++++++ tools/test_block_transformer_parity.py | 60 ++++ 5 files changed, 532 insertions(+) create mode 100644 crates/horizon-client/examples/block_transform_fixture.rs create mode 100644 crates/horizon-client/src/block_transform.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java create mode 100644 tools/test_block_transformer_parity.py diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/block_transform_fixture.rs new file mode 100644 index 000000000..686ad8c42 --- /dev/null +++ b/crates/horizon-client/examples/block_transform_fixture.rs @@ -0,0 +1,94 @@ +//! Block transformer lookups for tools/test_block_transformer_parity.py: reads +//! "transformer TAB face TAB clicked TAB above" lines (states as +//! "name|prop=value,...") and prints the oracle's result lines. +//! +//! usage: block_transform_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + assets::Assets, + block_transform::{Around, Transformers}, + items::Items, +}; +use horizon_world::chunk::BlockState; +use std::{fs, path::Path}; + +fn parse(text: &str) -> BlockState { + let (name, props) = text.split_once('|').unwrap_or((text, "")); + BlockState { + name: name.to_owned(), + properties: props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(), + } +} + +fn describe(state: &BlockState) -> String { + let props: Vec = state + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}|{}", state.name, props.join(",")) +} + +struct Column { + clicked: BlockState, + above: BlockState, +} + +impl Around for Column { + fn state(&self, offset: [i32; 3]) -> BlockState { + match offset { + [0, 0, 0] => self.clicked.clone(), + [0, 1, 0] => self.above.clone(), + _ => BlockState { + name: "minecraft:stone".into(), + properties: Default::default(), + }, + } + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(args.get(1).ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let assets = Assets::load(root)?; + let transformers = Transformers::load(root, assets.registry)?; + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split('\t').collect(); + let around = Column { + clicked: parse(f[2]), + above: parse(f[3]), + }; + if f[0] == "honeycomb" { + let waxed = transformers.waxed(assets.registry, &around.clicked); + out += &format!("{}\n", waxed.map_or("none".to_owned(), |s| describe(&s))); + continue; + } + let id = format!("minecraft:{}", f[0]); + match transformers.apply(&items, assets.registry, &id, f[1], &around) { + None => out += "none\n", + Some((index, t, state)) => { + out += &format!( + "{index}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", + describe(&state), + t.sound, + t.particle, + t.loot.as_deref().unwrap_or("-"), + t.drop_strategy, + t.update_from_neighbors, + t.transform_type, + t.consume_on_use, + t.damage + ); + } + } + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/block_transform.rs b/crates/horizon-client/src/block_transform.rs new file mode 100644 index 000000000..fb94c2532 --- /dev/null +++ b/crates/horizon-client/src/block_transform.rs @@ -0,0 +1,259 @@ +//! The `minecraft:block_transformer` registry (axe, hoe, shovel) that +//! `BlockTransformer.transformBlock` reads: each transform's rule based state +//! provider is evaluated against the clicked block and the block above. +//! `tools/test_block_transformer_parity.py` compares every block state with +//! vanilla. +use crate::{Result, items::Items}; +use horizon_world::{chunk::BlockState, registry::BlockRegistry}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +enum Predicate { + Blocks(Vec), + Tag { tag: String, offset: [i32; 3] }, + AllOf(Vec), + AnyOf(Vec), +} + +enum Provider { + Rules(Vec<(Predicate, Provider)>), + State(BlockState), + /// `CopyPropertiesProvider`: the source with the clicked block's properties. + Copy(Box), +} + +/// One `BlockTransformData`. +pub struct Transform { + provider: Provider, + pub disallowed_faces: Vec, + pub sound: String, + pub particle: String, + pub loot: Option, + pub drop_strategy: String, + pub update_from_neighbors: bool, + pub transform_type: String, + pub consume_on_use: bool, + pub damage: u32, +} + +pub struct Transformers { + transformers: HashMap>, +} + +/// What the transformer reads of the world: the block state at an offset from +/// the clicked position. +pub trait Around { + fn state(&self, offset: [i32; 3]) -> BlockState; +} + +fn state_of(value: &Value, registry: &BlockRegistry) -> Option { + let name = value["id"].as_str().or_else(|| value["Name"].as_str())?; + let default = registry.default_state(name)?; + let mut state = registry.state(default)?.clone(); + for (k, v) in value["properties"].as_object().into_iter().flatten() { + state.properties.insert(k.clone(), v.as_str()?.to_owned()); + } + Some(state) +} + +fn predicate(value: &Value) -> Option { + Some(match value["type"].as_str()? { + "minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|b| b.as_str().map(str::to_owned)).collect(), + _ => return None, + }), + "minecraft:matching_block_tag" => { + let o = value["offset"].as_array(); + let at = |i: usize| o.and_then(|o| o.get(i)).and_then(Value::as_i64).unwrap_or(0) as i32; + Predicate::Tag { + tag: value["tag"].as_str()?.to_owned(), + offset: [at(0), at(1), at(2)], + } + } + "minecraft:all_of" => Predicate::AllOf( + value["predicates"] + .as_array()? + .iter() + .map(predicate) + .collect::>()?, + ), + "minecraft:any_of" => Predicate::AnyOf( + value["predicates"] + .as_array()? + .iter() + .map(predicate) + .collect::>()?, + ), + _ => return None, + }) +} + +fn provider(value: &Value, registry: &BlockRegistry) -> Option { + match value["type"].as_str() { + Some("minecraft:rule_based") => { + let mut rules = Vec::new(); + for rule in value["rules"].as_array()? { + rules.push((predicate(&rule["if_true"])?, provider(&rule["then"], registry)?)); + } + Some(Provider::Rules(rules)) + } + Some("minecraft:copy_properties") => Some(Provider::Copy(Box::new(provider( + &value["source"], + registry, + )?))), + _ => state_of(value, registry).map(Provider::State), + } +} + +/// `BlockState.withPropertiesOf`: the properties both blocks have. +fn with_properties_of( + registry: &BlockRegistry, + mut state: BlockState, + old: &BlockState, +) -> Option { + let defaults = registry + .default_state(&state.name) + .and_then(|id| registry.state(id))?; + for (k, v) in &old.properties { + if defaults.properties.contains_key(k) { + let mut candidate = state.clone(); + candidate.properties.insert(k.clone(), v.clone()); + if registry.resolve(&candidate).is_ok() { + state = candidate; + } + } + } + Some(state) +} + +impl Predicate { + fn test(&self, items: &Items, around: &dyn Around) -> bool { + match self { + Self::Blocks(names) => { + let state = around.state([0, 0, 0]); + names.iter().any(|n| *n == state.name) + } + Self::Tag { tag, offset } => { + let state = around.state(*offset); + items + .block_tags + .get(tag) + .is_some_and(|members| members.contains(&state.name)) + } + Self::AllOf(all) => all.iter().all(|p| p.test(items, around)), + Self::AnyOf(any) => any.iter().any(|p| p.test(items, around)), + } + } +} + +impl Provider { + fn state( + &self, + items: &Items, + registry: &BlockRegistry, + around: &dyn Around, + ) -> Option { + match self { + Self::Rules(rules) => rules + .iter() + .find(|(p, _)| p.test(items, around)) + .and_then(|(_, then)| then.state(items, registry, around)), + Self::State(state) => Some(state.clone()), + Self::Copy(source) => { + let state = source.state(items, registry, around)?; + with_properties_of(registry, state, &around.state([0, 0, 0])) + } + } + } +} + +impl Transformers { + /// Reads `data/minecraft/block_transformer/*.json`. + pub fn load(root: &Path, registry: &BlockRegistry) -> Result { + let mut transformers = HashMap::new(); + let dir = root.join("data/minecraft/block_transformer"); + if dir.exists() { + for entry in fs::read_dir(&dir)?.flatten() { + let path = entry.path(); + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let list: Value = serde_json::from_slice(&fs::read(&path)?)?; + let mut transforms = Vec::new(); + for t in list.as_array().into_iter().flatten() { + let text = |k: &str, d: &str| t[k].as_str().unwrap_or(d).to_owned(); + let Some(provider) = provider(&t["block_state_provider"], registry) else { + continue; + }; + transforms.push(Transform { + provider, + disallowed_faces: t["disallowed_faces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f.as_str().map(str::to_owned)) + .collect(), + sound: text("sound", "minecraft:empty"), + particle: text("particle", "none"), + loot: t["loot"].as_str().map(str::to_owned), + drop_strategy: text("drop_strategy", "from_middle"), + update_from_neighbors: t["update_from_neighbors"].as_bool().unwrap_or(true), + transform_type: text("transform_type", "single_block"), + consume_on_use: t["consume_on_use"].as_bool().unwrap_or(true), + damage: t["item_damage_per_use"].as_u64().unwrap_or(0) as u32, + }); + } + transformers.insert(format!("minecraft:{stem}"), transforms); + } + } + Ok(Self { transformers }) + } + + /// `BlockTransformer.transformBlock` without the world writes: the first + /// transform that allows the clicked face and provides a state, with its + /// index. + pub fn apply<'a>( + &'a self, + items: &Items, + registry: &BlockRegistry, + id: &str, + face: &str, + around: &dyn Around, + ) -> Option<(usize, &'a Transform, BlockState)> { + self.transformers + .get(id)? + .iter() + .enumerate() + .filter(|(_, t)| !t.disallowed_faces.iter().any(|f| f == face)) + .find_map(|(i, t)| Some((i, t, t.provider.state(items, registry, around)?))) + } + + /// `HoneycombItem.getWaxed`: the waxed twin of a copper block, found from + /// the axe's wax-off transforms (`WAX_OFF_BY_BLOCK` is the inverse of + /// `WAXABLES`). + pub fn waxed(&self, registry: &BlockRegistry, old: &BlockState) -> Option { + for transform in self.transformers.get("minecraft:axe")? { + if transform.particle != "wax_off" { + continue; + } + let Provider::Rules(rules) = &transform.provider else { + continue; + }; + for (predicate, then) in rules { + if let (Predicate::Blocks(names), Provider::Copy(source)) = (predicate, then) + && let Provider::State(unwaxed) = &**source + && unwaxed.name == old.name + && let Some(waxed) = names.first() + { + let target = registry + .default_state(waxed) + .and_then(|id| registry.state(id))? + .clone(); + return with_properties_of(registry, target, old); + } + } + } + None + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index bb2dd3763..ca2783d1d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -10,6 +10,7 @@ pub mod audio; pub mod banner; pub mod biome; pub mod block_entity_render; +pub mod block_transform; pub mod blocks; pub mod bossbar; pub mod brewing; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java new file mode 100644 index 000000000..bc8551c4d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java @@ -0,0 +1,118 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.core.component.BlockTransformer; + +/** + * Original oracle: the data-driven axe/hoe/shovel BlockTransformer entries. + * "dump" lists every block state; a case line "transformer TAB face TAB + * clicked TAB above" (states as "name|prop=value,...") prints the first + * transform that yields a state and its settings, as BlockTransformer.transformBlock + * would pick it. + */ +public final class VanillaBlockTransformerOracle { + static String describe(BlockState state) { + StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|'); + List> props = new ArrayList<>(state.getProperties()); + props.sort(Comparator.comparing(Property::getName)); + boolean first = true; + for (Property p : props) { + out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p)); + first = false; + } + return out.toString(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static String name(BlockState state, Property p) { + return p.getName(state.getValue(p)); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static BlockState parse(String text) { + String[] parts = text.split("\\|", -1); + Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0])); + BlockState state = block.defaultBlockState(); + if (!parts[1].isEmpty()) { + for (String kv : parts[1].split(",")) { + String[] pair = kv.split("="); + Property p = block.getStateDefinition().getProperty(pair[0]); + state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow()); + } + } + return state; + } + + static LevelAccessor level(BlockState clicked, BlockState above) { + return (LevelAccessor) Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(), new Class[]{LevelAccessor.class}, (proxy, method, args) -> { + if (method.getName().equals("getBlockState")) { + BlockPos pos = (BlockPos) args[0]; + return pos.getY() == 0 ? clicked : pos.getY() == 1 && pos.getX() == 0 && pos.getZ() == 0 ? above : net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(); + } + throw new UnsupportedOperationException(method.getName()); + }); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + if (args[0].equals("dump")) { + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (Block block : BuiltInRegistries.BLOCK) { + for (BlockState state : block.getStateDefinition().getPossibleStates()) out.println(describe(state)); + } + } + return; + } + var registry = ParityData.access.lookupOrThrow(Registries.BLOCK_TRANSFORMER); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + String[] f = line.split("\t", -1); + try { + if (f[0].equals("honeycomb")) { + out.println(net.minecraft.world.item.HoneycombItem.getWaxed(parse(f[2])).map(VanillaBlockTransformerOracle::describe).orElse("none")); + continue; + } + var transformer = registry.getOrThrow(ResourceKey.create(Registries.BLOCK_TRANSFORMER, Identifier.parse(f[0]))).value(); + Direction face = Direction.byName(f[1]); + BlockState clicked = parse(f[2]); + LevelAccessor level = level(clicked, parse(f[3])); + String result = "none"; + int index = 0; + for (var data : transformer.transforms()) { + if (!data.disallowedFaces().contains(face)) { + BlockState state = data.blockStateProvider().value().getOptionalState(level, RandomSource.create(0L), BlockPos.ZERO); + if (state != null) { + result = index + "\t" + describe(state) + "\t" + BuiltInRegistries.SOUND_EVENT.getKey(data.sound().value()) + + "\t" + data.particle().name().toLowerCase() + "\t" + + data.loot().map(k -> k.identifier().toString()).orElse("-") + "\t" + data.dropStrategy().name().toLowerCase() + + "\t" + data.updateFromNeighbors() + "\t" + data.transformType().name().toLowerCase() + "\t" + data.consumeOnUse() + + "\t" + data.itemDamagePerUse(); + break; + } + } + index++; + } + out.println(result); + } catch (Throwable e) { + out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage()); + } + } + } + } +} diff --git a/tools/test_block_transformer_parity.py b/tools/test_block_transformer_parity.py new file mode 100644 index 000000000..daad0c731 --- /dev/null +++ b/tools/test_block_transformer_parity.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Compare the data-driven axe/hoe/shovel block transformers with vanilla. + +The Java oracle (VanillaBlockTransformerOracle) evaluates the registry's +BlockStateProviders on a stand-in level; the Rust example +(block_transform_fixture) evaluates horizon_client::block_transform. Cases are +every block state any transformer mentions (plus a random sample of all states) +under each transformer, with a few blocks above and three clicked faces. +""" +import argparse +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +ABOVE = ['minecraft:air|', 'minecraft:cave_air|', 'minecraft:stone|', 'minecraft:water|level=0', 'minecraft:oak_slab|type=bottom,waterlogged=false'] +FACES = ['up', 'down', 'north'] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--sample', type=int, default=3000) + parser.add_argument('--limit', type=int, default=4) + args = parser.parse_args() + work = lib.work_dir('block-transformer-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaBlockTransformerOracle') + vanilla.run('VanillaBlockTransformerOracle', 'dump', work / 'states.txt') + states = (work / 'states.txt').read_text().splitlines() + mentioned = set() + for path in (lib.RESOURCES / 'data/minecraft/block_transformer').glob('*.json'): + text = path.read_text() + for name in set(__import__('re').findall(r'"minecraft:([a-z_0-9]+)"', text)): + mentioned.add('minecraft:' + name) + tags = set() + for tag in ['turns_into_farmland', 'turns_into_dirt_path', 'air']: + for name in __import__('json').loads((lib.RESOURCES / 'data/minecraft/tags/block' / (tag + '.json')).read_text())['values']: + if not name.startswith('#'): + tags.add(name) + rng = random.Random(args.seed) + chosen = [s for s in states if s.split('|')[0] in mentioned or s.split('|')[0] in tags or 'copper' in s or 'lightning_rod' in s] + chosen += rng.sample(states, args.sample) + cases = [] + for transformer in ['axe', 'hoe', 'shovel', 'honeycomb']: + for state in chosen: + for face in FACES: + cases.append('\t'.join([transformer, face, state, rng.choice(ABOVE)])) + (work / 'cases.txt').write_text(''.join(c + '\n' for c in cases)) + vanilla.run('VanillaBlockTransformerOracle', work / 'cases.txt', work / 'native.txt') + lib.cargo_example('horizon-client', 'block_transform_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt') + total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', + lambda case, line: case.split('\t')[0] + ' ' + line.split('\t')[0][:12], None, args.limit) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From 5ec93bf9e79f0e46e34467e49a65319d57a65575 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:09:48 +0200 Subject: [PATCH 06/16] Use the block transformers for axes, hoes, shovels and honeycomb in play Stripping, scraping, wax removal, tilling and path making now come from the data pack's transformers instead of hard coded block lists, so every copper variant, rooted dirt loot and the face restrictions behave like vanilla, and honeycomb waxes copper blocks. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 162 ++++++++++++++++++----------- crates/horizon-client/src/items.rs | 5 + 2 files changed, 105 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2af1021f2..e48da11f1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -446,6 +446,7 @@ pub struct Resources { facts: BlockFacts, items: Items, recipes: Recipes, + transformers: horizon_client::block_transform::Transformers, biomes: Arc, environment: Environment, atlas: HudAtlas, @@ -5419,6 +5420,90 @@ impl Game<'_> { } None } + /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. + fn use_block_transformer( + &mut self, + stack: &ItemStack, + pos: [i32; 3], + face: [i32; 3], + ) -> Result { + use horizon_client::block_transform::Around; + struct Column<'w> { + world: &'w World, + registry: &'w horizon_world::registry::BlockRegistry, + pos: [i32; 3], + } + impl Around for Column<'_> { + fn state(&self, o: [i32; 3]) -> horizon_world::chunk::BlockState { + let id = self + .world + .block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]); + self.registry + .state(id) + .cloned() + .unwrap_or_else(|| horizon_world::chunk::BlockState { + name: "minecraft:air".into(), + properties: Default::default(), + }) + } + } + let Some(id) = self + .res + .items + .get(&stack.item) + .and_then(|i| i.block_transformer.clone()) + else { + return Ok(false); + }; + let face_name = match face { + [0, -1, 0] => "down", + [0, 1, 0] => "up", + [0, 0, -1] => "north", + [0, 0, 1] => "south", + [-1, 0, 0] => "west", + _ => "east", + }; + let registry = self.res.assets.registry; + let (state, sound, loot, damage) = { + let around = Column { + world: &self.world, + registry, + pos, + }; + let Some((_, t, state)) = self.res.transformers.apply( + &self.res.items, + registry, + &id, + face_name, + &around, + ) else { + return Ok(false); + }; + (state, t.sound.clone(), t.loot.clone(), t.damage) + }; + let Ok(new) = registry.resolve(&state) else { + return Ok(false); + }; + self.level_set(pos, new)?; + if loot.as_deref() == Some("minecraft:till/rooted_dirt") { + self.pop_resource( + [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]], + ItemStack::new("minecraft:hanging_roots", 1), + ); + } + self.audio.play( + &sound, + Some([ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]), + 1.0, + 1.0, + ); + self.damage_held(damage); + Ok(true) + } fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { let registry = &self.res.assets.registry; let old = self.world.block(pos[0], pos[1], pos[2]); @@ -5514,17 +5599,6 @@ impl Game<'_> { return Ok(false); }; let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let name = self - .res - .facts - .get(clicked) - .name - .trim_start_matches("minecraft:") - .to_owned(); - let above_air = - self.res - .facts - .is_air(self.world.block(hit.pos[0], hit.pos[1] + 1, hit.pos[2])); if item == "water_bucket" || item == "lava_bucket" { let target = if self.res.facts.get(clicked).replaceable { hit.pos @@ -5561,60 +5635,21 @@ impl Game<'_> { } return Ok(true); } - if item.ends_with("_hoe") && hit.face != [0, -1, 0] && above_air { - // HoeItem.TILLABLES - let result = match name.as_str() { - "grass_block" | "dirt_path" | "dirt" => Some("minecraft:farmland"), - "coarse_dirt" | "rooted_dirt" => Some("minecraft:dirt"), - _ => None, - }; - if let Some(result) = result { - self.set_state_named(hit.pos, result, &[])?; - if name == "rooted_dirt" { - self.pop_resource( - [hit.pos[0], hit.pos[1] - 1, hit.pos[2]], - ItemStack { - item: Arc::from("minecraft:hanging_roots"), - count: 1, - damage: 0, - extra: None, - }, - ); - } - self.audio - .play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0); - self.damage_held(1); - return Ok(true); - } - } - if item.ends_with("_shovel") - && hit.face != [0, -1, 0] - && above_air - && matches!( - name.as_str(), - "grass_block" | "dirt" | "podzol" | "coarse_dirt" | "mycelium" | "rooted_dirt" - ) - { - // ShovelItem.FLATTENABLES - self.set_state_named(hit.pos, "minecraft:dirt_path", &[])?; - self.audio - .play("minecraft:item.shovel.flatten", Some(at(hit.pos)), 1.0, 1.0); - self.damage_held(1); + if self.use_block_transformer(&stack, hit.pos, hit.face)? { return Ok(true); } - if item.ends_with("_axe") && !name.starts_with("stripped_") { - // AxeItem.STRIPPABLES - let strippable = name.ends_with("_log") - || name.ends_with("_wood") - || name.ends_with("_stem") - || name.ends_with("_hyphae") - || name == "bamboo_block"; - let stripped = format!("minecraft:stripped_{name}"); - if strippable && self.res.assets.registry.default_state(&stripped).is_some() { - self.set_state_named(hit.pos, &stripped, &["axis"])?; + if item == "honeycomb" { + let registry = self.res.assets.registry; + let old = registry.state(clicked).cloned(); + if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) + && let Ok(state) = registry.resolve(&waxed) + { + self.level_set(hit.pos, state)?; self.audio - .play("minecraft:item.axe.strip", Some(at(hit.pos)), 1.0, 1.0); - self.damage_held(1); + .play("minecraft:item.honeycomb.wax_on", Some(at(hit.pos)), 1.0, 1.0); + if !self.creative { + self.consume_held(); + } return Ok(true); } } @@ -7606,6 +7641,8 @@ pub fn run() -> Result<()> { let items = Items::load(&root, assets.registry, &facts)?; eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); let recipes = Recipes::load(&root, &items)?; + let transformers = + horizon_client::block_transform::Transformers::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); @@ -7677,6 +7714,7 @@ pub fn run() -> Result<()> { facts, items, recipes, + transformers, biomes, environment, atlas, diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 6e3ebe114..d7b75440e 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -64,6 +64,8 @@ pub struct ItemInfo { pub crafting_remainder: Option, /// `dye`: the dye colour name (dyes, and anything else with the component). pub dye: Option, + /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. + pub block_transformer: Option, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -374,6 +376,9 @@ impl Items { .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), + block_transformer: c["minecraft:block_transformer"] + .as_str() + .map(str::to_owned), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) From 7bd28cc6f117732376e30853885facc84e65e337 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:13:50 +0200 Subject: [PATCH 07/16] Port the cauldron item interactions and test them against vanilla Using a bucket, bottle, water potion, dyed armour, patterned banner or dyed shulker box on an empty, water, lava or powder snow cauldron follows CauldronInteractions, including the creative-mode stack rules of ItemUtils.createFilledResult and the underwater refusal for lava and powder snow. A harness runs every item against every cauldron state in vanilla's own useItemOn and compares the result, block writes, sounds, drops and inventory. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/cauldron_fixture.rs | 132 +++++++++ crates/horizon-client/src/cauldron.rs | 271 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu.rs | 17 ++ .../parity/VanillaCauldronOracle.java | 168 +++++++++++ tools/test_cauldron_parity.py | 81 ++++++ 6 files changed, 670 insertions(+) create mode 100644 crates/horizon-client/examples/cauldron_fixture.rs create mode 100644 crates/horizon-client/src/cauldron.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java create mode 100644 tools/test_cauldron_parity.py diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs new file mode 100644 index 000000000..3b8014410 --- /dev/null +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -0,0 +1,132 @@ +//! Cauldron interactions for tools/test_cauldron_parity.py: reads one JSON +//! case per line and prints "result TAB events TAB inventory". +//! +//! usage: cauldron_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + cauldron::{Outcome, Player, interact}, + crafting::Recipes, + item_data::{canon_stack, parse_stack}, + items::{ItemStack, Items}, + menu::{Env, Kind, Menu}, +}; +use horizon_world::chunk::BlockState; +use serde_json::Value; +use std::{fs, path::Path}; + +struct Stand<'a> { + menu: Menu, + env: &'a Env<'a>, + events: Vec, + hand: Option, +} + +impl Player for Stand<'_> { + fn creative(&self) -> bool { + self.menu.creative + } + fn hand(&mut self) -> &mut Option { + &mut self.hand + } + fn add(&mut self, stack: &mut ItemStack) -> bool { + // The held stack lives in inventory slot 0 for Inventory.add. + self.menu.set_player_item(0, self.hand.take()); + let added = self.menu.give(self.env, stack); + self.hand = self.menu.player_item(0).cloned(); + self.menu.set_player_item(0, None); + added + } + fn contains(&self, stack: &ItemStack) -> bool { + self.menu.player_contains(stack) + || self + .hand + .as_ref() + .is_some_and(|h| h.same_item_same_components(stack)) + } + fn drop_stack(&mut self, stack: ItemStack) { + self.events + .push(format!("drop {}", canon_stack(Some(&stack)))); + } +} + +fn parse(text: &str) -> BlockState { + let (name, props) = text.split_once('|').unwrap_or((text, "")); + BlockState { + name: name.to_owned(), + properties: props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(), + } +} + +fn describe(state: &BlockState) -> String { + let props: Vec = state + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}|{}", state.name, props.join(",")) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(args.get(1).ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let env = Env { + items: &items, + recipes: &recipes, + }; + let mut out = String::new(); + for line in input.lines() { + let case: Value = serde_json::from_str(line)?; + let mut menu = Menu::new(Kind::Inventory); + menu.creative = case["creative"].as_bool().unwrap_or(false); + for pair in case["inventory"].as_array().ok_or("inventory")? { + menu.set_player_item( + pair[0].as_u64().unwrap_or(0) as usize, + parse_stack(pair[1].as_str().unwrap_or("-"))?, + ); + } + let held = parse_stack(case["held"].as_str().unwrap_or("-"))?; + let mut stand = Stand { + menu, + env: &env, + events: Vec::new(), + hand: held, + }; + let cauldron = parse(case["state"].as_str().unwrap_or_default()); + let result = interact( + &items, + &cauldron, + case["under_water"].as_bool().unwrap_or(false), + &mut stand, + ); + if let Some(block) = &result.block { + stand.events.push(format!("set {}", describe(block))); + } + if let Some(sound) = result.sound { + stand.events.push(format!("sound {sound}")); + } + let kind = match result.outcome { + Outcome::Success => "success", + Outcome::Consume => "consume", + Outcome::Pass => "pass", + }; + stand.menu.set_player_item(0, stand.hand.take()); + let inventory: Vec = (0..41) + .filter_map(|i| { + stand + .menu + .player_item(i) + .map(|s| format!("{i}={}", canon_stack(Some(s)))) + }) + .collect(); + out += &format!("{kind}\t{}\t{}\n", stand.events.join(";"), inventory.join(" ")); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs new file mode 100644 index 000000000..6ab4fb5c3 --- /dev/null +++ b/crates/horizon-client/src/cauldron.rs @@ -0,0 +1,271 @@ +//! `CauldronInteractions`: what an item does to an empty, water, lava or +//! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item +//! with vanilla's `useItemOn`. +use crate::items::{ItemStack, Items}; +use horizon_world::chunk::BlockState; + +/// The player side of an interaction. +pub trait Player { + fn creative(&self) -> bool; + /// The stack in the interacting hand. + fn hand(&mut self) -> &mut Option; + /// `Inventory.add`; the leftover stays in `stack`. + fn add(&mut self, stack: &mut ItemStack) -> bool; + /// `Inventory.contains`. + fn contains(&self, stack: &ItemStack) -> bool; + fn drop_stack(&mut self, stack: ItemStack); +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Outcome { + /// `InteractionResult.SUCCESS` + Success, + /// `InteractionResult.CONSUME` + Consume, + /// `TRY_WITH_EMPTY_HAND` + Pass, +} + +#[derive(Debug)] +pub struct Interaction { + pub outcome: Outcome, + /// The cauldron's new state. + pub block: Option, + pub sound: Option<&'static str>, +} + +fn state(name: &str, level: Option) -> BlockState { + BlockState { + name: name.to_owned(), + properties: level + .map(|l| ("level".to_owned(), l.to_string())) + .into_iter() + .collect(), + } +} + +fn pass() -> Interaction { + Interaction { + outcome: Outcome::Pass, + block: None, + sound: None, + } +} + +/// `ItemUtils.createFilledResult`. +fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) { + let creative = player.creative(); + if limit_creative && creative { + if !player.contains(&new) { + let mut new = new; + player.add(&mut new); + } + return; + } + let hand = player.hand(); + if !creative && let Some(held) = hand.as_mut() { + held.count -= 1; + if held.count == 0 { + *hand = None; + } + } + if hand.is_none() { + *hand = Some(new); + return; + } + let mut new = new; + if !player.add(&mut new) { + player.drop_stack(new); + } +} + +/// `LayeredCauldronBlock.lowerFillLevel`. +fn lowered(cauldron: &BlockState) -> BlockState { + let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(1); + if level <= 1 { + state("minecraft:cauldron", None) + } else { + let mut next = cauldron.clone(); + next.properties.insert("level".into(), (level - 1).to_string()); + next + } +} + +fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { + Interaction { + outcome: Outcome::Success, + block: Some(block), + sound, + } +} + +const COLORS: [&str; 16] = [ + "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", + "purple", "blue", "brown", "green", "red", "black", +]; + +/// The cauldron interaction of the held item (`useItemOn`); the hand stack is +/// changed through `player`. +pub fn interact( + items: &Items, + cauldron: &BlockState, + under_water: bool, + player: &mut dyn Player, +) -> Interaction { + let Some(held) = player.hand().clone() else { + return pass(); + }; + let kind = match cauldron.name.as_str() { + "minecraft:cauldron" => "empty", + "minecraft:water_cauldron" => "water", + "minecraft:lava_cauldron" => "lava", + "minecraft:powder_snow_cauldron" => "powder_snow", + _ => return pass(), + }; + let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(0); + let item = &*held.item; + let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water"); + // Dispatcher.get: tags first, then the item map. + if kind == "water" + && items + .item_tags + .get("minecraft:cauldron_can_remove_dye") + .is_some_and(|members| members.contains(item)) + { + if held.data().and_then(|d| d.dyed_color).is_none() { + return pass(); + } + if let Some(stack) = player.hand().as_mut() { + stack.data_mut().dyed_color = None; + stack.tidy(); + } + return changed(lowered(cauldron), None); + } + let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| { + if !can_fill { + return pass(); + } + filled(player, ItemStack::new(new, 1), true); + changed(state("minecraft:cauldron", None), Some(sound)) + }; + let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| { + filled(player, ItemStack::new("minecraft:bucket", 1), true); + changed(block, Some(sound)) + }; + match item { + "minecraft:lava_bucket" => { + return if under_water { + Interaction { + outcome: Outcome::Consume, + block: None, + sound: None, + } + } else { + empty_bucket( + player, + state("minecraft:lava_cauldron", None), + "minecraft:item.bucket.empty_lava", + ) + }; + } + "minecraft:water_bucket" => { + return empty_bucket( + player, + state("minecraft:water_cauldron", Some(3)), + "minecraft:item.bucket.empty", + ); + } + "minecraft:powder_snow_bucket" => { + return if under_water { + Interaction { + outcome: Outcome::Consume, + block: None, + sound: None, + } + } else { + empty_bucket( + player, + state("minecraft:powder_snow_cauldron", Some(3)), + "minecraft:item.bucket.empty_powder_snow", + ) + }; + } + _ => {} + } + match (kind, item) { + ("empty", "minecraft:potion") => { + if !water_potion { + return pass(); + } + filled(player, ItemStack::new("minecraft:glass_bottle", 1), true); + changed( + state("minecraft:water_cauldron", Some(1)), + Some("minecraft:item.bottle.empty"), + ) + } + ("water", "minecraft:bucket") => fill_bucket( + player, + "minecraft:water_bucket", + level == 3, + "minecraft:item.bucket.fill", + ), + ("water", "minecraft:glass_bottle") => { + filled( + player, + ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"), + true, + ); + changed(lowered(cauldron), Some("minecraft:item.bottle.fill")) + } + ("water", "minecraft:potion") => { + if level == 3 || !water_potion { + return pass(); + } + filled(player, ItemStack::new("minecraft:glass_bottle", 1), true); + let mut next = cauldron.clone(); + // BlockState.cycle on a 1..=3 property + next.properties + .insert("level".into(), (level % 3 + 1).to_string()); + changed(next, Some("minecraft:item.bottle.empty")) + } + ("water", name) + if name + .strip_prefix("minecraft:") + .and_then(|n| n.strip_suffix("_banner")) + .is_some_and(|c| COLORS.contains(&c)) => + { + let layers = held.data().map_or(0, |d| d.banner_patterns.len()); + if layers == 0 { + return pass(); + } + let mut cleaned = held.clone(); + cleaned.count = 1; + cleaned.data_mut().banner_patterns.pop(); + cleaned.tidy(); + filled(player, cleaned, false); + changed(lowered(cauldron), None) + } + ("water", name) + if name + .strip_prefix("minecraft:") + .and_then(|n| n.strip_suffix("_shulker_box")) + .is_some_and(|c| COLORS.contains(&c)) => + { + filled(player, held.transmute("minecraft:shulker_box", 1), false); + changed(lowered(cauldron), None) + } + ("lava", "minecraft:bucket") => fill_bucket( + player, + "minecraft:lava_bucket", + true, + "minecraft:item.bucket.fill_lava", + ), + ("powder_snow", "minecraft:bucket") => fill_bucket( + player, + "minecraft:powder_snow_bucket", + level == 3, + "minecraft:item.bucket.fill_powder_snow", + ), + _ => pass(), + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ca2783d1d..594064c90 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -14,6 +14,7 @@ pub mod block_transform; pub mod blocks; pub mod bossbar; pub mod brewing; +pub mod cauldron; pub mod chat; pub mod chunk; pub mod clock; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 5190cf16f..071d13be4 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -278,6 +278,23 @@ impl Menu { self.containers[PLAYER][i].as_ref() } + pub fn set_player_item(&mut self, i: usize, stack: Option) { + self.containers[PLAYER][i] = stack; + } + + /// `Inventory.add`: the leftover stays in `stack`. + pub fn give(&mut self, env: &Env, stack: &mut ItemStack) -> bool { + self.inventory_add(env, stack) + } + + /// `Inventory.contains(stack)`. + pub fn player_contains(&self, stack: &ItemStack) -> bool { + self.containers[PLAYER] + .iter() + .flatten() + .any(|have| have.same_item_same_components(stack)) + } + // ---- item helpers ---- fn max_stack(env: &Env, stack: &ItemStack) -> u32 { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java new file mode 100644 index 000000000..3c1b5dc04 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java @@ -0,0 +1,168 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.AbstractCauldronBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Fluids; + +/** + * Original oracle: a cauldron's useItemOn (CauldronInteractions) with a + * recording stand-in level and player. Each case line is JSON: cauldron state + * ("name|prop=value"), the held stack, creative, whether water is above. The + * output line lists the result, block writes, sounds, the final inventory and + * drops. + */ +public final class VanillaCauldronOracle { + static Object unsafe; + static java.lang.reflect.Method allocate; + static final List events = new ArrayList<>(); + static boolean underWater; + + @SuppressWarnings("unchecked") + static T make(Class type) { + try { + return (T) allocate.invoke(unsafe, type); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + static void set(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + f.set(target, value); + } + + static String describe(BlockState state) { + StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|'); + List> props = new ArrayList<>(state.getProperties()); + props.sort(Comparator.comparing(Property::getName)); + boolean first = true; + for (Property p : props) { + out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p)); + first = false; + } + return out.toString(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static String name(BlockState state, Property p) { + return p.getName(state.getValue(p)); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static BlockState parse(String text) { + String[] parts = text.split("\\|", -1); + Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0])); + BlockState state = block.defaultBlockState(); + if (!parts[1].isEmpty()) { + for (String kv : parts[1].split(",")) { + String[] pair = kv.split("="); + Property p = block.getStateDefinition().getProperty(pair[0]); + state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow()); + } + } + return state; + } + + static final class World extends ServerLevel { + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public boolean isClientSide() { return false; } + @Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int limit) { events.add("set " + describe(state)); return true; } + @Override public FluidState getFluidState(BlockPos pos) { return underWater ? Fluids.WATER.defaultFluidState() : Fluids.EMPTY.defaultFluidState(); } + @Override public void playSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { + events.add("sound " + BuiltInRegistries.SOUND_EVENT.getKey(s)); + } + @Override public void gameEvent(net.minecraft.core.Holder e, net.minecraft.world.phys.Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + @Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; } + } + + static final class FakePlayer extends ServerPlayer { + boolean creative; + Inventory inv; + FakePlayer() { + super(null, null, null, null); + } + @Override public Inventory getInventory() { return inv; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public void setItemInHand(InteractionHand hand, ItemStack stack) { inv.setItem(0, stack); } + @Override public ItemStack getItemInHand(InteractionHand hand) { return inv.getItem(0); } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { } + @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { + if (!stack.isEmpty()) events.add("drop " + ParityData.canon(stack)); + return null; + } + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + try { + events.clear(); + underWater = f.get("under_water").getAsBoolean(); + var world = make(World.class); + var player = make(FakePlayer.class); + player.creative = f.get("creative").getAsBoolean(); + player.inv = new Inventory(player, new EntityEquipment()); + for (var other : f.getAsJsonArray("inventory")) { + var pair = other.getAsJsonArray(); + player.inv.setItem(pair.get(0).getAsInt(), ParityData.stack(pair.get(1).getAsString())); + } + ItemStack held = ParityData.stack(f.get("held").getAsString()); + player.inv.setItem(0, held); + BlockState state = parse(f.get("state").getAsString()); + var cauldron = (AbstractCauldronBlock) state.getBlock(); + var use = net.minecraft.world.level.block.state.BlockBehaviour.class.getDeclaredMethod("useItemOn", ItemStack.class, BlockState.class, + net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, net.minecraft.world.phys.BlockHitResult.class); + use.setAccessible(true); + InteractionResult result = (InteractionResult) use.invoke(cauldron, held, state, world, BlockPos.ZERO, player, InteractionHand.MAIN_HAND, null); + String kind = result == InteractionResult.SUCCESS ? "success" : result == InteractionResult.CONSUME ? "consume" + : result == InteractionResult.TRY_WITH_EMPTY_HAND ? "pass" : result.toString(); + StringBuilder inventory = new StringBuilder(); + for (int i = 0; i < 41; i++) { + ItemStack s = player.inv.getItem(i); + if (!s.isEmpty()) inventory.append(i).append('=').append(ParityData.canon(s)).append(' '); + } + out.println(kind + "\t" + String.join(";", events) + "\t" + inventory.toString().trim()); + } catch (Throwable e) { + out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage()); + if (System.getenv("CAULDRON_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/test_cauldron_parity.py b/tools/test_cauldron_parity.py new file mode 100644 index 000000000..f815d0cac --- /dev/null +++ b/tools/test_cauldron_parity.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Compare cauldron item interactions with vanilla's CauldronInteractions. + +The Java oracle (VanillaCauldronOracle) calls the cauldron block's useItemOn +with a recording level and player; the Rust example (cauldron_fixture) runs +horizon_client::cauldron. Every item is used on every cauldron state (empty, +water, lava and powder snow at each level), with water potions, dyed armour, +patterned banners and shulker boxes, in survival and creative, under water or +not, and with a crowded inventory. The result, block writes, sounds, drops and +the final inventory are compared. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +STATES = ['minecraft:cauldron|', 'minecraft:water_cauldron|level=1', 'minecraft:water_cauldron|level=2', + 'minecraft:water_cauldron|level=3', 'minecraft:lava_cauldron|', 'minecraft:powder_snow_cauldron|level=1', + 'minecraft:powder_snow_cauldron|level=3'] +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def snbt(item, count=1, **components): + body = ','.join('"minecraft:%s":%s' % (k, v) for k, v in sorted(components.items())) + return '{id:"%s",count:%d%s}' % (item, count, ',components:{%s}' % body if body else '') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--limit', type=int, default=4) + args = parser.parse_args() + work = lib.work_dir('cauldron-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaCauldronOracle') + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json')) + rng = random.Random(args.seed) + held = [] + for name, info in items.items(): + if name == 'minecraft:air': + continue + top = info.get('minecraft:max_stack_size', 64) + held.append(snbt(name, 1)) + held.append(snbt(name, rng.randrange(1, top + 1))) + for color in DYES: + for layers in range(0, 4): + body = '[%s]' % ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(patterns), rng.choice(DYES)) for _ in range(layers)) + held.append(snbt('minecraft:%s_banner' % color, rng.choice([1, 3]), banner_patterns=body)) + held.append(snbt('minecraft:%s_shulker_box' % color, rng.choice([1, 2]))) + for item in ['leather_helmet', 'leather_chestplate', 'leather_leggings', 'leather_boots', 'leather_horse_armor', 'wolf_armor']: + held.append(snbt('minecraft:' + item, 1, dyed_color=rng.randrange(1 << 24))) + for potion in ['minecraft:water', 'minecraft:healing', 'minecraft:awkward']: + for item in ['potion', 'splash_potion', 'lingering_potion']: + held.append(snbt('minecraft:' + item, rng.choice([1, 2]), potion_contents='{potion:"%s"}' % potion)) + cases = [] + filler = [snbt(i, 64) for i in ['minecraft:stone', 'minecraft:dirt', 'minecraft:cobblestone']] + for state in STATES: + for stack in held: + crowded = rng.random() < 0.25 + inventory = [[i, rng.choice(filler)] for i in range(1, 36)] if crowded else [] + if not crowded and rng.random() < 0.3: + inventory = [[rng.randrange(1, 36), snbt('minecraft:bucket', rng.randrange(1, 16))]] + cases.append({'state': state, 'held': stack, 'creative': rng.random() < 0.3, 'under_water': rng.random() < 0.3, + 'inventory': inventory}) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + vanilla.run('VanillaCauldronOracle', work / 'cases.jsonl', work / 'native.txt') + lib.cargo_example('horizon-client', 'cauldron_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', + lambda case, line: case['state'].split('|')[0] + ' ' + line.split('\t')[0], + lambda case: json.dumps(case)[:700], args.limit) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From f49faf685c3a4a36ad2cc743a77dd67519b54592 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:14:26 +0200 Subject: [PATCH 08/16] Use cauldron interactions in play Right clicking a cauldron with a bucket, bottle, water potion, dyed armour, banner or dyed shulker box now applies the verified cauldron rules to the held stack, inventory and block. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/cauldron_fixture.rs | 8 +- crates/horizon-client/src/cauldron.rs | 20 +++-- crates/horizon-client/src/game.rs | 78 +++++++++++++++++++ 3 files changed, 96 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 3b8014410..e111782fb 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -3,7 +3,7 @@ //! //! usage: cauldron_fixture RESOURCES INPUT OUTPUT use horizon_client::{ - cauldron::{Outcome, Player, interact}, + cauldron::{Outcome, Player, interact, removes_dye}, crafting::Recipes, item_data::{canon_stack, parse_stack}, items::{ItemStack, Items}, @@ -99,10 +99,14 @@ fn main() -> horizon_client::Result<()> { hand: held, }; let cauldron = parse(case["state"].as_str().unwrap_or_default()); + let dye = stand + .hand + .as_ref() + .is_some_and(|h| removes_dye(&items, &h.item)); let result = interact( - &items, &cauldron, case["under_water"].as_bool().unwrap_or(false), + dye, &mut stand, ); if let Some(block) = &result.block { diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index 6ab4fb5c3..a2b48168a 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -2,6 +2,14 @@ //! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item //! with vanilla's `useItemOn`. use crate::items::{ItemStack, Items}; + +/// `ItemTags.CAULDRON_CAN_REMOVE_DYE` membership. +pub fn removes_dye(items: &Items, item: &str) -> bool { + items + .item_tags + .get("minecraft:cauldron_can_remove_dye") + .is_some_and(|members| members.contains(item)) +} use horizon_world::chunk::BlockState; /// The player side of an interaction. @@ -105,11 +113,12 @@ const COLORS: [&str; 16] = [ ]; /// The cauldron interaction of the held item (`useItemOn`); the hand stack is -/// changed through `player`. +/// changed through `player`. `removes_dye` is whether the held item is in the +/// `cauldron_can_remove_dye` tag. pub fn interact( - items: &Items, cauldron: &BlockState, under_water: bool, + removes_dye: bool, player: &mut dyn Player, ) -> Interaction { let Some(held) = player.hand().clone() else { @@ -126,12 +135,7 @@ pub fn interact( let item = &*held.item; let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water"); // Dispatcher.get: tags first, then the item map. - if kind == "water" - && items - .item_tags - .get("minecraft:cauldron_can_remove_dye") - .is_some_and(|members| members.contains(item)) - { + if kind == "water" && removes_dye { if held.data().and_then(|d| d.dyed_color).is_none() { return pass(); } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e48da11f1..52b0eb3a2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5420,6 +5420,79 @@ impl Game<'_> { } None } + /// `CauldronInteractions` for the held item aimed at a cauldron. + fn use_on_cauldron(&mut self, pos: [i32; 3]) -> Result { + use horizon_client::cauldron::{self, Outcome}; + struct Hand<'g, 'a>(&'g mut Game<'a>); + impl cauldron::Player for Hand<'_, '_> { + fn creative(&self) -> bool { + self.0.creative + } + fn hand(&mut self) -> &mut Option { + let selected = self.0.selected; + &mut self.0.inventory[selected] + } + fn add(&mut self, stack: &mut ItemStack) -> bool { + let before = stack.count; + match self.0.give(stack.clone()) { + None => stack.count = 0, + Some(rest) => stack.count = rest.count, + } + stack.count < before + } + fn contains(&self, stack: &ItemStack) -> bool { + self.0 + .inventory + .iter() + .flatten() + .any(|have| have.same_item_same_components(stack)) + } + fn drop_stack(&mut self, stack: ItemStack) { + if let Some(eye) = self.0.eye_position() { + self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40); + } + } + } + let registry = self.res.assets.registry; + let id = self.world.block(pos[0], pos[1], pos[2]); + let Some(state) = registry + .state(id) + .filter(|s| s.name.ends_with("cauldron")) + .cloned() + else { + return Ok(false); + }; + let Some(held) = self.inventory[self.selected].as_ref() else { + return Ok(false); + }; + let removes_dye = cauldron::removes_dye(&self.res.items, &held.item); + let above = self.world.block(pos[0], pos[1] + 1, pos[2]); + let under_water = registry + .state(above) + .is_some_and(|s| s.name == "minecraft:water"); + let result = cauldron::interact(&state, under_water, removes_dye, &mut Hand(self)); + if result.outcome == Outcome::Pass { + return Ok(false); + } + if let Some(block) = result.block + && let Ok(new) = registry.resolve(&block) + { + self.level_set(pos, new)?; + } + if let Some(sound) = result.sound { + self.audio.play( + sound, + Some([ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]), + 1.0, + 1.0, + ); + } + Ok(true) + } /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. fn use_block_transformer( &mut self, @@ -5560,6 +5633,11 @@ impl Game<'_> { f64::from(p[2]) + 0.5, ] }; + if let Some(hit) = self.pick() + && self.use_on_cauldron(hit.pos)? + { + return Ok(true); + } if item == "bucket" { let Some(hit) = self.pick_fluid() else { return Ok(false); From f6e519097d906e1dc5f14ddade569ed0f331da9b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:14:42 +0200 Subject: [PATCH 09/16] Format the interaction work Co-Authored-By: Claude Sonnet 5.5 --- .../examples/block_transform_fixture.rs | 5 ++- .../examples/cauldron_fixture.rs | 11 +++++- crates/horizon-client/src/block_transform.rs | 16 ++++++-- crates/horizon-client/src/cauldron.rs | 33 +++++++++++++--- crates/horizon-client/src/game.rs | 38 +++++++++---------- crates/horizon-client/src/items.rs | 4 +- 6 files changed, 74 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/block_transform_fixture.rs index 686ad8c42..01d92a047 100644 --- a/crates/horizon-client/examples/block_transform_fixture.rs +++ b/crates/horizon-client/examples/block_transform_fixture.rs @@ -53,7 +53,10 @@ impl Around for Column { fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().collect(); - let root = Path::new(args.get(1).ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?); + let root = Path::new( + args.get(1) + .ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?, + ); let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let assets = Assets::load(root)?; diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index e111782fb..9f238396d 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -72,7 +72,10 @@ fn describe(state: &BlockState) -> String { fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().collect(); - let root = Path::new(args.get(1).ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?); + let root = Path::new( + args.get(1) + .ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?, + ); let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; @@ -129,7 +132,11 @@ fn main() -> horizon_client::Result<()> { .map(|s| format!("{i}={}", canon_stack(Some(s)))) }) .collect(); - out += &format!("{kind}\t{}\t{}\n", stand.events.join(";"), inventory.join(" ")); + out += &format!( + "{kind}\t{}\t{}\n", + stand.events.join(";"), + inventory.join(" ") + ); } fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; Ok(()) diff --git a/crates/horizon-client/src/block_transform.rs b/crates/horizon-client/src/block_transform.rs index fb94c2532..92f1455e9 100644 --- a/crates/horizon-client/src/block_transform.rs +++ b/crates/horizon-client/src/block_transform.rs @@ -60,12 +60,19 @@ fn predicate(value: &Value) -> Option { Some(match value["type"].as_str()? { "minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] { Value::String(s) => vec![s.clone()], - Value::Array(a) => a.iter().filter_map(|b| b.as_str().map(str::to_owned)).collect(), + Value::Array(a) => a + .iter() + .filter_map(|b| b.as_str().map(str::to_owned)) + .collect(), _ => return None, }), "minecraft:matching_block_tag" => { let o = value["offset"].as_array(); - let at = |i: usize| o.and_then(|o| o.get(i)).and_then(Value::as_i64).unwrap_or(0) as i32; + let at = |i: usize| { + o.and_then(|o| o.get(i)) + .and_then(Value::as_i64) + .unwrap_or(0) as i32 + }; Predicate::Tag { tag: value["tag"].as_str()?.to_owned(), offset: [at(0), at(1), at(2)], @@ -94,7 +101,10 @@ fn provider(value: &Value, registry: &BlockRegistry) -> Option { Some("minecraft:rule_based") => { let mut rules = Vec::new(); for rule in value["rules"].as_array()? { - rules.push((predicate(&rule["if_true"])?, provider(&rule["then"], registry)?)); + rules.push(( + predicate(&rule["if_true"])?, + provider(&rule["then"], registry)?, + )); } Some(Provider::Rules(rules)) } diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index a2b48168a..9fbe1179f 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -89,12 +89,17 @@ fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) { /// `LayeredCauldronBlock.lowerFillLevel`. fn lowered(cauldron: &BlockState) -> BlockState { - let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(1); + let level: u8 = cauldron + .properties + .get("level") + .and_then(|l| l.parse().ok()) + .unwrap_or(1); if level <= 1 { state("minecraft:cauldron", None) } else { let mut next = cauldron.clone(); - next.properties.insert("level".into(), (level - 1).to_string()); + next.properties + .insert("level".into(), (level - 1).to_string()); next } } @@ -108,8 +113,22 @@ fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { } const COLORS: [&str; 16] = [ - "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", - "purple", "blue", "brown", "green", "red", "black", + "white", + "orange", + "magenta", + "light_blue", + "yellow", + "lime", + "pink", + "gray", + "light_gray", + "cyan", + "purple", + "blue", + "brown", + "green", + "red", + "black", ]; /// The cauldron interaction of the held item (`useItemOn`); the hand stack is @@ -131,7 +150,11 @@ pub fn interact( "minecraft:powder_snow_cauldron" => "powder_snow", _ => return pass(), }; - let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(0); + let level: u8 = cauldron + .properties + .get("level") + .and_then(|l| l.parse().ok()) + .unwrap_or(0); let item = &*held.item; let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water"); // Dispatcher.get: tags first, then the item map. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 52b0eb3a2..2fc27c703 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5508,16 +5508,15 @@ impl Game<'_> { } impl Around for Column<'_> { fn state(&self, o: [i32; 3]) -> horizon_world::chunk::BlockState { - let id = self - .world - .block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]); - self.registry - .state(id) - .cloned() - .unwrap_or_else(|| horizon_world::chunk::BlockState { + let id = + self.world + .block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]); + self.registry.state(id).cloned().unwrap_or_else(|| { + horizon_world::chunk::BlockState { name: "minecraft:air".into(), properties: Default::default(), - }) + } + }) } } let Some(id) = self @@ -5543,13 +5542,11 @@ impl Game<'_> { registry, pos, }; - let Some((_, t, state)) = self.res.transformers.apply( - &self.res.items, - registry, - &id, - face_name, - &around, - ) else { + let Some((_, t, state)) = + self.res + .transformers + .apply(&self.res.items, registry, &id, face_name, &around) + else { return Ok(false); }; (state, t.sound.clone(), t.loot.clone(), t.damage) @@ -5723,8 +5720,12 @@ impl Game<'_> { && let Ok(state) = registry.resolve(&waxed) { self.level_set(hit.pos, state)?; - self.audio - .play("minecraft:item.honeycomb.wax_on", Some(at(hit.pos)), 1.0, 1.0); + self.audio.play( + "minecraft:item.honeycomb.wax_on", + Some(at(hit.pos)), + 1.0, + 1.0, + ); if !self.creative { self.consume_held(); } @@ -7719,8 +7720,7 @@ pub fn run() -> Result<()> { let items = Items::load(&root, assets.registry, &facts)?; eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); let recipes = Recipes::load(&root, &items)?; - let transformers = - horizon_client::block_transform::Transformers::load(&root, assets.registry)?; + let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index d7b75440e..c34c296d0 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -376,9 +376,7 @@ impl Items { .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), - block_transformer: c["minecraft:block_transformer"] - .as_str() - .map(str::to_owned), + block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) From 4a0d9ea01d1ca60c98da70eb2b04941ec52c3f56 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:16:12 +0200 Subject: [PATCH 10/16] Fix clippy findings in the menu, transformer and wiring code Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/block_transform.rs | 2 +- crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/menu.rs | 16 ++++++++-------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/block_transform.rs b/crates/horizon-client/src/block_transform.rs index 92f1455e9..4cd1d6f94 100644 --- a/crates/horizon-client/src/block_transform.rs +++ b/crates/horizon-client/src/block_transform.rs @@ -142,7 +142,7 @@ impl Predicate { match self { Self::Blocks(names) => { let state = around.state([0, 0, 0]); - names.iter().any(|n| *n == state.name) + names.contains(&state.name) } Self::Tag { tag, offset } => { let state = around.state(*offset); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2852e9633..5725c9fe8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5746,7 +5746,7 @@ impl Game<'_> { } return Ok(true); } - if self.use_block_transformer(&stack, hit.pos, hit.face)? { + if self.use_block_transformer(stack, hit.pos, hit.face)? { return Ok(true); } if item == "honeycomb" { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 071d13be4..4d7cec897 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -878,9 +878,9 @@ impl Menu { if input == Input::QuickCraft { let expected = self.quick_status; self.quick_status = button & 3; - if (expected != 1 || self.quick_status != 2) && expected != self.quick_status { - self.reset_quick_craft(); - } else if self.carried.is_none() { + if ((expected != 1 || self.quick_status != 2) && expected != self.quick_status) + || self.carried.is_none() + { self.reset_quick_craft(); } else if self.quick_status == 0 { self.quick_type = (button >> 2) & 3; @@ -1069,7 +1069,7 @@ impl Menu { let amount = if primary { clicked.count } else { - (clicked.count + 1) / 2 + clicked.count.div_ceil(2) }; if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { self.carried = Some(taken); @@ -1190,10 +1190,10 @@ impl Menu { let item = self.slot(t).expect("has item").clone(); if pass != 0 || item.count != Self::max_stack(env, &item) { let room = carried_max - have.count; - if let Some(removed) = self.safe_take(env, t, item.count, room) { - if let Some(c) = self.carried.as_mut() { - c.count += removed.count; - } + if let Some(removed) = self.safe_take(env, t, item.count, room) + && let Some(c) = self.carried.as_mut() + { + c.count += removed.count; } } } From 5041496f0824048abf8a0f29bf437eb0433a5020 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:29:00 +0200 Subject: [PATCH 11/16] Add the brewing stand to the menu engine and click harness The brewing stand menu follows BrewingStandMenu: single-item potion slots, the ingredient and fuel slots with their quick move rules, checked against vanilla with potion bottles, ingredients and fuels in the random contents. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/cauldron_fixture.rs | 2 + .../horizon-client/examples/menu_fixture.rs | 2 + crates/horizon-client/src/menu.rs | 96 ++++++++++++++++++- tools/test_menu_click_parity.py | 14 ++- 4 files changed, 108 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 9f238396d..f2cd257cd 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -79,9 +79,11 @@ fn main() -> horizon_client::Result<()> { let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; + let brewing = horizon_client::brewing::Brewing::load(root, &items); let env = Env { items: &items, recipes: &recipes, + brewing: &brewing, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index ded828ef3..0909d3de4 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -34,9 +34,11 @@ fn main() -> horizon_client::Result<()> { let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; + let brewing = horizon_client::brewing::Brewing::load(root, &items); let env = Env { items: &items, recipes: &recipes, + brewing: &brewing, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 4d7cec897..b0bafd2bf 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -5,6 +5,7 @@ //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. use crate::{ + brewing::Brewing, crafting::Recipes, items::{ItemStack, Items}, }; @@ -13,6 +14,7 @@ use crate::{ pub struct Env<'a> { pub items: &'a Items, pub recipes: &'a Recipes, + pub brewing: &'a Brewing, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -51,6 +53,7 @@ pub enum Kind { Shulker, /// The cooking recipe type: smelting, blasting or smoking. Furnace(&'static str), + Brewing, } impl Kind { @@ -67,6 +70,7 @@ impl Kind { "furnace" => Self::Furnace("smelting"), "blast_furnace" => Self::Furnace("blasting"), "smoker" => Self::Furnace("smoking"), + "brewing" => Self::Brewing, _ => return None, }) } @@ -84,6 +88,12 @@ enum Role { Output, /// `ResultSlot` of a crafting grid. CraftResult, + /// `BrewingStandMenu.PotionSlot`. + Potion, + /// `BrewingStandMenu.IngredientsSlot`. + Ingredient, + /// `BrewingStandMenu.FuelSlot`. + BrewFuel, } #[derive(Clone, Copy)] @@ -220,6 +230,27 @@ impl Menu { slots.extend(main(27, Role::Shulker)); player(&mut slots); } + Kind::Brewing => { + containers[MAIN] = vec![None; 5]; + for (index, role) in [ + Role::Potion, + Role::Potion, + Role::Potion, + Role::Ingredient, + Role::BrewFuel, + ] + .into_iter() + .enumerate() + { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + player(&mut slots); + data = 4; + } Kind::Furnace(_) => { containers[MAIN] = vec![None; 3]; slots.extend([ @@ -349,6 +380,19 @@ impl Menu { Role::Shulker => Self::fits_inside(stack), Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), Role::Output | Role::CraftResult => false, + Role::Potion => { + env.brewing.is_bottle(stack) + || env + .items + .item_tags + .get("minecraft:brewing_potion_inputs") + .is_some_and(|m| m.contains(&*stack.item)) + } + Role::Ingredient => env.brewing.is_reagent(stack), + Role::BrewFuel => env + .items + .get(&stack.item) + .is_some_and(|i| i.brewing_fuel.is_some()), } } @@ -367,7 +411,7 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) => 1, + Role::Armor(_) | Role::Potion => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -742,6 +786,56 @@ impl Menu { return None; } } + Kind::Brewing => { + after_take = true; + let slot = self.slots[index]; + let commit = |m: &mut Self, stack: &ItemStack| { + m.containers[slot.container][slot.index] = + (stack.count > 0).then(|| stack.clone()); + }; + if index <= 4 { + if !self.move_to(env, &mut stack, 5, 41, true) { + return None; + } + } else if env + .items + .get(&clicked.item) + .is_some_and(|i| i.brewing_fuel.is_some()) + { + let moved = self.move_to(env, &mut stack, 4, 5, false); + if moved + || (env.brewing.is_reagent(&stack) + && !self.move_to(env, &mut stack, 3, 4, false)) + { + commit(self, &stack); + return None; + } + } else if env.brewing.is_reagent(&stack) { + if !self.move_to(env, &mut stack, 3, 4, false) { + return None; + } + } else if env.brewing.is_bottle(&stack) + || env + .items + .item_tags + .get("minecraft:brewing_potion_inputs") + .is_some_and(|m| m.contains(&*stack.item)) + { + if !self.move_to(env, &mut stack, 0, 3, false) { + return None; + } + } else if (5..32).contains(&index) { + if !self.move_to(env, &mut stack, 32, 41, false) { + return None; + } + } else if (32..41).contains(&index) { + if !self.move_to(env, &mut stack, 5, 32, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 5, 41, false) { + return None; + } + } Kind::Furnace(recipe) => { after_take = true; if index == 2 { diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index cd015e703..6f71e49ef 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -19,22 +19,25 @@ except ImportError: import lab 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} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4} + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4} COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', 'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box', 'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling', - 'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest'] + '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'] def quote(text): return '"' + text + '"' -def snbt(item, count, damage=0, curse=False): +def snbt(item, count, damage=0, curse=False, potion=None): comps = [] + if potion: + comps.append('"minecraft:potion_contents":{potion:"%s"}' % potion) if damage: comps.append('"minecraft:damage":%d' % damage) if curse: @@ -60,7 +63,8 @@ class Gen: if info.get('minecraft:max_damage') and rng.random() < 0.3: damage = rng.randrange(1, info['minecraft:max_damage']) count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) - return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info)) + potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None + return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) def slots(self, size, density): return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] From 3318a0481909f13f4de0d4f85eff730e86a55dea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:30:07 +0200 Subject: [PATCH 12/16] Add the crafter to the menu engine and click harness The crafter menu follows CrafterMenu: slots refuse items while their disabled flag is set, and the result slot is non-interactive. Random disabled flags are part of the harness cases. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/menu.rs | 31 ++++++++++++++++++++++++++++++- tools/test_menu_click_parity.py | 6 +++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index b0bafd2bf..c23db47ec 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -54,6 +54,7 @@ pub enum Kind { /// The cooking recipe type: smelting, blasting or smoking. Furnace(&'static str), Brewing, + Crafter, } impl Kind { @@ -71,6 +72,7 @@ impl Kind { "blast_furnace" => Self::Furnace("blasting"), "smoker" => Self::Furnace("smoking"), "brewing" => Self::Brewing, + "crafter" => Self::Crafter, _ => return None, }) } @@ -88,6 +90,10 @@ enum Role { Output, /// `ResultSlot` of a crafting grid. CraftResult, + /// `CrafterSlot`: refuses items while its disabled flag (data slot) is set. + CrafterIn, + /// `NonInteractiveResultSlot`. + Inert, /// `BrewingStandMenu.PotionSlot`. Potion, /// `BrewingStandMenu.IngredientsSlot`. @@ -230,6 +236,17 @@ impl Menu { slots.extend(main(27, Role::Shulker)); player(&mut slots); } + Kind::Crafter => { + containers[MAIN] = vec![None; 9]; + slots.extend(main(9, Role::CrafterIn)); + player(&mut slots); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::Inert, + }); + data = 10; + } Kind::Brewing => { containers[MAIN] = vec![None; 5]; for (index, role) in [ @@ -379,7 +396,8 @@ impl Menu { .unwrap_or(false), Role::Shulker => Self::fits_inside(stack), Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), - Role::Output | Role::CraftResult => false, + Role::Output | Role::CraftResult | Role::Inert => false, + Role::CrafterIn => self.data.get(self.slots[s].index) != Some(&1), Role::Potion => { env.brewing.is_bottle(stack) || env @@ -398,6 +416,7 @@ impl Menu { fn may_pickup(&self, s: usize) -> bool { match self.slots[s].role { + Role::Inert => false, Role::Armor(_) => match self.slot(s) { Some(stack) => { self.creative || stack.enchantment_level("minecraft:binding_curse") == 0 @@ -836,6 +855,16 @@ impl Menu { return None; } } + Kind::Crafter => { + after_take = true; + if index < 9 { + if !self.move_to(env, &mut stack, 9, 45, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 9, false) { + return None; + } + } Kind::Furnace(recipe) => { after_take = true; if index == 2 { diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 6f71e49ef..5137537b2 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -19,8 +19,8 @@ except ImportError: import lab 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} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4} + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10} COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', @@ -132,7 +132,7 @@ def main(): if menu in ('inventory', 'crafting') and rng.random() < 0.6: g.recipe(slots, 2 if menu == 'inventory' else 3) cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, - 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [0] * DATA.get(menu, 0), + 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))], 'ops': g.ops(size)}) (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt') From 0351c4d6c4a126cb10ef413171d62ab4e75f6d85 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:30:49 +0200 Subject: [PATCH 13/16] Run container shift-clicks through the verified menu engine Shift-clicking in chests, barrels, shulker boxes, hoppers, droppers, dispensers and furnaces now builds the vanilla menu from the open container and the player inventory, applies quickMoveStack with the repeat-until-unchanged loop of doClick, and writes the slots back. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/storage.rs | 120 ++++++++++++---------- 1 file changed, 65 insertions(+), 55 deletions(-) diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index cf9a3a1ac..348983352 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -342,70 +342,80 @@ impl Game<'_> { impl Game<'_> { /// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace - /// menu for a shift-click on `slot`; false when the menu has none. + /// menu for a shift-click on `slot`, run by the verified menu engine + /// (`horizon_client::menu`); false when the menu has none. pub(super) fn container_quick_move(&mut self, slot: usize) -> bool { + use horizon_client::menu::{Env, Input, Kind, Menu}; let size = self.container_size(); - let furnace = match self.container_kind() { - Some(BlockEntity::Chest(_)) => None, - Some(BlockEntity::Furnace(f)) => Some(f.kind), + let (kind, count) = match self.container_kind() { + Some(BlockEntity::Chest(_)) => { + let shulker = self.container.is_some_and(|k| { + let id = self.world.block(k.0, k.1, k.2); + is_shulker_box(&self.res.facts.get(id).name) + }); + let kind = match size { + 5 => Kind::Hopper, + 9 => Kind::Dispenser, + 27 if shulker => Kind::Shulker, + n => Kind::Chest((n / 9).clamp(1, 6)), + }; + (kind, size) + } + Some(BlockEntity::Furnace(f)) => ( + Kind::Furnace( + match f.kind.recipe_type().trim_start_matches("minecraft:") { + "blasting" => "blasting", + "smoking" => "smoking", + _ => "smelting", + }, + ), + 3, + ), _ => return false, }; - if slot >= 300 + size.max(3) { + // Menu index <-> game slot: container 300.., main inventory 9..36, hotbar 0..9. + let to_menu = |g: usize| match g { + 300.. if g < 300 + count => Some(g - 300), + 9..36 => Some(count + g - 9), + 0..9 => Some(count + 27 + g), + _ => None, + }; + let from_menu = |i: usize| match i { + _ if i < count => 300 + i, + _ if i < count + 27 => 9 + i - count, + _ => i - count - 27, + }; + let Some(index) = to_menu(slot) else { return false; - } - let Some(mut stack) = self.slot_mut(slot).take() else { - return true; }; - let player: Vec = (9..36).chain(0..9).collect(); - let hotbar_or_main = |slot: usize| -> Vec { - if slot < 9 { - (9..36).collect() - } else { - (0..9).collect() + let mut menu = Menu::new(kind); + let total = menu.slot_count(); + let before: Vec> = (0..total) + .map(|i| self.slot_mut(from_menu(i)).clone()) + .collect(); + let after: Vec> = { + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + }; + for (i, stack) in before.iter().enumerate() { + menu.set_slot(&env, i, stack.clone()); } + if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { + return true; + } + (0..total).map(|i| menu.slot(i).cloned()).collect() }; - match furnace { - None => { - if slot >= 300 { - self.move_to(&mut stack, &player, true); - } else { - let targets: Vec = (300..300 + size).collect(); - self.move_to(&mut stack, &targets, false); - } - } - Some(kind) => { - // AbstractFurnaceMenu.quickMoveStack. - if slot >= 300 { - self.move_to(&mut stack, &player, slot == 302); - } else { - let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some(); - let fuel = self - .res - .items - .get(&stack.item) - .is_some_and(|i| i.fuel.is_some()); - let moved = if smeltable { - self.move_to(&mut stack, &[300], false) - } else if fuel { - self.move_to(&mut stack, &[301], false) - } else { - false - }; - if !moved && !smeltable && !fuel { - let other = hotbar_or_main(slot); - self.move_to(&mut stack, &other, false); - } - if let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - f.cooking_timer = 0; - } - } - } + for (i, stack) in after.into_iter().enumerate() { + *self.slot_mut(from_menu(i)) = stack; } - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); + if matches!(kind, Kind::Furnace(_)) + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + f.cooking_timer = 0; } true } From b3b6e9583554c0e0032f2d2f1d58ecf14f881770 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:31:26 +0200 Subject: [PATCH 14/16] Run inventory and crafting table shift-clicks through the menu engine Shift-clicking an inventory, hotbar, armour or crafting grid slot now follows InventoryMenu and CraftingMenu quickMoveStack, including moving into the crafting grid, armour and off-hand slots and the repeat-until-unchanged loop. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 129 ++++++++++++++++-------------- 1 file changed, 67 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5725c9fe8..9c648216c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3527,6 +3527,69 @@ impl Game<'_> { self.close_ender_chest(); self.close_cart_container(); } + /// `quickMoveStack` of the player inventory or crafting table menu for a + /// shift-click, run by the verified menu engine (`horizon_client::menu`). + fn inventory_quick_move(&mut self, slot: usize) -> bool { + use horizon_client::menu::{Env, Input, Kind, Menu}; + let table = self.craft_size == 3; + let cells = self.craft_size * self.craft_size; + // Game slot <-> menu index. + let main = if table { 10 } else { 9 }; + let to_menu = |g: usize| match g { + 100..109 if g - 100 < cells => Some(1 + g - 100), + 500..504 if !table => Some(5 + g - 500), + 9..36 => Some(main + g - 9), + 0..9 => Some(main + 27 + g), + _ => None, + }; + let Some(index) = to_menu(slot) else { + return false; + }; + let total = main + 36 + usize::from(!table); + let mut game_slots: Vec> = vec![None; total]; + for g in (100..109).chain(500..504).chain(0..36) { + if let Some(i) = to_menu(g) { + game_slots[i] = Some(g); + } + } + let mut menu = Menu::new(if table { + Kind::Crafting + } else { + Kind::Inventory + }); + let before: Vec> = game_slots + .iter() + .map(|g| g.and_then(|g| self.slot_mut(g).clone())) + .collect(); + let offhand = self.offhand.clone(); + let after: Vec> = { + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + }; + for (i, stack) in before.iter().enumerate() { + menu.set_slot(&env, i, stack.clone()); + } + if !table { + menu.set_slot(&env, 45, offhand); + } + if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { + return true; + } + (0..total).map(|i| menu.slot(i).cloned()).collect() + }; + for (i, g) in game_slots.iter().enumerate() { + if let Some(g) = g { + *self.slot_mut(*g) = after[i].clone(); + } + } + if !table { + self.offhand = after[45].clone(); + } + self.apply_equipment(); + true + } fn click_inventory(&mut self, right: bool) { if self.mount_click(right) { return; @@ -3653,68 +3716,10 @@ impl Game<'_> { } return; } - if shift && (500..504).contains(&slot) { - // InventoryMenu.quickMoveStack: armour back to the main - // inventory, then the hotbar. - if let Some(stack) = self.armor[slot - 500].take() { - if let Some(i) = (9..36).chain(0..9).find(|&i| self.inventory[i].is_none()) { - self.inventory[i] = Some(stack); - } else { - self.armor[slot - 500] = Some(stack); - } - self.apply_equipment(); - } - return; - } - if shift && slot < 36 { - // InventoryMenu.quickMoveStack: armour into its empty slot, an - // off-hand item into an empty off hand. - let equip = self.inventory[slot] - .as_ref() - .and_then(|s| self.res.items.get(&s.item)) - .and_then(|i| i.equip_slot.clone()); - let armor = ["head", "chest", "legs", "feet"] - .iter() - .position(|s| equip.as_deref() == Some(*s)); - if let Some(a) = armor - && self.armor[a].is_none() - { - self.armor[a] = self.inventory[slot].take(); - self.apply_equipment(); - return; - } - if equip.as_deref() == Some("offhand") && self.offhand.is_none() { - self.offhand = self.inventory[slot].take(); - return; - } - // Quick move between hotbar and main inventory. - if let Some(stack) = self.inventory[slot].take() { - let range = if slot < 9 { 9..36 } else { 0..9 }; - let mut stack = stack; - for i in range.clone() { - if let Some(s) = &mut self.inventory[i] - && s.same_item_same_components(&stack) - { - let moved = max(&self.res.items, s) - .saturating_sub(s.count) - .min(stack.count); - s.count += moved; - stack.count -= moved; - } - } - if stack.count > 0 - && let Some(i) = range.clone().find(|&i| self.inventory[i].is_none()) - { - self.inventory[i] = Some(stack); - stack = ItemStack { - count: 0, - ..self.inventory[i].clone().unwrap() - }; - } - if stack.count > 0 { - self.inventory[slot] = Some(stack); - } - } + if shift + && (slot < 36 || (500..504).contains(&slot) || (100..109).contains(&slot)) + && self.inventory_quick_move(slot) + { return; } if (500..504).contains(&slot) { From 762ad298e64a3364f152952e8eb33c7390002cb2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:33:13 +0200 Subject: [PATCH 15/16] Finish the pending menu and storage work Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 359 +++++++++++++++++++--- crates/horizon-client/src/game/storage.rs | 74 +---- crates/horizon-client/src/menu.rs | 4 + 3 files changed, 316 insertions(+), 121 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9c648216c..721cf907b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -505,6 +505,10 @@ struct Game<'a> { carried: Option, craft_grid: Vec>, craft_size: usize, + /// A quick craft drag over inventory slots: (button, game slots so far). + inv_drag: Option<(i32, Vec)>, + /// The last inventory click, for the double click that gathers a stack. + last_inv_click: Option<(std::time::Instant, usize, bool)>, /// Open container block entity, if any. container: Option<(i32, i32, i32)>, /// Open workstation menu (enchanting table, anvil, ...). @@ -1072,9 +1076,9 @@ impl Game<'_> { } /// Player.drop: thrown from the eyes along the view direction. fn drop_held(&mut self, all: bool) { - let Some(eye) = self.eye_position() else { + if self.eye_position().is_none() { return; - }; + } let Some(stack) = self.inventory[self.selected].as_mut() else { return; }; @@ -1083,13 +1087,20 @@ impl Game<'_> { count, ..stack.clone() }; - // Player.drop: the drop statistics. - self.stats.add("dropped", &thrown.item, count as i32); - self.stats.custom("drop", 1); stack.count -= count; if stack.count == 0 { self.inventory[self.selected] = None; } + self.player_drop(thrown); + } + /// `Player.drop`: the statistics and a thrown item entity in front of the player. + fn player_drop(&mut self, thrown: ItemStack) { + let Some(eye) = self.eye_position() else { + return; + }; + // Player.drop: the drop statistics. + self.stats.add("dropped", &thrown.item, thrown.count as i32); + self.stats.custom("drop", 1); let (yaw, pitch) = ( f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians(), @@ -3527,69 +3538,303 @@ impl Game<'_> { self.close_ender_chest(); self.close_cart_container(); } - /// `quickMoveStack` of the player inventory or crafting table menu for a - /// shift-click, run by the verified menu engine (`horizon_client::menu`). + /// `quickMoveStack` of the open plain menu for a shift-click. fn inventory_quick_move(&mut self, slot: usize) -> bool { - use horizon_client::menu::{Env, Input, Kind, Menu}; - let table = self.craft_size == 3; - let cells = self.craft_size * self.craft_size; - // Game slot <-> menu index. - let main = if table { 10 } else { 9 }; - let to_menu = |g: usize| match g { - 100..109 if g - 100 < cells => Some(1 + g - 100), - 500..504 if !table => Some(5 + g - 500), - 9..36 => Some(main + g - 9), - 0..9 => Some(main + 27 + g), - _ => None, - }; - let Some(index) = to_menu(slot) else { - return false; - }; - let total = main + 36 + usize::from(!table); - let mut game_slots: Vec> = vec![None; total]; - for g in (100..109).chain(500..504).chain(0..36) { - if let Some(i) = to_menu(g) { - game_slots[i] = Some(g); + self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove) + } + /// `AbstractContainerMenu.clicked` on the open inventory, crafting table, + /// chest, hopper, dispenser or furnace menu, run by the verified menu + /// engine (`horizon_client::menu`). `slot` None is outside the window. + /// False when the open screen is not one the engine models. + fn menu_click( + &mut self, + slot: Option, + button: i32, + input: horizon_client::menu::Input, + ) -> bool { + use horizon_client::menu::{Env, Kind, Menu}; + #[derive(Clone, Copy)] + struct Map { + container: usize, + table: bool, + cells: usize, + plain: bool, + } + impl Map { + fn main(&self) -> usize { + match (self.plain, self.table) { + (false, _) => self.container, + (true, true) => 10, + (true, false) => 9, + } + } + fn to_menu(&self, g: usize) -> Option { + let main = self.main(); + if self.plain { + match g { + 200 => Some(0), + 100..109 if g - 100 < self.cells => Some(1 + g - 100), + 500..504 if !self.table => Some(5 + g - 500), + 504 if !self.table => Some(45), + 9..36 => Some(main + g - 9), + 0..9 => Some(main + 27 + g), + _ => None, + } + } else { + match g { + 300.. if g < 300 + self.container => Some(g - 300), + 9..36 => Some(main + g - 9), + 0..9 => Some(main + 27 + g), + _ => None, + } + } + } + fn to_game(&self, i: usize) -> Option { + let main = self.main(); + if self.plain { + match i { + 0 => None, + 1..=9 if i - 1 < self.cells => Some(100 + i - 1), + 5..9 if !self.table => Some(500 + i - 5), + 45 if !self.table => Some(504), + _ if i >= main && i < main + 27 => Some(9 + i - main), + _ if i >= main + 27 && i < main + 36 => Some(i - main - 27), + _ => None, + } + } else if i < self.container { + Some(300 + i) + } else if i < self.container + 27 { + Some(9 + i - self.container) + } else { + Some(i - self.container - 27) + } } } - let mut menu = Menu::new(if table { - Kind::Crafting + let (kind, map) = if self.container.is_some() { + let size = self.container_size(); + let (kind, count) = match self.container_kind() { + Some(BlockEntity::Chest(_)) => { + let shulker = self.container.is_some_and(|k| { + let id = self.world.block(k.0, k.1, k.2); + storage::is_shulker_box(&self.res.facts.get(id).name) + }); + let kind = match size { + 5 => Kind::Hopper, + 9 => Kind::Dispenser, + 27 if shulker => Kind::Shulker, + n => Kind::Chest((n / 9).clamp(1, 6)), + }; + (kind, size) + } + Some(BlockEntity::Furnace(f)) => ( + Kind::Furnace( + match f.kind.recipe_type().trim_start_matches("minecraft:") { + "blasting" => "blasting", + "smoking" => "smoking", + _ => "smelting", + }, + ), + 3, + ), + _ => return false, + }; + let map = Map { + container: count, + table: false, + cells: 0, + plain: false, + }; + (kind, map) + } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { + let table = self.craft_size == 3; + let map = Map { + container: 0, + table, + cells: self.craft_size * self.craft_size, + plain: true, + }; + ( + if table { + Kind::Crafting + } else { + Kind::Inventory + }, + map, + ) } else { - Kind::Inventory - }); - let before: Vec> = game_slots - .iter() - .map(|g| g.and_then(|g| self.slot_mut(g).clone())) + return false; + }; + let menu_slot = match slot { + Some(g) => { + if g == 200 && input != horizon_client::menu::Input::QuickMove { + return false; + } + match map.to_menu(g) { + Some(i) => i as i32, + None => return false, + } + } + None => -999, + }; + let mut menu = Menu::new(kind); + let total = menu.slot_count(); + let before: Vec> = (0..total) + .map(|i| map.to_game(i).and_then(|g| self.slot_mut(g).clone())) .collect(); - let offhand = self.offhand.clone(); - let after: Vec> = { + let carried = self.carried.clone(); + let creative = self.creative; + let (after, carried, dropped): (Vec>, Option, Vec) = { let env = Env { items: &self.res.items, recipes: &self.res.recipes, brewing: &self.res.stations.brewing, }; + menu.creative = creative; for (i, stack) in before.iter().enumerate() { menu.set_slot(&env, i, stack.clone()); } - if !table { - menu.set_slot(&env, 45, offhand); - } - if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { + menu.carried = carried; + if menu.click(&env, menu_slot, button, input).is_err() { return true; } - (0..total).map(|i| menu.slot(i).cloned()).collect() + ( + (0..total).map(|i| menu.slot(i).cloned()).collect(), + menu.carried.take(), + std::mem::take(&mut menu.dropped), + ) }; - for (i, g) in game_slots.iter().enumerate() { - if let Some(g) = g { - *self.slot_mut(*g) = after[i].clone(); + for (i, stack) in after.into_iter().enumerate() { + if let Some(g) = map.to_game(i) { + *self.slot_mut(g) = stack; } } - if !table { - self.offhand = after[45].clone(); + self.carried = carried; + for stack in dropped { + self.player_drop(stack); + } + if matches!(kind, Kind::Furnace(_)) + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + f.cooking_timer = 0; } self.apply_equipment(); true } + /// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar + /// slot or the off hand, THROW one or the whole stack. + fn inventory_hotkey(&mut self, key: KeyCode) -> bool { + use horizon_client::menu::Input; + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return false; + }; + let batch = HudBatch::new(size); + let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { + return false; + }; + let digit = [ + KeyCode::Digit1, + KeyCode::Digit2, + KeyCode::Digit3, + KeyCode::Digit4, + KeyCode::Digit5, + KeyCode::Digit6, + KeyCode::Digit7, + KeyCode::Digit8, + KeyCode::Digit9, + ] + .iter() + .position(|k| *k == key); + let done = match (digit, key) { + (Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap), + (None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap), + (None, KeyCode::KeyQ) => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.menu_click(Some(slot), i32::from(all), Input::Throw) + } + _ => false, + }; + if done && let Some(key) = self.container { + self.container_changed(key); + } + done + } + /// The plain inventory mouse press: starts a quick craft drag when a + /// stack is held, gathers on a double click, else the normal click. + fn inventory_press(&mut self, right: bool) { + use horizon_client::menu::Input; + let slot = self.renderer.as_ref().and_then(|r| { + let batch = HudBatch::new([r.config.width, r.config.height]); + self.slot_at(&batch, self.cursor.0, self.cursor.1) + }); + let shift = + self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + if let Some(slot) = slot + && !shift + && slot != 200 + { + let now = std::time::Instant::now(); + let double = !right + && self.carried.is_some() + && self.last_inv_click.is_some_and(|(at, last, was_right)| { + last == slot && !was_right && now.duration_since(at).as_millis() < 250 + }); + self.last_inv_click = Some((now, slot, right)); + if double && self.menu_click(Some(slot), 0, Input::PickupAll) { + self.last_inv_click = None; + return; + } + if self.carried.is_some() { + self.inv_drag = Some((i32::from(right), vec![slot])); + return; + } + } + self.click_inventory(right); + } + /// Mouse movement while a quick craft drag is running. + fn inventory_drag_move(&mut self) { + let Some((_, slots)) = self.inv_drag.as_ref() else { + return; + }; + let Some(r) = self.renderer.as_ref() else { + return; + }; + let batch = HudBatch::new([r.config.width, r.config.height]); + if let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) + && slot != 200 + && !slots.contains(&slot) + && let Some((_, slots)) = self.inv_drag.as_mut() + { + slots.push(slot); + } + } + /// Mouse release: finishes a quick craft drag (one slot is a plain click). + fn inventory_release(&mut self) { + use horizon_client::menu::Input; + let Some((ty, slots)) = self.inv_drag.take() else { + return; + }; + if slots.len() == 1 { + if !self.menu_click(Some(slots[0]), ty, Input::Pickup) { + self.click_inventory(ty == 1); + } + } else { + let mask = |header: i32| header | (ty << 2); + self.menu_click(None, mask(0), Input::QuickCraft); + for slot in slots { + self.menu_click(Some(slot), mask(1), Input::QuickCraft); + } + self.menu_click(None, mask(2), Input::QuickCraft); + } + if let Some(key) = self.container { + self.container_changed(key); + } + } fn click_inventory(&mut self, right: bool) { if self.mount_click(right) { return; @@ -7129,6 +7374,18 @@ impl Game<'_> { Screen::WorldOptions => self.close_world_options(), Screen::Chat => self.close_chat(), }, + KeyCode::Digit1 + | KeyCode::Digit2 + | KeyCode::Digit3 + | KeyCode::Digit4 + | KeyCode::Digit5 + | KeyCode::Digit6 + | KeyCode::Digit7 + | KeyCode::Digit8 + | KeyCode::Digit9 + | KeyCode::KeyF + | KeyCode::KeyQ + if self.screen == Screen::Inventory && self.inventory_hotkey(key) => {} KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), // key.advancements. @@ -7376,6 +7633,7 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory { self.loom_drag(); + self.inventory_drag_move(); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -7503,12 +7761,15 @@ impl ApplicationHandler for Game<'_> { } } Screen::Inventory if pressed => { - self.click_inventory(button == MouseButton::Right); + self.inventory_press(button == MouseButton::Right); if let Some(key) = self.container { self.container_changed(key); } } - Screen::Inventory => self.loom_release(), + Screen::Inventory => { + self.inventory_release(); + self.loom_release(); + } Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(), Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); @@ -7913,6 +8174,8 @@ pub fn run() -> Result<()> { carried: None, craft_grid: vec![None; 9], craft_size: 2, + inv_drag: None, + last_inv_click: None, container: None, station: None, potions: Default::default(), diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 348983352..2cb6d40a0 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -345,79 +345,7 @@ impl Game<'_> { /// menu for a shift-click on `slot`, run by the verified menu engine /// (`horizon_client::menu`); false when the menu has none. pub(super) fn container_quick_move(&mut self, slot: usize) -> bool { - use horizon_client::menu::{Env, Input, Kind, Menu}; - let size = self.container_size(); - let (kind, count) = match self.container_kind() { - Some(BlockEntity::Chest(_)) => { - let shulker = self.container.is_some_and(|k| { - let id = self.world.block(k.0, k.1, k.2); - is_shulker_box(&self.res.facts.get(id).name) - }); - let kind = match size { - 5 => Kind::Hopper, - 9 => Kind::Dispenser, - 27 if shulker => Kind::Shulker, - n => Kind::Chest((n / 9).clamp(1, 6)), - }; - (kind, size) - } - Some(BlockEntity::Furnace(f)) => ( - Kind::Furnace( - match f.kind.recipe_type().trim_start_matches("minecraft:") { - "blasting" => "blasting", - "smoking" => "smoking", - _ => "smelting", - }, - ), - 3, - ), - _ => return false, - }; - // Menu index <-> game slot: container 300.., main inventory 9..36, hotbar 0..9. - let to_menu = |g: usize| match g { - 300.. if g < 300 + count => Some(g - 300), - 9..36 => Some(count + g - 9), - 0..9 => Some(count + 27 + g), - _ => None, - }; - let from_menu = |i: usize| match i { - _ if i < count => 300 + i, - _ if i < count + 27 => 9 + i - count, - _ => i - count - 27, - }; - let Some(index) = to_menu(slot) else { - return false; - }; - let mut menu = Menu::new(kind); - let total = menu.slot_count(); - let before: Vec> = (0..total) - .map(|i| self.slot_mut(from_menu(i)).clone()) - .collect(); - let after: Vec> = { - let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - }; - for (i, stack) in before.iter().enumerate() { - menu.set_slot(&env, i, stack.clone()); - } - if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { - return true; - } - (0..total).map(|i| menu.slot(i).cloned()).collect() - }; - for (i, stack) in after.into_iter().enumerate() { - *self.slot_mut(from_menu(i)) = stack; - } - if matches!(kind, Kind::Furnace(_)) - && let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - f.cooking_timer = 0; - } - true + self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove) } } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index c23db47ec..4ced9e6d0 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -128,6 +128,8 @@ pub struct Menu { pub creative: bool, /// Dropped stacks (canonical text), `xp+N` and the like, in order. pub drops: Vec, + /// The dropped stacks themselves, for the caller to throw. + pub dropped: Vec, quick_status: i32, quick_type: i32, quick_slots: Vec, @@ -302,6 +304,7 @@ impl Menu { data: vec![0; data], creative: false, drops: Vec::new(), + dropped: Vec::new(), quick_status: 0, quick_type: 0, quick_slots: Vec::new(), @@ -531,6 +534,7 @@ impl Menu { fn drop_stack(&mut self, stack: &ItemStack) { if stack.count > 0 { self.drops.push(crate::item_data::canon_stack(Some(stack))); + self.dropped.push(stack.clone()); } } From cedae6609d333b9194487d4a67a826b98c6c85b4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:02:24 +0200 Subject: [PATCH 16/16] Route inventory clicks, drags, double clicks, hotkeys and drops through the menu engine On the player inventory, crafting table, chest family, hopper, dispenser and furnace screens, holding a stack and dragging across slots now splits it (left even, right one each), a quick second click gathers matching stacks, number keys and F swap with the hotbar or off hand, and Q or Ctrl+Q throws one or the whole stack, all through the same engine the click harness checks against vanilla. Other screens keep their own click handling. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 54 ++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 721cf907b..847629c83 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3552,6 +3552,10 @@ impl Game<'_> { button: i32, input: horizon_client::menu::Input, ) -> bool { + self.menu_ops(&[(slot, button, input)]) + } + /// Several clicks on one menu instance (a quick craft drag is three). + fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::{Env, Kind, Menu}; #[derive(Clone, Copy)] struct Map { @@ -3568,7 +3572,7 @@ impl Game<'_> { (true, false) => 9, } } - fn to_menu(&self, g: usize) -> Option { + fn to_menu(self, g: usize) -> Option { let main = self.main(); if self.plain { match g { @@ -3589,7 +3593,7 @@ impl Game<'_> { } } } - fn to_game(&self, i: usize) -> Option { + fn to_game(self, i: usize) -> Option { let main = self.main(); if self.plain { match i { @@ -3664,18 +3668,22 @@ impl Game<'_> { } else { return false; }; - let menu_slot = match slot { - Some(g) => { - if g == 200 && input != horizon_client::menu::Input::QuickMove { - return false; + let mut clicks = Vec::new(); + for &(slot, button, input) in ops { + let menu_slot = match slot { + Some(g) => { + if g == 200 && input != horizon_client::menu::Input::QuickMove { + return false; + } + match map.to_menu(g) { + Some(i) => i as i32, + None => return false, + } } - match map.to_menu(g) { - Some(i) => i as i32, - None => return false, - } - } - None => -999, - }; + None => -999, + }; + clicks.push((menu_slot, button, input)); + } let mut menu = Menu::new(kind); let total = menu.slot_count(); let before: Vec> = (0..total) @@ -3694,8 +3702,10 @@ impl Game<'_> { menu.set_slot(&env, i, stack.clone()); } menu.carried = carried; - if menu.click(&env, menu_slot, button, input).is_err() { - return true; + for (menu_slot, button, input) in clicks { + if menu.click(&env, menu_slot, button, input).is_err() { + return true; + } } ( (0..total).map(|i| menu.slot(i).cloned()).collect(), @@ -3825,11 +3835,17 @@ impl Game<'_> { } } else { let mask = |header: i32| header | (ty << 2); - self.menu_click(None, mask(0), Input::QuickCraft); - for slot in slots { - self.menu_click(Some(slot), mask(1), Input::QuickCraft); + let mut ops = vec![(None, mask(0), Input::QuickCraft)]; + ops.extend( + slots + .into_iter() + .map(|slot| (Some(slot), mask(1), Input::QuickCraft)), + ); + ops.push((None, mask(2), Input::QuickCraft)); + if !self.menu_ops(&ops) { + // Not a menu the engine models: the drag is a plain click. + self.click_inventory(ty == 1); } - self.menu_click(None, mask(2), Input::QuickCraft); } if let Some(key) = self.container { self.container_changed(key);