diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs new file mode 100644 index 000000000..e919c1e05 --- /dev/null +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -0,0 +1,89 @@ +//! Recipe book placements for tools/test_place_recipe_parity.py: reads one +//! JSON case per line (menu, inventory, grid, recipe, max, creative, +//! selected) and the oracle's order of the counted items, runs +//! `Menu::place_recipe` and prints the oracle's line. +//! +//! usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT +use horizon_client::{ + crafting::Recipes, + item_data::{canon_stack, parse_stack}, + items::Items, + menu::{Env, Kind, Menu, place::PostPlace}, +}; +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(); + let inv: Vec = (0..41).map(|i| canon_stack(menu.player_item(i))).collect(); + format!( + "{} | {} |{data} | {} | inv {}", + slots.join(" "), + canon_stack(menu.carried.as_ref()), + menu.drops.join(";"), + inv.join(" ") + ) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT"; + let root = Path::new(args.get(1).ok_or(usage)?); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let orders = fs::read_to_string(args.get(3).ok_or(usage)?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let brewing = horizon_client::brewing::Brewing::load(root, &items); + let banners = horizon_client::banner::Banners::default(); + let env = Env { + items: &items, + recipes: &recipes, + brewing: &brewing, + banners: &banners, + }; + let mut out = String::new(); + for (line, order) in cases.lines().zip(orders.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); + menu.selected = case["selected"].as_u64().unwrap_or(0) as usize; + 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("-"))?, + ); + } + for pair in case["grid"].as_array().ok_or("grid")? { + menu.set_slot( + &env, + pair[0].as_u64().unwrap_or(0) as usize, + parse_stack(pair[1].as_str().unwrap_or("-"))?, + ); + } + menu.drops.clear(); + let order: Vec = order.split_whitespace().map(str::to_owned).collect(); + let recipe = case["recipe"].as_str().unwrap_or_default(); + let impossible = recipes.placement(recipe).is_none_or(|p| p.impossible()); + let post = if impossible { + "-" + } else { + match menu.place_recipe( + &env, + recipe, + case["max"].as_bool().unwrap_or(false), + menu.creative, + Some(&order), + ) { + PostPlace::Nothing => "NOTHING", + PostPlace::Ghost => "PLACE_GHOST_RECIPE", + } + }; + out += &format!("post {post} | {}\n", state(&menu)); + } + fs::write(args.get(4).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 754c701b3..44a8bf994 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -56,6 +56,39 @@ impl Ingredient { self.0.contains(&*stack.item) } } +/// `PlacementInfo`: the ingredients to find and, per recipe slot, the index +/// of its ingredient (`slotsToIngredientIndex`, -1 for an empty slot). Empty +/// when the recipe is impossible to place. +#[derive(Clone, Debug, Default)] +pub struct Placement { + pub ingredients: Vec, + pub slots: Vec, + /// A `ShapedRecipe`'s width and height (the others fill the grid). + pub shaped: Option<(usize, usize)>, +} +impl Placement { + /// `PlacementInfo.createFromOptionals` (and `create` with no empty slots). + pub fn of(cells: Vec>, shaped: Option<(usize, usize)>) -> Self { + let mut out = Self { + shaped, + ..Self::default() + }; + for cell in cells { + match cell { + Some(i) if i.0.is_empty() => return Self::default(), + Some(i) => { + out.slots.push(out.ingredients.len() as i32); + out.ingredients.push(i); + } + None => out.slots.push(-1), + } + } + out + } + pub fn impossible(&self) -> bool { + self.slots.is_empty() + } +} /// A recipe result: `ItemStackTemplate` (`id`, `count`, `components`), with the /// id optional for the transmuting recipes that keep the input's item. #[derive(Clone, Debug)] @@ -1319,56 +1352,114 @@ impl Recipes { map_scale, }; for (name, recipe) in &self.crafting { - let result = match recipe { - Recipe::Special(special) => { - if !special.matches(&ctx, &input) { - continue; - } - special.assemble(&ctx, &input) - } - Recipe::Shaped { - width, - height, - cells, - result, - } => { - if *width != input.width - || *height != input.height - || cells.iter().flatten().count() != input.count() - { - continue; - } - let matches = |mirror: bool| { - (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, - } - }) - }) - }; - if !(matches(false) || matches(true)) { - continue; - } - Some(result.create()) - } - Recipe::Shapeless { - ingredients, - result, - } => { - if !matches_all(ingredients, &input.stacks()) { - continue; - } - Some(result.create()) - } - }; - return result.map(|r| (name.as_str(), r)); + if let Some(result) = Self::assemble_if_matches(&ctx, &input, recipe) { + return result.map(|r| (name.as_str(), r)); + } } None } + /// `Recipe.matches` then `assemble` for one recipe: None when it does + /// not match, Some(None) when it matches with nothing to make. + fn assemble_if_matches( + ctx: &Context, + input: &Input, + recipe: &Recipe, + ) -> Option> { + match recipe { + Recipe::Special(special) => special + .matches(ctx, input) + .then(|| special.assemble(ctx, input)), + Recipe::Shaped { + width, + height, + cells, + result, + } => { + if *width != input.width + || *height != input.height + || cells.iter().flatten().count() != input.count() + { + return None; + } + let matches = |mirror: bool| { + (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, + } + }) + }) + }; + (matches(false) || matches(true)).then(|| Some(result.create())) + } + Recipe::Shapeless { + ingredients, + result, + } => matches_all(ingredients, &input.stacks()).then(|| Some(result.create())), + } + } + /// `recipe.matches(craftSlots.asCraftInput())` for one recipe by id + /// (`minecraft:name`). + pub fn recipe_matches(&self, id: &str, grid: &[Option], size: usize) -> bool { + let name = id.trim_start_matches("minecraft:"); + let Some((_, recipe)) = self.crafting.iter().find(|(n, _)| n == name) else { + return false; + }; + let Some(input) = Input::of(grid, size) else { + return false; + }; + let ctx = Context { + recipes: self, + map_scale: &|_| None, + }; + Self::assemble_if_matches(&ctx, &input, recipe).is_some() + } + /// `Recipe.placementInfo` of a crafting or cooking recipe by id; None for + /// an unknown id, an empty placement when it is impossible to place. + pub fn placement(&self, id: &str) -> Option { + let name = id.trim_start_matches("minecraft:"); + if let Some(c) = self.cooking.iter().find(|c| c.id == name) { + return Some(Placement::of(vec![Some(c.ingredient.clone())], None)); + } + let (_, recipe) = self.crafting.iter().find(|(n, _)| n == name)?; + Some(match recipe { + Recipe::Shaped { + width, + height, + cells, + .. + } => Placement::of(cells.clone(), Some((*width, *height))), + Recipe::Shapeless { ingredients, .. } => { + Placement::of(ingredients.iter().cloned().map(Some).collect(), None) + } + Recipe::Special(Special::Transmute { + input, + material, + max, + .. + }) => { + let mut list = vec![Some(input.clone())]; + list.extend(std::iter::repeat_n(Some(material.clone()), *max)); + Placement::of(list, None) + } + Recipe::Special(Special::Dye { target, dye, .. }) => { + Placement::of(vec![Some(target.clone()), Some(dye.clone())], None) + } + Recipe::Special(Special::Imbue { + source, material, .. + }) => Placement::of( + (0..9) + .map(|i| Some(if i == 4 { source } else { material }.clone())) + .collect(), + None, + ), + // CustomRecipe.placementInfo: NOT_PLACEABLE. + Recipe::Special(_) => Placement::default(), + }) + } /// `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. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8fd558374..7360723f3 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3738,9 +3738,15 @@ impl Game<'_> { banners: &self.res.stations.banners, }; menu.creative = creative; + menu.selected = self.selected; for (i, stack) in before.iter().enumerate() { menu.set_slot(&env, i, stack.clone()); } + // The off hand is part of the inventory even when the menu has no slot for it. + let offhand_mapped = game_of.contains(&Some(504)); + if !offhand_mapped { + menu.set_player_item(40, self.offhand.clone()); + } menu.settle(&env); if kind == Kind::Loom && let Some((selected, patterns)) = station_menu @@ -3773,6 +3779,9 @@ impl Game<'_> { } } self.carried = carried; + if !offhand_mapped { + self.offhand = menu.player_item(40).cloned(); + } for stack in dropped { self.player_drop(stack); } diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 1a1095bd4..ee42f991f 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -9,7 +9,8 @@ use horizon_client::{ containers::{BlockEntity, FurnaceKind}, hud::{HudBatch, Rect, rgba}, items::ItemStack, - recipe_book::{Available, Book, BookType, Collection, Display, Entry, Tab}, + menu::place::{PostPlace, Stacked}, + recipe_book::{Book, BookType, Collection, Display, Entry, Tab}, ui::EditBox, }; use std::{ @@ -212,30 +213,16 @@ impl Game<'_> { fn book_grid(&self) -> (usize, usize) { (self.craft_size, self.craft_size) } - /// The slot ids holding the menu's recipe inputs (and, for furnaces, the - /// fuel and result slots that the book also reads). - fn book_input_slots(&self, book: BookType) -> Vec { - match book { - BookType::Crafting => { - let (w, h) = self.book_grid(); - (0..w * h).map(|i| 100 + i).collect() - } - _ => vec![300], - } - } - /// The items the book counts: the inventory and the menu's crafting slots. - fn book_available(&mut self, book: BookType) -> Available { - let mut stacks: Vec = self.inventory.iter().flatten().cloned().collect(); - let slots = match book { - BookType::Crafting => self.book_input_slots(book), - _ => vec![300, 301, 302], - }; - for slot in slots { - if let Some(s) = self.slot_mut(slot).clone() { - stacks.push(s); - } - } - Available::from_stacks(stacks.iter()) + /// The items the book counts (`RecipeBookComponent.updateStackedContents`): + /// the inventory and the menu's crafting slots, as the menu engine counts them. + fn book_available(&mut self, _book: BookType) -> Stacked { + let mut out = Stacked::default(); + let stock = &mut out; + self.menu_session(|menu, env, _| { + *stock = menu.stacked_contents(env); + Some(false) + }); + out } fn unlocked_recipes(&self) -> BTreeSet { self.adv @@ -317,7 +304,7 @@ impl Game<'_> { 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())) + && (!filtering || book.can_craft(e, &available)) }; let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id); let mut tabs = Vec::new(); @@ -376,7 +363,7 @@ impl Game<'_> { BookType::Crafting => e.fits(gw, gh), _ => true, }; - let craftable = |e: &Entry| selected(e) && available.can_craft(&e.requirements()); + let craftable = |e: &Entry| selected(e) && book.can_craft(e, &available); let filtering = self.book_filtering(book_type); let mut tabs = Vec::new(); for tab in book_type.tabs() { @@ -660,8 +647,9 @@ impl Game<'_> { self.recipe_ui.ghost.clear(); self.place_recipe(book_type, entry_index, use_max); } - /// `ServerPlaceRecipe.placeRecipe`: fills the grid from the inventory, - /// or shows the ghost recipe when the items are missing. + /// `ServerboundPlaceRecipePacket`: the server places the recipe + /// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost + /// recipe when the items are missing. fn place_recipe(&mut self, book_type: BookType, entry_index: usize, use_max: bool) { let Some(entry) = self .recipe_ui @@ -672,88 +660,23 @@ impl Game<'_> { else { return; }; - let (gw, gh) = match book_type { - BookType::Crafting => self.book_grid(), - _ => (1, 1), - }; - let inputs = self.book_input_slots(book_type); - let clear: Vec = match book_type { - BookType::Crafting => inputs.clone(), - _ => vec![300, 302], - }; - if !self.creative && !self.can_clear_grid(&clear) { - return; - } - let available = self.book_available(book_type); - let requirements = entry.requirements(); - if !available.can_craft(&requirements) { - self.clear_book_grid(&clear); + let creative = self.creative; + let mut post = None; + let answer = &mut post; + self.menu_session(|menu, env, _| { + // handlePlaceRecipe: an impossible recipe is refused outright. + if env + .recipes + .placement(&entry.id) + .is_none_or(|p| p.impossible()) + { + return Some(false); + } + *answer = Some(menu.place_recipe(env, &entry.id, use_max, creative, None)); + Some(true) + }); + if post == Some(PostPlace::Ghost) { self.fill_ghost(book_type, &entry); - self.recipe_book_changed(); - return; - } - let matches_placed = self.recipe_matches(book_type, &entry); - let biggest = available.biggest_stack(&requirements); - if matches_placed { - for slot in &inputs { - let stack = self.slot_mut(*slot).clone(); - if let Some(s) = stack { - let max = self.res.items.get(&s.item).map_or(64, |i| i.max_stack); - if biggest.min(max) < s.count + 1 { - return; - } - } - } - } - let amount = if use_max { - biggest - } else if matches_placed { - let smallest = inputs - .iter() - .filter_map(|slot| self.slot_mut(*slot).as_ref().map(|s| s.count)) - .min(); - smallest.map_or(1, |n| n + 1) - } else { - 1 - }; - let order = self - .recipe_ui - .book - .as_ref() - .map(|b| b.order.clone()) - .unwrap_or_default(); - let Some(mut used) = available.pick(&requirements, amount, &order) else { - return; - }; - let item_max = |item: &str| self.res.items.get(item).map_or(64, |i| i.max_stack); - let mut amount = amount; - let clamped = used.iter().map(|i| item_max(i)).fold(amount, u32::min); - if clamped != amount { - amount = clamped; - match available.pick(&requirements, amount, &order) { - Some(u) => used = u, - None => return, - } - } - self.clear_book_grid(&clear); - for (ingredient, grid_index) in entry.grid_cells(gw, gh) { - let Some(ingredient) = ingredient else { - continue; - }; - let slot = inputs[grid_index.min(inputs.len() - 1)]; - let mut remaining = amount as i64; - while remaining > 0 { - remaining = self.move_item_to_grid(slot, &used[ingredient], remaining); - if remaining < 0 { - break; - } - } - } - if let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - f.cooking_timer = 0; } self.recipe_book_changed(); } @@ -764,111 +687,6 @@ impl Game<'_> { self.container_changed(key); } } - /// `menu.recipeMatches(recipe)`: the grid already holds this recipe. - fn recipe_matches(&mut self, book_type: BookType, entry: &Entry) -> bool { - match (&entry.display, book_type) { - (Display::Furnace(ingredient), _) => self - .slot_mut(300) - .as_ref() - .is_some_and(|s| ingredient.test(s)), - (_, BookType::Crafting) => { - let n = self.craft_size; - let grid: Vec> = - (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); - self.res - .recipes - .find(&grid, n) - .is_some_and(|(name, _)| format!("minecraft:{name}") == entry.id) - } - _ => false, - } - } - /// `Inventory.getSlotWithRemainingSpace`. - fn has_room_for(&self, stack: &ItemStack) -> bool { - let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); - self.inventory - .iter() - .flatten() - .any(|s| s.same_item_same_components(stack) && max > 1 && s.count < max) - } - /// `ServerPlaceRecipe.testClearGrid`. - fn can_clear_grid(&mut self, slots: &[usize]) -> bool { - let mut free: Vec = Vec::new(); - let free_in_inventory = self.inventory.iter().filter(|s| s.is_none()).count(); - for &slot in slots { - let Some(mut stack) = self.slot_mut(slot).clone() else { - continue; - }; - if !self.has_room_for(&stack) && free.len() <= free_in_inventory { - for other in free.iter_mut() { - let max = self.res.items.get(&other.item).map_or(64, |i| i.max_stack); - if other.item == stack.item - && other.count != max - && other.count + stack.count <= max - { - other.count += stack.count; - stack.count = 0; - break; - } - } - if stack.count > 0 { - if free.len() >= free_in_inventory { - return false; - } - free.push(stack); - } - } else if !self.has_room_for(&stack) { - return false; - } - } - true - } - /// `ServerPlaceRecipe.clearGrid`: the grid's items go back to the inventory. - fn clear_book_grid(&mut self, slots: &[usize]) { - for &slot in slots { - if let Some(stack) = self.slot_mut(slot).take() { - self.give_or_drop_quiet(stack); - } - } - } - /// Back into the inventory; what does not fit is lost only in creative - /// (survival checks room first with `can_clear_grid`). - fn give_or_drop_quiet(&mut self, stack: ItemStack) { - let _ = self.give(stack); - } - /// `ServerPlaceRecipe.moveItemToGrid`; the count still to move or -1. - fn move_item_to_grid(&mut self, slot: usize, item: &str, count: i64) -> i64 { - let target = self.slot_mut(slot).clone(); - let found = self.inventory.iter().position(|s| { - s.as_ref().is_some_and(|s| { - &*s.item == item - && s.damage == 0 - && s.enchantments().is_empty() - && s.custom_name().is_none() - && target - .as_ref() - .is_none_or(|t| t.same_item_same_components(s)) - }) - }); - let Some(index) = found else { return -1 }; - let Some(source) = self.inventory[index].as_mut() else { - return -1; - }; - let taken = (count as u32).min(source.count); - let moved = ItemStack { - count: taken, - ..source.clone() - }; - source.count -= taken; - if source.count == 0 { - self.inventory[index] = None; - } - match self.slot_mut(slot) { - Some(existing) => existing.count += taken, - empty => *empty = Some(moved), - } - count - i64::from(taken) - } // ---- ghost recipe ---- diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 149e34cc0..da859aa9b 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -14,6 +14,8 @@ use crate::{ }; use std::sync::Arc; +pub mod place; + /// What a menu needs to know about items and recipes. pub struct Env<'a> { pub items: &'a Items, @@ -144,6 +146,8 @@ pub struct Menu { pub carried: Option, pub data: Vec, pub creative: bool, + /// The selected hotbar slot (`Inventory.selected`). + pub selected: usize, /// Dropped stacks (canonical text), `xp+N` and the like, in order. pub drops: Vec, /// The dropped stacks themselves, for the caller to throw. @@ -345,6 +349,7 @@ impl Menu { carried: None, data: vec![0; data], creative: false, + selected: 0, drops: Vec::new(), dropped: Vec::new(), quick_status: 0, @@ -818,13 +823,16 @@ impl Menu { /// `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)) + [self.selected, 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. diff --git a/crates/horizon-client/src/menu/place.rs b/crates/horizon-client/src/menu/place.rs new file mode 100644 index 000000000..97363c301 --- /dev/null +++ b/crates/horizon-client/src/menu/place.rs @@ -0,0 +1,706 @@ +//! `ServerPlaceRecipe`: what the server does with a recipe book click +//! (`ServerboundPlaceRecipePacket`) in the inventory, crafting table and +//! furnace menus, with `StackedContents`' exact matching of items to +//! ingredients (`RecipePicker`). `tools/test_place_recipe_parity.py` +//! compares every placement with vanilla's. +//! +//! Vanilla keeps the available items in a `Reference2IntOpenHashMap` keyed by +//! item holders, whose iteration order follows their identity hash codes: it +//! differs between runs of the game, and decides which of several fitting +//! items fills an ingredient. `Stacked` keeps an explicit order: the order +//! items were first counted, or one given (the harness passes the oracle's). +use super::{Env, GRID, Kind, MAIN, Menu, PLAYER, RESULT, split, tidy}; +use crate::{ + crafting::{Ingredient, Placement}, + items::ItemStack, +}; +use std::{collections::HashMap, sync::Arc}; + +/// `StackedContents>`: item counts in an iteration order. +#[derive(Clone, Debug, Default)] +pub struct Stacked { + keys: Vec>, + amounts: Vec, + index: HashMap, usize>, +} + +/// `Inventory.isUsableForCrafting`: not damaged, enchanted or renamed. +pub fn usable_for_crafting(stack: &ItemStack) -> bool { + stack.damage == 0 && stack.enchantments().is_empty() && stack.custom_name().is_none() +} + +impl Stacked { + /// `StackedContents.account`. + pub fn account(&mut self, item: &Arc, count: i32) { + match self.index.get(item) { + Some(&i) => self.amounts[i] += count, + None => { + self.index.insert(item.clone(), self.keys.len()); + self.keys.push(item.clone()); + self.amounts.push(count); + } + } + } + /// `StackedItemContents.accountStack(stack, maxCount)`. + pub fn account_stack(&mut self, stack: &ItemStack, max: u32) { + if stack.count > 0 { + self.account(&stack.item, stack.count.min(max) as i32); + } + } + /// `accountSimpleStack`. + pub fn account_simple(&mut self, stack: &ItemStack, max: u32) { + if usable_for_crafting(stack) { + self.account_stack(stack, max); + } + } + /// Reorders the keys: the given items first, in that order (vanilla's hash + /// map order for the same items), then the rest as they were. + pub fn set_order(&mut self, order: &[String]) { + let mut keys: Vec> = order + .iter() + .filter_map(|o| self.index.get_key_value(o.as_str()).map(|(k, _)| k.clone())) + .collect(); + for k in &self.keys { + if !keys.contains(k) { + keys.push(k.clone()); + } + } + let amounts = keys.iter().map(|k| self.amounts[self.index[k]]).collect(); + self.index = keys + .iter() + .cloned() + .enumerate() + .map(|(i, k)| (k, i)) + .collect(); + self.keys = keys; + self.amounts = amounts; + } + pub fn keys(&self) -> &[Arc] { + &self.keys + } + /// `canCraft(ingredients, null)` without touching the counts (the recipe + /// book's craftable test; the answer does not depend on the order). + pub fn can_craft(&self, ingredients: &[&Ingredient]) -> bool { + !ingredients.is_empty() && self.clone().try_pick(ingredients, 1, None) + } + /// `getResultUpperBound`. + fn upper_bound(&self, ingredients: &[&Ingredient]) -> i32 { + let mut min = i32::MAX; + 'ingredients: for ing in ingredients { + let mut max = 0; + for (key, &count) in self.keys.iter().zip(&self.amounts) { + if count > max { + if ing.0.contains(&**key) { + max = count; + } + if max >= min { + continue 'ingredients; + } + } + } + min = max; + if min == 0 { + break; + } + } + min + } + /// `tryPick` (`canCraft(recipe, amount, output)`). + pub fn try_pick( + &mut self, + ingredients: &[&Ingredient], + amount: i32, + output: Option<&mut Vec>>, + ) -> bool { + Picker::new(self, ingredients).try_pick(amount, output) + } + /// `tryPickAll` (`getBiggestCraftableStack`). + pub fn try_pick_all( + &mut self, + ingredients: &[&Ingredient], + max_size: i32, + output: Option<&mut Vec>>, + ) -> i32 { + Picker::new(self, ingredients).try_pick_all(max_size, output) + } +} + +/// `StackedContents.RecipePicker`: augmenting paths over item-ingredient pairs. +struct Picker<'a> { + stacked: &'a mut Stacked, + ingredients: Vec<&'a Ingredient>, + /// Indices into the stacked keys of the items any ingredient accepts. + items: Vec, + connection: Vec, + assigned: Vec, + satisfied: Vec, + visited_ingredient: Vec, + visited_item: Vec, + path: Vec, +} + +impl<'a> Picker<'a> { + fn new(stacked: &'a mut Stacked, ingredients: &[&'a Ingredient]) -> Self { + // getUniqueAvailableIngredientItems + let items: Vec = (0..stacked.keys.len()) + .filter(|&i| { + stacked.amounts[i] > 0 + && ingredients.iter().any(|g| g.0.contains(&*stacked.keys[i])) + }) + .collect(); + let (ni, nt) = (ingredients.len(), items.len()); + let mut connection = vec![false; ni * nt]; + for (g, ing) in ingredients.iter().enumerate() { + for (t, &key) in items.iter().enumerate() { + if ing.0.contains(&*stacked.keys[key]) { + connection[t * ni + g] = true; + } + } + } + Self { + stacked, + ingredients: ingredients.to_vec(), + items, + connection, + assigned: vec![false; ni * nt], + satisfied: vec![false; ni], + visited_ingredient: vec![false; ni], + visited_item: vec![false; nt], + path: Vec::new(), + } + } + fn at(&self, item: usize, ingredient: usize) -> usize { + item * self.ingredients.len() + ingredient + } + fn clear_visited(&mut self) { + self.visited_ingredient.fill(false); + self.visited_item.fill(false); + } + fn try_pick(&mut self, capacity: i32, mut output: Option<&mut Vec>>) -> bool { + if capacity <= 0 { + return true; + } + let mut satisfied_count = 0; + loop { + let Some(path) = self.try_assigning_new_item(capacity) else { + let valid = satisfied_count == self.ingredients.len(); + let has_output = valid && output.is_some(); + self.clear_visited(); + self.satisfied.fill(false); + for g in 0..self.ingredients.len() { + for t in 0..self.items.len() { + let at = self.at(t, g); + if self.assigned[at] { + self.assigned[at] = false; + let key = self.items[t]; + self.stacked.amounts[key] += capacity; + if has_output && let Some(out) = output.as_deref_mut() { + out.push(self.stacked.keys[key].clone()); + } + break; + } + } + } + return valid; + }; + let key = self.items[path[0]]; + self.stacked.amounts[key] -= capacity; + self.satisfied[path[path.len() - 1]] = true; + satisfied_count += 1; + for i in 0..path.len() - 1 { + if i & 1 == 0 { + let at = self.at(path[i], path[i + 1]); + self.assigned[at] = true; + } else { + let at = self.at(path[i + 1], path[i]); + self.assigned[at] = false; + } + } + } + } + fn try_assigning_new_item(&mut self, capacity: i32) -> Option> { + self.clear_visited(); + for t in 0..self.items.len() { + if self.stacked.amounts[self.items[t]] >= capacity + && let Some(path) = self.find_path(t) + { + return Some(path); + } + } + None + } + fn find_path(&mut self, start: usize) -> Option> { + self.path.clear(); + self.visited_item[start] = true; + self.path.push(start); + while !self.path.is_empty() { + let len = self.path.len(); + if (len - 1) & 1 == 0 { + let item = self.path[len - 1]; + for g in 0..self.ingredients.len() { + let at = self.at(item, g); + if !self.visited_ingredient[g] && self.connection[at] && !self.assigned[at] { + self.visited_ingredient[g] = true; + self.path.push(g); + break; + } + } + } else { + let ingredient = self.path[len - 1]; + if !self.satisfied[ingredient] { + return Some(self.path.clone()); + } + for t in 0..self.items.len() { + if !self.visited_item[t] && self.assigned[self.at(t, ingredient)] { + self.visited_item[t] = true; + self.path.push(t); + break; + } + } + } + if self.path.len() == len { + self.path.pop(); + } + } + None + } + fn try_pick_all(&mut self, max_size: i32, output: Option<&mut Vec>>) -> i32 { + let mut min = 0i32; + // Java int arithmetic: an empty ingredient list overflows as vanilla does. + let mut max = max_size + .min(self.stacked.upper_bound(&self.ingredients)) + .wrapping_add(1); + loop { + let mid = min.wrapping_add(max) / 2; + if self.try_pick(mid, None) { + if max.wrapping_sub(min) <= 1 { + if mid > 0 { + self.try_pick(mid, output); + } + return mid; + } + min = mid; + } else { + max = mid; + } + } + } +} + +/// `RecipeBookMenu.PostPlaceAction`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PostPlace { + Nothing, + /// The client shows the recipe as a ghost (`ClientboundPlaceGhostRecipePacket`). + Ghost, +} + +/// The menu slots a placement works on. +struct Grid { + width: usize, + height: usize, + /// `inputGridSlots` and `slotsToClear` as menu slot indices. + inputs: Vec, + clear: Vec, +} + +impl Menu { + fn place_grid(&self) -> Option { + match self.kind { + Kind::Inventory => Some(Grid { + width: 2, + height: 2, + inputs: (1..5).collect(), + clear: (1..5).collect(), + }), + Kind::Crafting => Some(Grid { + width: 3, + height: 3, + inputs: (1..10).collect(), + clear: (1..10).collect(), + }), + Kind::Furnace(_) => Some(Grid { + width: 1, + height: 1, + inputs: vec![0], + clear: vec![0, 2], + }), + _ => None, + } + } + + /// `Inventory.fillStackedContents` then the menu's + /// `fillCraftSlotsStackedContents`. + pub fn stacked_contents(&self, env: &Env) -> Stacked { + let mut stacked = Stacked::default(); + for stack in self.containers[PLAYER][..36].iter().flatten() { + stacked.account_simple(stack, Self::max_stack(env, stack)); + } + match self.kind { + // A furnace's SimpleContainer counts all three slots, unfiltered. + Kind::Furnace(_) => { + for stack in self.containers[MAIN].iter().flatten() { + stacked.account_stack(stack, Self::max_stack(env, stack)); + } + } + _ => { + for stack in self.containers[GRID].iter().flatten() { + stacked.account_simple(stack, Self::max_stack(env, stack)); + } + } + } + stacked + } + + /// `RecipeBookMenu.handlePlacement` for the recipe `id` + /// (`ServerPlaceRecipe.placeRecipe`). `allow_drop` is the player being in + /// creative; `order` the iteration order of the counted items, if known. + pub fn place_recipe( + &mut self, + env: &Env, + id: &str, + use_max: bool, + allow_drop: bool, + order: Option<&[String]>, + ) -> PostPlace { + let Some(grid) = self.place_grid() else { + return PostPlace::Nothing; + }; + let Some(placement) = env.recipes.placement(id) else { + return PostPlace::Nothing; + }; + if placement.impossible() { + return PostPlace::Nothing; + } + if !allow_drop && !self.test_clear_grid(env, &grid) { + return PostPlace::Nothing; + } + let mut stacked = self.stacked_contents(env); + if let Some(order) = order { + stacked.set_order(order); + } + let ingredients: Vec<&Ingredient> = placement.ingredients.iter().collect(); + let post = if stacked.try_pick(&ingredients, 1, None) { + self.place(env, id, &grid, &placement, &mut stacked, use_max); + PostPlace::Nothing + } else { + self.clear_grid(env, &grid); + PostPlace::Ghost + }; + // AbstractCraftingMenu.finishPlacingRecipe: the result follows the grid. + self.recompute(env); + post + } + + /// `recipeMatches`: the recipe already fills the grid. + fn recipe_in_grid(&self, env: &Env, id: &str) -> bool { + match self.kind { + Kind::Furnace(_) => { + let name = id.trim_start_matches("minecraft:"); + match ( + env.recipes.cooking.iter().find(|c| c.id == name), + self.containers[MAIN][0].as_ref(), + ) { + (Some(c), Some(input)) => c.ingredient.test(input), + _ => false, + } + } + _ => env + .recipes + .recipe_matches(id, &self.containers[GRID], self.grid_size), + } + } + + fn place( + &mut self, + env: &Env, + id: &str, + grid: &Grid, + placement: &Placement, + stacked: &mut Stacked, + use_max: bool, + ) { + let ingredients: Vec<&Ingredient> = placement.ingredients.iter().collect(); + let matches = self.recipe_in_grid(env, id); + let biggest = stacked.try_pick_all(&ingredients, i32::MAX, None); + if matches { + for &s in &grid.inputs { + if let Some(stack) = self.slot(s) + && (biggest.min(Self::max_stack(env, stack) as i32) as i64) + < i64::from(stack.count) + 1 + { + return; + } + } + } + // calculateAmountToCraft + let amount = if use_max { + biggest + } else if matches { + let smallest = grid + .inputs + .iter() + .filter_map(|&s| self.slot(s)) + .map(|s| s.count as i32) + .min(); + smallest.map_or(i32::MAX, |n| n + 1) + } else { + 1 + }; + let mut used = Vec::new(); + if !stacked.try_pick(&ingredients, amount, Some(&mut used)) { + return; + } + // clampToMaxStackSize + let adjusted = used.iter().fold(amount, |n, item| { + n.min(env.items.get(item).map_or(1, |i| i.max_stack) as i32) + }); + if adjusted != amount { + used.clear(); + if !stacked.try_pick(&ingredients, adjusted, Some(&mut used)) { + return; + } + } + self.clear_grid(env, grid); + let (w, h) = placement.shaped.unwrap_or((grid.width, grid.height)); + let slots: Vec = placement.slots.clone(); + for (ingredient, index) in + crate::recipe_book::place_cells(grid.width, grid.height, w, h, &slots) + { + if ingredient == -1 { + continue; + } + let target = grid.inputs[index]; + let item = used[ingredient as usize].clone(); + let mut remaining = adjusted; + while remaining > 0 { + remaining = self.move_item_to_grid(target, &item, remaining); + if remaining == -1 { + break; + } + } + } + } + + /// `moveItemToGrid`: the rest still to move, or -1 when nothing matches. + fn move_item_to_grid(&mut self, target: usize, item: &str, count: i32) -> i32 { + let existing = self.slot(target).cloned(); + let found = (0..36).find(|&i| { + self.containers[PLAYER][i].as_ref().is_some_and(|s| { + &*s.item == item + && usable_for_crafting(s) + && existing + .as_ref() + .is_none_or(|e| e.same_item_same_components(s)) + }) + }); + let Some(i) = found else { + return -1; + }; + let cell = &mut self.containers[PLAYER][i]; + let taken = match cell.as_mut() { + Some(have) if (count as u32) < have.count => split(have, count as u32), + _ => cell.take().expect("found"), + }; + tidy(cell); + let taken_count = taken.count as i32; + let slot = self.slots[target]; + match self.containers[slot.container][slot.index].as_mut() { + None => self.containers[slot.container][slot.index] = Some(taken), + Some(have) => have.count += taken.count, + } + count - taken_count + } + + /// `clearGrid`: the slots to clear go back to the inventory (or drop), + /// then the grid empties (`clearCraftingContent`). + fn clear_grid(&mut self, env: &Env, grid: &Grid) { + for &s in &grid.clear { + let slot = self.slots[s]; + if let Some(stack) = self.containers[slot.container][slot.index].clone() { + let mut copy = stack; + self.place_back(env, &mut copy); + } + } + match self.kind { + Kind::Furnace(_) => { + for &s in &grid.clear { + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = None; + } + } + _ => { + self.containers[GRID].fill(None); + self.containers[RESULT][0] = None; + } + } + } + + /// `Inventory.placeItemBackInInventory`. + fn place_back(&mut self, env: &Env, stack: &mut ItemStack) { + while stack.count > 0 { + let slot = self + .slot_with_space(env, stack) + .or_else(|| (0..36).find(|&i| self.containers[PLAYER][i].is_none())); + let Some(slot) = slot else { + let dropped = std::mem::replace( + stack, + ItemStack { + count: 0, + ..stack.clone() + }, + ); + self.drop_stack(&dropped); + break; + }; + let have = self.containers[PLAYER][slot] + .as_ref() + .map_or(0, |s| s.count); + let space = Self::max_stack(env, stack).saturating_sub(have); + let mut part = split(stack, space); + self.inventory_add_at(env, slot, &mut part); + } + } + + /// `Inventory.add(slot, stack)`. + fn inventory_add_at(&mut self, env: &Env, slot: usize, stack: &mut ItemStack) { + if stack.count == 0 { + return; + } + if Self::damageable(env, stack) && stack.damage > 0 { + self.containers[PLAYER][slot] = Some(stack.clone()); + stack.count = 0; + return; + } + loop { + let last = stack.count; + // addResource(slot, stack) + let cell = self.containers[PLAYER][slot].get_or_insert_with(|| ItemStack { + count: 0, + ..stack.clone() + }); + let room = super::CONTAINER_MAX + .min(Self::max_stack(env, cell)) + .saturating_sub(cell.count); + let add = stack.count.min(room); + cell.count += add; + stack.count -= add; + tidy(&mut self.containers[PLAYER][slot]); + if stack.count == 0 || stack.count >= last { + if stack.count == last && self.creative { + stack.count = 0; + } + return; + } + } + } + + /// `testClearGrid`: whether the inventory can take the grid back. + fn test_clear_grid(&self, env: &Env, grid: &Grid) -> bool { + let mut free_slots: Vec = Vec::new(); + let free_in_inventory = self.containers[PLAYER][..36] + .iter() + .filter(|s| s.is_none()) + .count(); + for &s in &grid.inputs { + let Some(mut stack) = self.slot(s).cloned() else { + continue; + }; + let with_space = self.slot_with_space(env, &stack); + if with_space.is_none() && free_slots.len() <= free_in_inventory { + for listed in &mut free_slots { + let max = Self::max_stack(env, listed); + if listed.item == stack.item + && listed.count != max + && listed.count + stack.count <= max + { + listed.count += stack.count; + stack.count = 0; + break; + } + } + if stack.count > 0 { + if free_slots.len() >= free_in_inventory { + return false; + } + free_slots.push(stack); + } + } else if with_space.is_none() { + return false; + } + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ing(items: &[&str]) -> Ingredient { + Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + } + fn have(items: &[(&str, i32)]) -> Stacked { + let mut s = Stacked::default(); + for (item, n) in items { + s.account(&Arc::from(*item), *n); + } + s + } + #[test] + fn a_single_item_can_fill_several_ingredients() { + let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]); + let reqs = [&planks, &planks, &planks, &planks]; + let mut a = have(&[("minecraft:oak_planks", 2), ("minecraft:birch_planks", 2)]); + assert!(a.can_craft(&reqs)); + // Two sets need 8 planks, but only 4 are there. + assert!(!a.try_pick(&reqs, 2, None)); + assert_eq!(a.try_pick_all(&reqs, i32::MAX, None), 1); + assert_eq!( + have(&[("minecraft:oak_planks", 64)]).try_pick_all(&reqs, i32::MAX, None), + 16 + ); + // Picking leaves the counts as they were. + assert!(a.try_pick(&reqs, 1, None)); + assert!(a.can_craft(&reqs)); + } + #[test] + fn the_matching_reassigns_flexible_ingredients() { + // The first ingredient takes either item, the second only the stick: + // the first item tried (the stick) moves over to free it. + let any = ing(&["minecraft:stick", "minecraft:bone"]); + let stick = ing(&["minecraft:stick"]); + let mut a = have(&[("minecraft:stick", 1), ("minecraft:bone", 1)]); + let mut used = Vec::new(); + assert!(a.try_pick(&[&any, &stick], 1, Some(&mut used))); + assert_eq!(&*used[0], "minecraft:bone"); + assert_eq!(&*used[1], "minecraft:stick"); + assert!(!have(&[("minecraft:stick", 1)]).can_craft(&[&any, &stick])); + } + #[test] + fn the_order_decides_between_fitting_items() { + let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]); + let mut a = have(&[("minecraft:oak_planks", 4), ("minecraft:birch_planks", 4)]); + let mut used = Vec::new(); + a.try_pick(&[&planks], 1, Some(&mut used)); + assert_eq!(&*used[0], "minecraft:oak_planks"); + a.set_order(&["minecraft:birch_planks".to_owned()]); + used.clear(); + a.try_pick(&[&planks], 1, Some(&mut used)); + assert_eq!(&*used[0], "minecraft:birch_planks"); + } + #[test] + fn damaged_or_named_stacks_are_not_counted() { + let mut named = ItemStack::new("minecraft:stick", 4); + named.data_mut().custom_name = Some("x".into()); + let mut damaged = ItemStack::new("minecraft:iron_sword", 1); + damaged.damage = 3; + let mut s = Stacked::default(); + for stack in [&named, &damaged, &ItemStack::new("minecraft:stick", 2)] { + s.account_simple(stack, 64); + } + assert_eq!(s.keys().len(), 1); + assert!(s.can_craft(&[&ing(&["minecraft:stick"]), &ing(&["minecraft:stick"])])); + assert!(!s.can_craft(&[&ing(&["minecraft:stick"]); 3])); + } +} diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 5c76b17c7..f86c34782 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -4,7 +4,7 @@ //! craftable stack), where a recipe goes in a grid (`PlaceRecipeHelper`) and //! the book's saved settings. use crate::{ - crafting::{Ingredient, Recipe, Recipes}, + crafting::{Ingredient, Placement, Recipe, Recipes}, items::{ItemStack, Items}, }; use horizon_world::nbt::Tag; @@ -245,6 +245,9 @@ pub struct Collection { #[derive(Default)] pub struct Book { pub entries: Vec, + /// `Recipe.placementInfo` by recipe id: what the book's craftable test + /// and the server's placement look for. + pub placements: HashMap, /// Item id -> registry position, to order ingredient choices. pub order: HashMap, } @@ -327,7 +330,15 @@ impl Book { .enumerate() .map(|(i, id)| (id.to_string(), i)) .collect(); - Self { entries, order } + let placements = entries + .iter() + .filter_map(|e| Some((e.id.clone(), recipes.placement(&e.id)?))) + .collect(); + Self { + entries, + placements, + order, + } } /// The unlocked recipes of one tab as collections (`ClientRecipeBook.rebuildCollections`). pub fn collections( @@ -380,6 +391,13 @@ impl Book { Category::SmokerFood => BookType::Smoker, }) } + /// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients can + /// all be found in `stock`. + pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool { + self.placements.get(&entry.id).is_some_and(|p| { + !p.impossible() && stock.can_craft(&p.ingredients.iter().collect::>()) + }) + } pub fn entry(&self, id: &str) -> Option<&Entry> { self.entries.iter().find(|e| e.id == id) } @@ -419,125 +437,6 @@ impl Book { } } -/// `StackedItemContents`: simple stacks (undamaged, unenchanted, unnamed) by item. -#[derive(Clone, Debug, Default)] -pub struct Available { - pub counts: HashMap, -} -impl Available { - /// `accountSimpleStack`. - pub fn add(&mut self, stack: &ItemStack) { - if stack.count > 0 - && stack.damage == 0 - && stack.enchantments().is_empty() - && stack.custom_name().is_none() - { - *self.counts.entry(stack.item.to_string()).or_default() += stack.count; - } - } - pub fn from_stacks<'a>(stacks: impl IntoIterator) -> Self { - let mut a = Self::default(); - for s in stacks { - a.add(s); - } - a - } - /// `StackedItemContents.canCraft(ingredients, null)`. - pub fn can_craft(&self, requirements: &[&Ingredient]) -> bool { - !requirements.is_empty() && pick(requirements, &self.counts, 1, &HashMap::new()).is_some() - } - /// `canCraft(recipe, amount, output)`: the item each ingredient uses when - /// `amount` sets can be made, preferring earlier registry items. - pub fn pick( - &self, - requirements: &[&Ingredient], - amount: u32, - order: &HashMap, - ) -> Option> { - pick(requirements, &self.counts, amount, order) - } - /// `getBiggestCraftableStack`: how many sets can be made, up to 99. - pub fn biggest_stack(&self, requirements: &[&Ingredient]) -> u32 { - if !self.can_craft(requirements) { - return 0; - } - let none = HashMap::new(); - let (mut lo, mut hi) = (1u32, 99u32); - while lo < hi { - let mid = (lo + hi).div_ceil(2); - if pick(requirements, &self.counts, mid, &none).is_some() { - lo = mid; - } else { - hi = mid - 1; - } - } - lo - } -} -/// Bipartite assignment of one item to each ingredient where an item can -/// serve `count / amount` ingredients. -fn pick( - requirements: &[&Ingredient], - counts: &HashMap, - amount: u32, - order: &HashMap, -) -> Option> { - let amount = amount.max(1); - let capacity = |item: &str| counts.get(item).copied().unwrap_or(0) / amount; - let candidates: Vec> = requirements - .iter() - .map(|ing| { - let mut v: Vec = ing.0.iter().filter(|i| capacity(i) > 0).cloned().collect(); - v.sort_by_key(|i| (order.get(i).copied().unwrap_or(usize::MAX), i.clone())); - v - }) - .collect(); - let mut used: HashMap> = HashMap::new(); - fn assign( - i: usize, - candidates: &[Vec], - used: &mut HashMap>, - visited: &mut Vec, - capacity: &dyn Fn(&str) -> u32, - ) -> bool { - for item in &candidates[i] { - if visited.contains(item) { - continue; - } - visited.push(item.clone()); - let holders = used.get(item).cloned().unwrap_or_default(); - if (holders.len() as u32) < capacity(item) { - used.entry(item.clone()).or_default().push(i); - return true; - } - for j in holders { - if assign(j, candidates, used, visited, capacity) { - // j moved elsewhere: drop it from this item and take its place. - if let Some(list) = used.get_mut(item) { - list.retain(|x| *x != j); - list.push(i); - } - return true; - } - } - } - false - } - for i in 0..requirements.len() { - let mut visited = Vec::new(); - if !assign(i, &candidates, &mut used, &mut visited, &capacity) { - return None; - } - } - let mut result = vec![String::new(); requirements.len()]; - for (item, holders) in used { - for i in holders { - result[i] = item.clone(); - } - } - Some(result) -} - /// The recipe book's saved state: the `recipeBook` compound of the player. #[derive(Clone, Debug, Default)] pub struct Settings { @@ -602,11 +501,6 @@ mod tests { fn ing(items: &[&str]) -> Ingredient { Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) } - fn have(items: &[(&str, u32)]) -> Available { - Available { - counts: items.iter().map(|(i, n)| ((*i).to_owned(), *n)).collect(), - } - } #[test] fn small_recipes_are_centred_in_the_grid() { // One ingredient in a 3x3 grid goes to the middle cell. @@ -631,46 +525,6 @@ mod tests { assert_eq!(small, vec![0]); } #[test] - fn a_single_item_can_fill_several_ingredients() { - let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]); - let reqs = [&planks, &planks, &planks, &planks]; - let a = have(&[("minecraft:oak_planks", 2), ("minecraft:birch_planks", 2)]); - assert!(a.can_craft(&reqs)); - let none = HashMap::new(); - // Two sets need 8 planks, but only 4 are there. - assert!(a.pick(&reqs, 2, &none).is_none()); - assert!(a.pick(&reqs, 1, &none).is_some()); - assert_eq!(a.biggest_stack(&reqs), 1); - assert_eq!( - have(&[("minecraft:oak_planks", 64)]).biggest_stack(&reqs), - 16 - ); - } - #[test] - fn the_matching_reassigns_flexible_ingredients() { - // The first ingredient takes either item, the second only the stick: - // one stick must not be wasted on the first. - let any = ing(&["minecraft:stick", "minecraft:bone"]); - let stick = ing(&["minecraft:stick"]); - let a = have(&[("minecraft:stick", 1), ("minecraft:bone", 1)]); - let mut order = HashMap::new(); - order.insert("minecraft:stick".to_owned(), 0); - order.insert("minecraft:bone".to_owned(), 1); - let picked = a.pick(&[&any, &stick], 1, &order).expect("matching"); - assert_eq!(picked, vec!["minecraft:bone", "minecraft:stick"]); - assert!(!have(&[("minecraft:stick", 1)]).can_craft(&[&any, &stick])); - } - #[test] - fn damaged_or_named_stacks_are_not_counted() { - let mut named = ItemStack::new("minecraft:stick", 4); - named.data_mut().custom_name = Some("x".into()); - let mut damaged = ItemStack::new("minecraft:iron_sword", 1); - damaged.damage = 3; - let a = Available::from_stacks([&named, &damaged, &ItemStack::new("minecraft:stick", 2)]); - assert_eq!(a.counts.get("minecraft:stick"), Some(&2)); - assert!(!a.counts.contains_key("minecraft:iron_sword")); - } - #[test] fn collections_group_recipes_of_a_category() { let entry = |id: &str, group: Option<&str>, category| Entry { id: id.into(), @@ -686,6 +540,7 @@ mod tests { entry("minecraft:c", None, Category::CraftingBuilding), entry("minecraft:d", Some("planks"), Category::CraftingMisc), ], + placements: HashMap::new(), order: HashMap::new(), }; let unlocked: BTreeSet = ["a", "b", "c", "d"] @@ -713,6 +568,7 @@ mod tests { display: Display::Shapeless(Vec::new()), result: ItemStack::new("minecraft:stick", 4), }], + placements: HashMap::new(), order: HashMap::new(), }; let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()]; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlaceRecipeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlaceRecipeOracle.java new file mode 100644 index 000000000..719390ed2 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlaceRecipeOracle.java @@ -0,0 +1,113 @@ +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.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.StackedContents; +import net.minecraft.world.entity.player.StackedItemContents; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeManager; + +/** + * Original oracle: the server side of a recipe book click. For each case a + * stand-in player (the menu oracle's) holds an inventory and opens the + * inventory, crafting table or a furnace menu with some grid contents; then + * RecipeBookMenu.handlePlacement (ServerPlaceRecipe) runs as + * ServerGamePacketListenerImpl.handlePlaceRecipe calls it, and every menu + * slot, the whole inventory, the drops and the post-place action are printed. + * + * The items available to the placement are kept in a hash map whose order + * follows identity hash codes; the order this run used (a replica built the + * same way iterates identically) goes to a second output for the Rust side. + */ +public final class VanillaPlaceRecipeOracle { + @SuppressWarnings("unchecked") + static List order(Inventory inv, RecipeBookMenu menu) throws Exception { + StackedItemContents contents = new StackedItemContents(); + inv.fillStackedContents(contents); + menu.fillCraftSlotsStackedContents(contents); + Field raw = StackedItemContents.class.getDeclaredField("raw"); + raw.setAccessible(true); + StackedContents> stacked = (StackedContents>) raw.get(contents); + List out = new ArrayList<>(); + for (var entry : it.unimi.dsi.fastutil.objects.Reference2IntMaps.fastIterable(stacked.amounts)) { + out.add(entry.getKey().unwrapKey().orElseThrow().identifier().toString()); + } + return out; + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + VanillaMenuOracle.unsafe = field.get(null); + VanillaMenuOracle.allocate = VanillaMenuOracle.unsafe.getClass().getMethod("allocateInstance", Class.class); + RecipeManager recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + VanillaMenuOracle.recipes = recipes; + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var orders = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + List order = List.of(); + try { + VanillaMenuOracle.drops.clear(); + var world = VanillaMenuOracle.make(VanillaMenuOracle.World.class); + world.server = VanillaMenuOracle.make(VanillaMenuOracle.Server.class); + var player = VanillaMenuOracle.make(VanillaMenuOracle.FakePlayer.class); + player.world = world; + player.creative = f.get("creative").getAsBoolean(); + player.advancements = VanillaMenuOracle.make(net.minecraft.server.PlayerAdvancements.class); + VanillaMenuOracle.set(player.advancements, net.minecraft.server.PlayerAdvancements.class, "activeTriggers", new IdentityHashMap<>()); + VanillaMenuOracle.set(player, ServerPlayer.class, "connection", VanillaMenuOracle.make(VanillaMenuOracle.Connection.class)); + var inv = new Inventory(player, new EntityEquipment()); + player.inv = inv; + for (var pair : f.getAsJsonArray("inventory")) { + var p = pair.getAsJsonArray(); + inv.setItem(p.get(0).getAsInt(), ParityData.stack(p.get(1).getAsString())); + } + inv.setSelectedSlot(f.get("selected").getAsInt()); + AbstractContainerMenu menu = VanillaMenuOracle.menu(f.get("menu").getAsString(), player, inv); + VanillaMenuOracle.set(player, Player.class, "containerMenu", menu); + if (menu instanceof InventoryMenu im) VanillaMenuOracle.set(player, Player.class, "inventoryMenu", im); + for (var pair : f.getAsJsonArray("grid")) { + var p = pair.getAsJsonArray(); + menu.getSlot(p.get(0).getAsInt()).set(ParityData.stack(p.get(1).getAsString())); + } + VanillaMenuOracle.drops.clear(); + RecipeBookMenu book = (RecipeBookMenu) menu; + order = order(inv, book); + RecipeHolder recipe = recipes.byKey(ResourceKey.create(Registries.RECIPE, Identifier.parse(f.get("recipe").getAsString()))).orElseThrow(); + String post = "-"; + // ServerGamePacketListenerImpl.handlePlaceRecipe + if (!recipe.value().placementInfo().isImpossibleToPlace()) { + post = book.handlePlacement(f.get("max").getAsBoolean(), player.isCreative(), recipe, world, inv).name(); + } + StringBuilder line2 = new StringBuilder("post " + post + " | "); + line2.append(VanillaMenuOracle.state(menu, inv)).append(" | inv"); + for (int i = 0; i < 41; i++) line2.append(' ').append(ParityData.canon(inv.getItem(i))); + out.println(line2); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + orders.println(String.join(" ", order)); + } + } + } +} diff --git a/tools/test_place_recipe_parity.py b/tools/test_place_recipe_parity.py new file mode 100644 index 000000000..405ad8009 --- /dev/null +++ b/tools/test_place_recipe_parity.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""Compare the server side of recipe book clicks with vanilla's ServerPlaceRecipe. + +Each case opens the inventory, a crafting table or a furnace (smelting, +blasting, smoking) on a player whose inventory holds the items of a random +recipe of the book (shaped, shapeless, transmuting, dyeing, imbuing and +cooking recipes), with more or fewer than needed, damaged, enchanted and +renamed copies the book must not use, junk, and sometimes a nearly full +inventory; the grid is empty, holds the same recipe already (placing again +adds one set, or a full stack with shift) or something else. The Java oracle +(VanillaPlaceRecipeOracle) runs RecipeBookMenu.handlePlacement as the server's +packet handler does; examples/place_recipe_fixture runs +horizon_client::menu's place_recipe. Every menu slot, the whole inventory, +the drops and whether the client gets a ghost recipe are compared. + +Vanilla counts the available items in a hash map ordered by identity hash +codes, an order that changes between runs and decides which of several +fitting items fills an ingredient; the oracle writes the order its run used +and the Rust side follows it. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, test_crafter_parity as crafter +except ImportError: + import interaction_lab as lib + import test_crafter_parity as crafter + +GRIDS = {'inventory': 2, 'crafting': 3} +COOKING = {'furnace': 'minecraft:smelting', 'blast_furnace': 'minecraft:blasting', 'smoker': 'minecraft:smoking'} +CRAFTING_TYPES = ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless', 'minecraft:crafting_transmute', + 'minecraft:crafting_dye', 'minecraft:crafting_imbue') +JUNK = ['minecraft:dirt', 'minecraft:stone', 'minecraft:diamond', 'minecraft:stick', 'minecraft:oak_planks', + 'minecraft:apple', 'minecraft:feather', 'minecraft:coal', 'minecraft:iron_ingot', 'minecraft:cobblestone'] + + +def stack(item, count, kind=None, rng=None): + comps = [] + if kind == 'damaged': + comps.append('"minecraft:damage":%d' % rng.randrange(1, 30)) + elif kind == 'enchanted': + comps.append('"minecraft:enchantments":{"minecraft:unbreaking":1}') + elif kind == 'named': + comps.append('"minecraft:custom_name":"x"') + body = ',components:{%s}' % ','.join(comps) if comps else '' + return '{id:"%s",count:%d%s}' % (item, count, body) + + +class Gen: + def __init__(self, rng, items, recipes): + self.rng = rng + self.items = items + self.recipes = recipes + self.by_type = {} + for name, r in recipes.recipes.items(): + self.by_type.setdefault(r['type'], []).append(name) + + def top(self, item): + return self.items.get(item, {}).get('minecraft:max_stack_size', 64) + + def ingredients(self, r): + """Each ingredient's item choices, as PlacementInfo lists them.""" + t = r['type'] + if t == 'minecraft:crafting_shaped': + return [self.recipes.choices(r['key'][ch]) for row in r['pattern'] for ch in row if ch != ' '] + if t == 'minecraft:crafting_shapeless': + return [self.recipes.choices(i) for i in r['ingredients']] + if t == 'minecraft:crafting_transmute': + n = r.get('material_count', {}) + top = n.get('max', 1) if isinstance(n, dict) else n + return [self.recipes.choices(r['input'])] + [self.recipes.choices(r['material'])] * top + if t == 'minecraft:crafting_dye': + return [self.recipes.choices(r['target']), self.recipes.choices(r['dye'])] + if t == 'minecraft:crafting_imbue': + return [self.recipes.choices(r['material'])] * 8 + [self.recipes.choices(r['source'])] + return [self.recipes.choices(r['ingredient'])] + + def fits(self, r, size): + t = r['type'] + if t == 'minecraft:crafting_shaped': + return len(r['pattern']) <= size and max(len(row) for row in r['pattern']) <= size + return len(self.ingredients(r)) <= size * size + + def case(self, menu): + rng = self.rng + if menu in COOKING: + name = rng.choice(self.by_type.get(COOKING[menu], [])) + else: + size = GRIDS[menu] + pool = [n for t in CRAFTING_TYPES for n in self.by_type.get(t, [])] + for _ in range(50): + name = rng.choice(pool) + if self.fits(self.recipes.recipes[name], size): + break + r = self.recipes.recipes[name] + ingredients = self.ingredients(r) + inventory = {} + free = list(range(36)) + rng.shuffle(free) + + def put(item_stack): + if free: + inventory[free.pop()] = item_stack + for choices in ingredients: + if not choices or rng.random() < 0.08: + continue + for item in rng.sample(choices, min(len(choices), rng.choice([1, 1, 1, 2, 3]))): + top = self.top(item) + for _ in range(rng.choice([1, 1, 1, 2, 3])): + count = 1 if top == 1 else rng.choice([1, 1, 2, 3, 7, top, top - 1, rng.randrange(1, top + 1)]) + kind = rng.choice([None] * 12 + ['damaged', 'enchanted', 'named']) + if kind == 'damaged' and not self.items.get(item, {}).get('minecraft:max_damage'): + kind = None + put(stack(item, max(1, count), kind, rng)) + fill = rng.choice([0, 0, 3, 8, 30, 36]) + for _ in range(fill): + item = rng.choice(JUNK) + put(stack(item, rng.choice([1, 16, 64, self.top(item)]))) + if rng.random() < 0.15: + inventory[40] = stack(rng.choice(JUNK + [c[0] for c in ingredients if c]), rng.choice([1, 5, 64])) + grid = [] + roll = rng.random() + if menu in COOKING: + if roll < 0.3: + grid.append([0, stack(rng.choice(ingredients[0]), rng.choice([1, 3, 64]))]) + elif roll < 0.5: + grid.append([0, stack(rng.choice(JUNK), rng.choice([1, 64]))]) + if rng.random() < 0.4: + grid.append([1, stack('minecraft:coal', rng.choice([1, 64]))]) + if rng.random() < 0.4: + result = r['result']['id'] if isinstance(r['result'], dict) else r['result'] + grid.append([2, stack(rng.choice([result, 'minecraft:stone']), rng.choice([1, 5, 64]))]) + else: + size = GRIDS[menu] + if roll < 0.35: + # The same recipe already in the grid (a placed or crafted set). + cells = self.recipes.grid(rng, name) if size == 3 else None + if cells is None: + cells = [None] * 9 + for i, choices in enumerate(ingredients[:size * size]): + if choices: + cells[(i // size) * 3 + i % size] = rng.choice(choices).split(':')[1] + for i, cell in enumerate(cells): + x, y = i % 3, i // 3 + if cell and x < size and y < size: + item = 'minecraft:' + cell + grid.append([1 + x + y * size, stack(item, rng.choice([1, 1, 2, 5, self.top(item)]))]) + elif roll < 0.6: + for i in range(size * size): + if rng.random() < 0.4: + grid.append([1 + i, stack(rng.choice(JUNK), rng.choice([1, 3, 64]))]) + return {'menu': menu, 'recipe': 'minecraft:' + name, 'max': rng.random() < 0.5, 'creative': rng.random() < 0.2, + 'selected': rng.randrange(9), 'inventory': sorted([k, v] for k, v in inventory.items()), 'grid': grid} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=11) + parser.add_argument('--cases', type=int, default=6000) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + work = lib.work_dir('place-recipe-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaMenuOracle', 'VanillaPlaceRecipeOracle') + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + gen = Gen(random.Random(args.seed), items, crafter.Recipes(lib.RESOURCES)) + menus = ['inventory', 'crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'] + cases = [gen.case(menus[n % len(menus)]) for n in range(args.cases)] + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + vanilla.run('VanillaPlaceRecipeOracle', work / 'cases.jsonl', work / 'native.txt', work / 'orders.txt') + lib.cargo_example('horizon-client', 'place_recipe_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'orders.txt', + work / 'rust.txt') + bad = lib.compare(cases, work / 'native.txt', work / 'rust.txt', + lambda case, line: f'{case["menu"]} {line.split(" ")[1] if line.startswith("post") else "error"}', + limit=args.limit) + errors = sum(1 for line in (work / 'native.txt').read_text().splitlines() if line.startswith('error-case')) + if errors: + print(f'{errors} oracle errors') + raise SystemExit(1 if bad or errors else 0) + + +if __name__ == '__main__': + main()